babylon.no-module.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. /**
  1242. * Gather the list of keyboard event types as constants.
  1243. */
  1244. var KeyboardEventTypes = /** @class */ (function () {
  1245. function KeyboardEventTypes() {
  1246. }
  1247. /**
  1248. * The keydown event is fired when a key becomes active (pressed).
  1249. */
  1250. KeyboardEventTypes.KEYDOWN = 0x01;
  1251. /**
  1252. * The keyup event is fired when a key has been released.
  1253. */
  1254. KeyboardEventTypes.KEYUP = 0x02;
  1255. return KeyboardEventTypes;
  1256. }());
  1257. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1258. /**
  1259. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1260. */
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. /**
  1263. * Instantiates a new keyboard info.
  1264. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1265. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1266. * @param event Defines the related dom event
  1267. */
  1268. function KeyboardInfo(
  1269. /**
  1270. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1271. */
  1272. type,
  1273. /**
  1274. * Defines the related dom event
  1275. */
  1276. event) {
  1277. this.type = type;
  1278. this.event = event;
  1279. }
  1280. return KeyboardInfo;
  1281. }());
  1282. BABYLON.KeyboardInfo = KeyboardInfo;
  1283. /**
  1284. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1285. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1286. */
  1287. var KeyboardInfoPre = /** @class */ (function (_super) {
  1288. __extends(KeyboardInfoPre, _super);
  1289. /**
  1290. * Instantiates a new keyboard pre info.
  1291. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfoPre(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. var _this = _super.call(this, type, event) || this;
  1305. _this.type = type;
  1306. _this.event = event;
  1307. _this.skipOnPointerObservable = false;
  1308. return _this;
  1309. }
  1310. return KeyboardInfoPre;
  1311. }(KeyboardInfo));
  1312. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1313. })(BABYLON || (BABYLON = {}));
  1314. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1315. var BABYLON;
  1316. (function (BABYLON) {
  1317. /**
  1318. * Gather the list of pointer event types as constants.
  1319. */
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. /**
  1324. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1325. */
  1326. PointerEventTypes.POINTERDOWN = 0x01;
  1327. /**
  1328. * The pointerup event is fired when a pointer is no longer active.
  1329. */
  1330. PointerEventTypes.POINTERUP = 0x02;
  1331. /**
  1332. * The pointermove event is fired when a pointer changes coordinates.
  1333. */
  1334. PointerEventTypes.POINTERMOVE = 0x04;
  1335. /**
  1336. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1337. */
  1338. PointerEventTypes.POINTERWHEEL = 0x08;
  1339. /**
  1340. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1341. */
  1342. PointerEventTypes.POINTERPICK = 0x10;
  1343. /**
  1344. * The pointertap event is fired when a the object has been touched and released without drag.
  1345. */
  1346. PointerEventTypes.POINTERTAP = 0x20;
  1347. /**
  1348. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1349. */
  1350. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1351. return PointerEventTypes;
  1352. }());
  1353. BABYLON.PointerEventTypes = PointerEventTypes;
  1354. /**
  1355. * Base class of pointer info types.
  1356. */
  1357. var PointerInfoBase = /** @class */ (function () {
  1358. /**
  1359. * Instantiates the base class of pointers info.
  1360. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1361. * @param event Defines the related dom event
  1362. */
  1363. function PointerInfoBase(
  1364. /**
  1365. * Defines the type of event (BABYLON.PointerEventTypes)
  1366. */
  1367. type,
  1368. /**
  1369. * Defines the related dom event
  1370. */
  1371. event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. /**
  1385. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1386. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1387. * @param event Defines the related dom event
  1388. * @param localX Defines the local x coordinates of the pointer when the event occured
  1389. * @param localY Defines the local y coordinates of the pointer when the event occured
  1390. */
  1391. function PointerInfoPre(type, event, localX, localY) {
  1392. var _this = _super.call(this, type, event) || this;
  1393. /**
  1394. * Ray from a pointer if availible (eg. 6dof controller)
  1395. */
  1396. _this.ray = null;
  1397. _this.skipOnPointerObservable = false;
  1398. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1399. return _this;
  1400. }
  1401. return PointerInfoPre;
  1402. }(PointerInfoBase));
  1403. BABYLON.PointerInfoPre = PointerInfoPre;
  1404. /**
  1405. * This type contains all the data related to a pointer event in Babylon.js.
  1406. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1407. */
  1408. var PointerInfo = /** @class */ (function (_super) {
  1409. __extends(PointerInfo, _super);
  1410. /**
  1411. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1412. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1413. * @param event Defines the related dom event
  1414. * @param pickInfo Defines the picking info associated to the info (if any)\
  1415. */
  1416. function PointerInfo(type, event,
  1417. /**
  1418. * Defines the picking info associated to the info (if any)\
  1419. */
  1420. pickInfo) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. _this.pickInfo = pickInfo;
  1423. return _this;
  1424. }
  1425. return PointerInfo;
  1426. }(PointerInfoBase));
  1427. BABYLON.PointerInfo = PointerInfo;
  1428. })(BABYLON || (BABYLON = {}));
  1429. //# sourceMappingURL=babylon.pointerEvents.js.map
  1430. var BABYLON;
  1431. (function (BABYLON) {
  1432. /**
  1433. * Constant used to convert a value to gamma space
  1434. * @ignorenaming
  1435. */
  1436. BABYLON.ToGammaSpace = 1 / 2.2;
  1437. /**
  1438. * Constant used to convert a value to linear space
  1439. * @ignorenaming
  1440. */
  1441. BABYLON.ToLinearSpace = 2.2;
  1442. /**
  1443. * Constant used to define the minimal number value in Babylon.js
  1444. * @ignorenaming
  1445. */
  1446. BABYLON.Epsilon = 0.001;
  1447. /**
  1448. * Class used to hold a RBG color
  1449. */
  1450. var Color3 = /** @class */ (function () {
  1451. /**
  1452. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1453. * @param r defines the red component (between 0 and 1, default is 0)
  1454. * @param g defines the green component (between 0 and 1, default is 0)
  1455. * @param b defines the blue component (between 0 and 1, default is 0)
  1456. */
  1457. function Color3(
  1458. /**
  1459. * Defines the red component (between 0 and 1, default is 0)
  1460. */
  1461. r,
  1462. /**
  1463. * Defines the green component (between 0 and 1, default is 0)
  1464. */
  1465. g,
  1466. /**
  1467. * Defines the blue component (between 0 and 1, default is 0)
  1468. */
  1469. b) {
  1470. if (r === void 0) { r = 0; }
  1471. if (g === void 0) { g = 0; }
  1472. if (b === void 0) { b = 0; }
  1473. this.r = r;
  1474. this.g = g;
  1475. this.b = b;
  1476. }
  1477. /**
  1478. * Creates a string with the Color3 current values
  1479. * @returns the string representation of the Color3 object
  1480. */
  1481. Color3.prototype.toString = function () {
  1482. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1483. };
  1484. /**
  1485. * Returns the string "Color3"
  1486. * @returns "Color3"
  1487. */
  1488. Color3.prototype.getClassName = function () {
  1489. return "Color3";
  1490. };
  1491. /**
  1492. * Compute the Color3 hash code
  1493. * @returns an unique number that can be used to hash Color3 objects
  1494. */
  1495. Color3.prototype.getHashCode = function () {
  1496. var hash = this.r || 0;
  1497. hash = (hash * 397) ^ (this.g || 0);
  1498. hash = (hash * 397) ^ (this.b || 0);
  1499. return hash;
  1500. };
  1501. // Operators
  1502. /**
  1503. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1504. * @param array defines the array where to store the r,g,b components
  1505. * @param index defines an optional index in the target array to define where to start storing values
  1506. * @returns the current Color3 object
  1507. */
  1508. Color3.prototype.toArray = function (array, index) {
  1509. if (index === undefined) {
  1510. index = 0;
  1511. }
  1512. array[index] = this.r;
  1513. array[index + 1] = this.g;
  1514. array[index + 2] = this.b;
  1515. return this;
  1516. };
  1517. /**
  1518. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1519. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1520. * @returns a new {BABYLON.Color4} object
  1521. */
  1522. Color3.prototype.toColor4 = function (alpha) {
  1523. if (alpha === void 0) { alpha = 1; }
  1524. return new Color4(this.r, this.g, this.b, alpha);
  1525. };
  1526. /**
  1527. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1528. * @returns the new array
  1529. */
  1530. Color3.prototype.asArray = function () {
  1531. var result = new Array();
  1532. this.toArray(result, 0);
  1533. return result;
  1534. };
  1535. /**
  1536. * Returns the luminance value
  1537. * @returns a float value
  1538. */
  1539. Color3.prototype.toLuminance = function () {
  1540. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1541. };
  1542. /**
  1543. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1544. * @param otherColor defines the second operand
  1545. * @returns the new Color3 object
  1546. */
  1547. Color3.prototype.multiply = function (otherColor) {
  1548. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1549. };
  1550. /**
  1551. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1552. * @param otherColor defines the second operand
  1553. * @param result defines the Color3 object where to store the result
  1554. * @returns the current Color3
  1555. */
  1556. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1557. result.r = this.r * otherColor.r;
  1558. result.g = this.g * otherColor.g;
  1559. result.b = this.b * otherColor.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Determines equality between Color3 objects
  1564. * @param otherColor defines the second operand
  1565. * @returns true if the rgb values are equal to the given ones
  1566. */
  1567. Color3.prototype.equals = function (otherColor) {
  1568. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1569. };
  1570. /**
  1571. * Determines equality between the current Color3 object and a set of r,b,g values
  1572. * @param r defines the red component to check
  1573. * @param g defines the green component to check
  1574. * @param b defines the blue component to check
  1575. * @returns true if the rgb values are equal to the given ones
  1576. */
  1577. Color3.prototype.equalsFloats = function (r, g, b) {
  1578. return this.r === r && this.g === g && this.b === b;
  1579. };
  1580. /**
  1581. * Multiplies in place each rgb value by scale
  1582. * @param scale defines the scaling factor
  1583. * @returns the updated Color3
  1584. */
  1585. Color3.prototype.scale = function (scale) {
  1586. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1587. };
  1588. /**
  1589. * Multiplies the rgb values by scale and stores the result into "result"
  1590. * @param scale defines the scaling factor
  1591. * @param result defines the Color3 object where to store the result
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.scaleToRef = function (scale, result) {
  1595. result.r = this.r * scale;
  1596. result.g = this.g * scale;
  1597. result.b = this.b * scale;
  1598. return this;
  1599. };
  1600. /**
  1601. * Scale the current Color3 values by a factor and add the result to a given Color3
  1602. * @param scale defines the scale factor
  1603. * @param result defines color to store the result into
  1604. * @returns the unmodified current Color3
  1605. */
  1606. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1607. result.r += this.r * scale;
  1608. result.g += this.g * scale;
  1609. result.b += this.b * scale;
  1610. return this;
  1611. };
  1612. /**
  1613. * Clamps the rgb values by the min and max values and stores the result into "result"
  1614. * @param min defines minimum clamping value (default is 0)
  1615. * @param max defines maximum clamping value (default is 1)
  1616. * @param result defines color to store the result into
  1617. * @returns the original Color3
  1618. */
  1619. Color3.prototype.clampToRef = function (min, max, result) {
  1620. if (min === void 0) { min = 0; }
  1621. if (max === void 0) { max = 1; }
  1622. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1623. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1624. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1625. return this;
  1626. };
  1627. /**
  1628. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1629. * @param otherColor defines the second operand
  1630. * @returns the new Color3
  1631. */
  1632. Color3.prototype.add = function (otherColor) {
  1633. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1634. };
  1635. /**
  1636. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1637. * @param otherColor defines the second operand
  1638. * @param result defines Color3 object to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.addToRef = function (otherColor, result) {
  1642. result.r = this.r + otherColor.r;
  1643. result.g = this.g + otherColor.g;
  1644. result.b = this.b + otherColor.b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1649. * @param otherColor defines the second operand
  1650. * @returns the new Color3
  1651. */
  1652. Color3.prototype.subtract = function (otherColor) {
  1653. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1654. };
  1655. /**
  1656. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1657. * @param otherColor defines the second operand
  1658. * @param result defines Color3 object to store the result into
  1659. * @returns the unmodified current Color3
  1660. */
  1661. Color3.prototype.subtractToRef = function (otherColor, result) {
  1662. result.r = this.r - otherColor.r;
  1663. result.g = this.g - otherColor.g;
  1664. result.b = this.b - otherColor.b;
  1665. return this;
  1666. };
  1667. /**
  1668. * Copy the current object
  1669. * @returns a new Color3 copied the current one
  1670. */
  1671. Color3.prototype.clone = function () {
  1672. return new Color3(this.r, this.g, this.b);
  1673. };
  1674. /**
  1675. * Copies the rgb values from the source in the current Color3
  1676. * @param source defines the source Color3 object
  1677. * @returns the updated Color3 object
  1678. */
  1679. Color3.prototype.copyFrom = function (source) {
  1680. this.r = source.r;
  1681. this.g = source.g;
  1682. this.b = source.b;
  1683. return this;
  1684. };
  1685. /**
  1686. * Updates the Color3 rgb values from the given floats
  1687. * @param r defines the red component to read from
  1688. * @param g defines the green component to read from
  1689. * @param b defines the blue component to read from
  1690. * @returns the current Color3 object
  1691. */
  1692. Color3.prototype.copyFromFloats = function (r, g, b) {
  1693. this.r = r;
  1694. this.g = g;
  1695. this.b = b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Updates the Color3 rgb values from the given floats
  1700. * @param r defines the red component to read from
  1701. * @param g defines the green component to read from
  1702. * @param b defines the blue component to read from
  1703. * @returns the current Color3 object
  1704. */
  1705. Color3.prototype.set = function (r, g, b) {
  1706. return this.copyFromFloats(r, g, b);
  1707. };
  1708. /**
  1709. * Compute the Color3 hexadecimal code as a string
  1710. * @returns a string containing the hexadecimal representation of the Color3 object
  1711. */
  1712. Color3.prototype.toHexString = function () {
  1713. var intR = (this.r * 255) | 0;
  1714. var intG = (this.g * 255) | 0;
  1715. var intB = (this.b * 255) | 0;
  1716. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1717. };
  1718. /**
  1719. * Computes a new Color3 converted from the current one to linear space
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.prototype.toLinearSpace = function () {
  1723. var convertedColor = new Color3();
  1724. this.toLinearSpaceToRef(convertedColor);
  1725. return convertedColor;
  1726. };
  1727. /**
  1728. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1729. * @param convertedColor defines the Color3 object where to store the linear space version
  1730. * @returns the unmodified Color3
  1731. */
  1732. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1733. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1734. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1735. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1736. return this;
  1737. };
  1738. /**
  1739. * Computes a new Color3 converted from the current one to gamma space
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.prototype.toGammaSpace = function () {
  1743. var convertedColor = new Color3();
  1744. this.toGammaSpaceToRef(convertedColor);
  1745. return convertedColor;
  1746. };
  1747. /**
  1748. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1749. * @param convertedColor defines the Color3 object where to store the gamma space version
  1750. * @returns the unmodified Color3
  1751. */
  1752. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1753. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1754. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1755. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1756. return this;
  1757. };
  1758. // Statics
  1759. /**
  1760. * Creates a new Color3 from the string containing valid hexadecimal values
  1761. * @param hex defines a string containing valid hexadecimal values
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromHexString = function (hex) {
  1765. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1766. return new Color3(0, 0, 0);
  1767. }
  1768. var r = parseInt(hex.substring(1, 3), 16);
  1769. var g = parseInt(hex.substring(3, 5), 16);
  1770. var b = parseInt(hex.substring(5, 7), 16);
  1771. return Color3.FromInts(r, g, b);
  1772. };
  1773. /**
  1774. * Creates a new Vector3 from the starting index of the given array
  1775. * @param array defines the source array
  1776. * @param offset defines an offset in the source array
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.FromArray = function (array, offset) {
  1780. if (offset === void 0) { offset = 0; }
  1781. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1782. };
  1783. /**
  1784. * Creates a new Color3 from integer values (< 256)
  1785. * @param r defines the red component to read from (value between 0 and 255)
  1786. * @param g defines the green component to read from (value between 0 and 255)
  1787. * @param b defines the blue component to read from (value between 0 and 255)
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.FromInts = function (r, g, b) {
  1791. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1792. };
  1793. /**
  1794. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1795. * @param start defines the start Color3 value
  1796. * @param end defines the end Color3 value
  1797. * @param amount defines the gradient value between start and end
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Lerp = function (start, end, amount) {
  1801. var result = new Color3(0.0, 0.0, 0.0);
  1802. Color3.LerpToRef(start, end, amount, result);
  1803. return result;
  1804. };
  1805. /**
  1806. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1807. * @param left defines the start value
  1808. * @param right defines the end value
  1809. * @param amount defines the gradient factor
  1810. * @param result defines the Color3 object where to store the result
  1811. */
  1812. Color3.LerpToRef = function (left, right, amount, result) {
  1813. result.r = left.r + ((right.r - left.r) * amount);
  1814. result.g = left.g + ((right.g - left.g) * amount);
  1815. result.b = left.b + ((right.b - left.b) * amount);
  1816. };
  1817. /**
  1818. * Returns a Color3 value containing a red color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Red = function () { return new Color3(1, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a green color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Green = function () { return new Color3(0, 1, 0); };
  1827. /**
  1828. * Returns a Color3 value containing a blue color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1832. /**
  1833. * Returns a Color3 value containing a black color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Black = function () { return new Color3(0, 0, 0); };
  1837. /**
  1838. * Returns a Color3 value containing a white color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.White = function () { return new Color3(1, 1, 1); };
  1842. /**
  1843. * Returns a Color3 value containing a purple color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a magenta color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a yellow color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a gray color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1862. /**
  1863. * Returns a Color3 value containing a teal color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1867. /**
  1868. * Returns a Color3 value containing a random color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1872. return Color3;
  1873. }());
  1874. BABYLON.Color3 = Color3;
  1875. /**
  1876. * Class used to hold a RBGA color
  1877. */
  1878. var Color4 = /** @class */ (function () {
  1879. /**
  1880. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1881. * @param r defines the red component (between 0 and 1, default is 0)
  1882. * @param g defines the green component (between 0 and 1, default is 0)
  1883. * @param b defines the blue component (between 0 and 1, default is 0)
  1884. * @param a defines the alpha component (between 0 and 1, default is 1)
  1885. */
  1886. function Color4(
  1887. /**
  1888. * Defines the red component (between 0 and 1, default is 0)
  1889. */
  1890. r,
  1891. /**
  1892. * Defines the green component (between 0 and 1, default is 0)
  1893. */
  1894. g,
  1895. /**
  1896. * Defines the blue component (between 0 and 1, default is 0)
  1897. */
  1898. b,
  1899. /**
  1900. * Defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. a) {
  1903. if (r === void 0) { r = 0; }
  1904. if (g === void 0) { g = 0; }
  1905. if (b === void 0) { b = 0; }
  1906. if (a === void 0) { a = 1; }
  1907. this.r = r;
  1908. this.g = g;
  1909. this.b = b;
  1910. this.a = a;
  1911. }
  1912. // Operators
  1913. /**
  1914. * Adds in place the given Color4 values to the current Color4 object
  1915. * @param right defines the second operand
  1916. * @returns the current updated Color4 object
  1917. */
  1918. Color4.prototype.addInPlace = function (right) {
  1919. this.r += right.r;
  1920. this.g += right.g;
  1921. this.b += right.b;
  1922. this.a += right.a;
  1923. return this;
  1924. };
  1925. /**
  1926. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1927. * @returns the new array
  1928. */
  1929. Color4.prototype.asArray = function () {
  1930. var result = new Array();
  1931. this.toArray(result, 0);
  1932. return result;
  1933. };
  1934. /**
  1935. * Stores from the starting index in the given array the Color4 successive values
  1936. * @param array defines the array where to store the r,g,b components
  1937. * @param index defines an optional index in the target array to define where to start storing values
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.toArray = function (array, index) {
  1941. if (index === undefined) {
  1942. index = 0;
  1943. }
  1944. array[index] = this.r;
  1945. array[index + 1] = this.g;
  1946. array[index + 2] = this.b;
  1947. array[index + 3] = this.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1952. * @param right defines the second operand
  1953. * @returns a new Color4 object
  1954. */
  1955. Color4.prototype.add = function (right) {
  1956. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1957. };
  1958. /**
  1959. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1960. * @param right defines the second operand
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.subtract = function (right) {
  1964. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1965. };
  1966. /**
  1967. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1968. * @param right defines the second operand
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current Color4 object
  1971. */
  1972. Color4.prototype.subtractToRef = function (right, result) {
  1973. result.r = this.r - right.r;
  1974. result.g = this.g - right.g;
  1975. result.b = this.b - right.b;
  1976. result.a = this.a - right.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 with the current Color4 values multiplied by scale
  1981. * @param scale defines the scaling factor to apply
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.scale = function (scale) {
  1985. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1986. };
  1987. /**
  1988. * Multiplies the current Color4 values by scale and stores the result in "result"
  1989. * @param scale defines the scaling factor to apply
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current unmodified Color4
  1992. */
  1993. Color4.prototype.scaleToRef = function (scale, result) {
  1994. result.r = this.r * scale;
  1995. result.g = this.g * scale;
  1996. result.b = this.b * scale;
  1997. result.a = this.a * scale;
  1998. return this;
  1999. };
  2000. /**
  2001. * Scale the current Color4 values by a factor and add the result to a given Color4
  2002. * @param scale defines the scale factor
  2003. * @param result defines the Color4 object where to store the result
  2004. * @returns the unmodified current Color4
  2005. */
  2006. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2007. result.r += this.r * scale;
  2008. result.g += this.g * scale;
  2009. result.b += this.b * scale;
  2010. result.a += this.a * scale;
  2011. return this;
  2012. };
  2013. /**
  2014. * Clamps the rgb values by the min and max values and stores the result into "result"
  2015. * @param min defines minimum clamping value (default is 0)
  2016. * @param max defines maximum clamping value (default is 1)
  2017. * @param result defines color to store the result into.
  2018. * @returns the cuurent Color4
  2019. */
  2020. Color4.prototype.clampToRef = function (min, max, result) {
  2021. if (min === void 0) { min = 0; }
  2022. if (max === void 0) { max = 1; }
  2023. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2024. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2025. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2026. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2027. return this;
  2028. };
  2029. /**
  2030. * Multipy an Color4 value by another and return a new Color4 object
  2031. * @param color defines the Color4 value to multiply by
  2032. * @returns a new Color4 object
  2033. */
  2034. Color4.prototype.multiply = function (color) {
  2035. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2036. };
  2037. /**
  2038. * Multipy a Color4 value by another and push the result in a reference value
  2039. * @param color defines the Color4 value to multiply by
  2040. * @param result defines the Color4 to fill the result in
  2041. * @returns the result Color4
  2042. */
  2043. Color4.prototype.multiplyToRef = function (color, result) {
  2044. result.r = this.r * color.r;
  2045. result.g = this.g * color.g;
  2046. result.b = this.b * color.b;
  2047. result.a = this.a * color.a;
  2048. return result;
  2049. };
  2050. /**
  2051. * Creates a string with the Color4 current values
  2052. * @returns the string representation of the Color4 object
  2053. */
  2054. Color4.prototype.toString = function () {
  2055. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2056. };
  2057. /**
  2058. * Returns the string "Color4"
  2059. * @returns "Color4"
  2060. */
  2061. Color4.prototype.getClassName = function () {
  2062. return "Color4";
  2063. };
  2064. /**
  2065. * Compute the Color4 hash code
  2066. * @returns an unique number that can be used to hash Color4 objects
  2067. */
  2068. Color4.prototype.getHashCode = function () {
  2069. var hash = this.r || 0;
  2070. hash = (hash * 397) ^ (this.g || 0);
  2071. hash = (hash * 397) ^ (this.b || 0);
  2072. hash = (hash * 397) ^ (this.a || 0);
  2073. return hash;
  2074. };
  2075. /**
  2076. * Creates a new Color4 copied from the current one
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.prototype.clone = function () {
  2080. return new Color4(this.r, this.g, this.b, this.a);
  2081. };
  2082. /**
  2083. * Copies the given Color4 values into the current one
  2084. * @param source defines the source Color4 object
  2085. * @returns the current updated Color4 object
  2086. */
  2087. Color4.prototype.copyFrom = function (source) {
  2088. this.r = source.r;
  2089. this.g = source.g;
  2090. this.b = source.b;
  2091. this.a = source.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Copies the given float values into the current one
  2096. * @param r defines the red component to read from
  2097. * @param g defines the green component to read from
  2098. * @param b defines the blue component to read from
  2099. * @param a defines the alpha component to read from
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2103. this.r = r;
  2104. this.g = g;
  2105. this.b = b;
  2106. this.a = a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the given float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.set = function (r, g, b, a) {
  2118. return this.copyFromFloats(r, g, b, a);
  2119. };
  2120. /**
  2121. * Compute the Color4 hexadecimal code as a string
  2122. * @returns a string containing the hexadecimal representation of the Color4 object
  2123. */
  2124. Color4.prototype.toHexString = function () {
  2125. var intR = (this.r * 255) | 0;
  2126. var intG = (this.g * 255) | 0;
  2127. var intB = (this.b * 255) | 0;
  2128. var intA = (this.a * 255) | 0;
  2129. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to linear space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toLinearSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toLinearSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the linear space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to gamma space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toGammaSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toGammaSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the gamma space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. // Statics
  2174. /**
  2175. * Creates a new Color4 from the string containing valid hexadecimal values
  2176. * @param hex defines a string containing valid hexadecimal values
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.FromHexString = function (hex) {
  2180. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2181. return new Color4(0.0, 0.0, 0.0, 0.0);
  2182. }
  2183. var r = parseInt(hex.substring(1, 3), 16);
  2184. var g = parseInt(hex.substring(3, 5), 16);
  2185. var b = parseInt(hex.substring(5, 7), 16);
  2186. var a = parseInt(hex.substring(7, 9), 16);
  2187. return Color4.FromInts(r, g, b, a);
  2188. };
  2189. /**
  2190. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2191. * @param left defines the start value
  2192. * @param right defines the end value
  2193. * @param amount defines the gradient factor
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.Lerp = function (left, right, amount) {
  2197. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2198. Color4.LerpToRef(left, right, amount, result);
  2199. return result;
  2200. };
  2201. /**
  2202. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2203. * @param left defines the start value
  2204. * @param right defines the end value
  2205. * @param amount defines the gradient factor
  2206. * @param result defines the Color4 object where to store data
  2207. */
  2208. Color4.LerpToRef = function (left, right, amount, result) {
  2209. result.r = left.r + (right.r - left.r) * amount;
  2210. result.g = left.g + (right.g - left.g) * amount;
  2211. result.b = left.b + (right.b - left.b) * amount;
  2212. result.a = left.a + (right.a - left.a) * amount;
  2213. };
  2214. /**
  2215. * Creates a new Color4 from a Color3 and an alpha value
  2216. * @param color3 defines the source Color3 to read from
  2217. * @param alpha defines the alpha component (1.0 by default)
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.FromColor3 = function (color3, alpha) {
  2221. if (alpha === void 0) { alpha = 1.0; }
  2222. return new Color4(color3.r, color3.g, color3.b, alpha);
  2223. };
  2224. /**
  2225. * Creates a new Color4 from the starting index element of the given array
  2226. * @param array defines the source array to read from
  2227. * @param offset defines the offset in the source array
  2228. * @returns a new Color4 object
  2229. */
  2230. Color4.FromArray = function (array, offset) {
  2231. if (offset === void 0) { offset = 0; }
  2232. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2233. };
  2234. /**
  2235. * Creates a new Color3 from integer values (< 256)
  2236. * @param r defines the red component to read from (value between 0 and 255)
  2237. * @param g defines the green component to read from (value between 0 and 255)
  2238. * @param b defines the blue component to read from (value between 0 and 255)
  2239. * @param a defines the alpha component to read from (value between 0 and 255)
  2240. * @returns a new Color3 object
  2241. */
  2242. Color4.FromInts = function (r, g, b, a) {
  2243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2244. };
  2245. /**
  2246. * Check the content of a given array and convert it to an array containing RGBA data
  2247. * If the original array was already containing count * 4 values then it is returned directly
  2248. * @param colors defines the array to check
  2249. * @param count defines the number of RGBA data to expect
  2250. * @returns an array containing count * 4 values (RGBA)
  2251. */
  2252. Color4.CheckColors4 = function (colors, count) {
  2253. // Check if color3 was used
  2254. if (colors.length === count * 3) {
  2255. var colors4 = [];
  2256. for (var index = 0; index < colors.length; index += 3) {
  2257. var newIndex = (index / 3) * 4;
  2258. colors4[newIndex] = colors[index];
  2259. colors4[newIndex + 1] = colors[index + 1];
  2260. colors4[newIndex + 2] = colors[index + 2];
  2261. colors4[newIndex + 3] = 1.0;
  2262. }
  2263. return colors4;
  2264. }
  2265. return colors;
  2266. };
  2267. return Color4;
  2268. }());
  2269. BABYLON.Color4 = Color4;
  2270. /**
  2271. * Class representing a vector containing 2 coordinates
  2272. */
  2273. var Vector2 = /** @class */ (function () {
  2274. /**
  2275. * Creates a new Vector2 from the given x and y coordinates
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. */
  2279. function Vector2(
  2280. /** defines the first coordinate */
  2281. x,
  2282. /** defines the second coordinate */
  2283. y) {
  2284. if (x === void 0) { x = 0; }
  2285. if (y === void 0) { y = 0; }
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Gets a string with the Vector2 coordinates
  2291. * @returns a string with the Vector2 coordinates
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Gets class name
  2298. * @returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Gets current vector hash code
  2305. * @returns the Vector2 hash code as a number
  2306. */
  2307. Vector2.prototype.getHashCode = function () {
  2308. var hash = this.x || 0;
  2309. hash = (hash * 397) ^ (this.y || 0);
  2310. return hash;
  2311. };
  2312. // Operators
  2313. /**
  2314. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2315. * @param array defines the source array
  2316. * @param index defines the offset in source array
  2317. * @returns the current Vector2
  2318. */
  2319. Vector2.prototype.toArray = function (array, index) {
  2320. if (index === void 0) { index = 0; }
  2321. array[index] = this.x;
  2322. array[index + 1] = this.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Copy the current vector to an array
  2327. * @returns a new array with 2 elements: the Vector2 coordinates.
  2328. */
  2329. Vector2.prototype.asArray = function () {
  2330. var result = new Array();
  2331. this.toArray(result, 0);
  2332. return result;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2336. * @param source defines the source Vector2
  2337. * @returns the current updated Vector2
  2338. */
  2339. Vector2.prototype.copyFrom = function (source) {
  2340. this.x = source.x;
  2341. this.y = source.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the Vector2 coordinates with the given floats
  2346. * @param x defines the first coordinate
  2347. * @param y defines the second coordinate
  2348. * @returns the current updated Vector2
  2349. */
  2350. Vector2.prototype.copyFromFloats = function (x, y) {
  2351. this.x = x;
  2352. this.y = y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.set = function (x, y) {
  2362. return this.copyFromFloats(x, y);
  2363. };
  2364. /**
  2365. * Add another vector with the current one
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2368. */
  2369. Vector2.prototype.add = function (otherVector) {
  2370. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.addToRef = function (otherVector, result) {
  2379. result.x = this.x + otherVector.x;
  2380. result.y = this.y + otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.addInPlace = function (otherVector) {
  2389. this.x += otherVector.x;
  2390. this.y += otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.addVector3 = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.subtract = function (otherVector) {
  2407. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2408. };
  2409. /**
  2410. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2411. * @param otherVector defines the other vector
  2412. * @param result defines the target vector
  2413. * @returns the unmodified current Vector2
  2414. */
  2415. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2416. result.x = this.x - otherVector.x;
  2417. result.y = this.y - otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns the current updated Vector2
  2424. */
  2425. Vector2.prototype.subtractInPlace = function (otherVector) {
  2426. this.x -= otherVector.x;
  2427. this.y -= otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Multiplies in place the current Vector2 coordinates by the given ones
  2432. * @param otherVector defines the other vector
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2436. this.x *= otherVector.x;
  2437. this.y *= otherVector.y;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.multiply = function (otherVector) {
  2446. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2447. };
  2448. /**
  2449. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @param result defines the target vector
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2455. result.x = this.x * otherVector.x;
  2456. result.y = this.y * otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2461. * @param x defines the first coordinate
  2462. * @param y defines the second coordinate
  2463. * @returns a new Vector2
  2464. */
  2465. Vector2.prototype.multiplyByFloats = function (x, y) {
  2466. return new Vector2(this.x * x, this.y * y);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2470. * @param otherVector defines the other vector
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.divide = function (otherVector) {
  2474. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2475. };
  2476. /**
  2477. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @param result defines the target vector
  2480. * @returns the unmodified current Vector2
  2481. */
  2482. Vector2.prototype.divideToRef = function (otherVector, result) {
  2483. result.x = this.x / otherVector.x;
  2484. result.y = this.y / otherVector.y;
  2485. return this;
  2486. };
  2487. /**
  2488. * Divides the current Vector2 coordinates by the given ones
  2489. * @param otherVector defines the other vector
  2490. * @returns the current updated Vector2
  2491. */
  2492. Vector2.prototype.divideInPlace = function (otherVector) {
  2493. return this.divideToRef(otherVector, this);
  2494. };
  2495. /**
  2496. * Gets a new Vector2 with current Vector2 negated coordinates
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.prototype.negate = function () {
  2500. return new Vector2(-this.x, -this.y);
  2501. };
  2502. /**
  2503. * Multiply the Vector2 coordinates by scale
  2504. * @param scale defines the scaling factor
  2505. * @returns the current updated Vector2
  2506. */
  2507. Vector2.prototype.scaleInPlace = function (scale) {
  2508. this.x *= scale;
  2509. this.y *= scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2514. * @param scale defines the scaling factor
  2515. * @returns a new Vector2
  2516. */
  2517. Vector2.prototype.scale = function (scale) {
  2518. var result = new Vector2(0, 0);
  2519. this.scaleToRef(scale, result);
  2520. return result;
  2521. };
  2522. /**
  2523. * Scale the current Vector2 values by a factor to a given Vector2
  2524. * @param scale defines the scale factor
  2525. * @param result defines the Vector2 object where to store the result
  2526. * @returns the unmodified current Vector2
  2527. */
  2528. Vector2.prototype.scaleToRef = function (scale, result) {
  2529. result.x = this.x * scale;
  2530. result.y = this.y * scale;
  2531. return this;
  2532. };
  2533. /**
  2534. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2535. * @param scale defines the scale factor
  2536. * @param result defines the Vector2 object where to store the result
  2537. * @returns the unmodified current Vector2
  2538. */
  2539. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2540. result.x += this.x * scale;
  2541. result.y += this.y * scale;
  2542. return this;
  2543. };
  2544. /**
  2545. * Gets a boolean if two vectors are equals
  2546. * @param otherVector defines the other vector
  2547. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2548. */
  2549. Vector2.prototype.equals = function (otherVector) {
  2550. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals (using an epsilon value)
  2554. * @param otherVector defines the other vector
  2555. * @param epsilon defines the minimal distance to consider equality
  2556. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2557. */
  2558. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2559. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2560. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2561. };
  2562. /**
  2563. * Gets a new Vector2 from current Vector2 floored values
  2564. * @returns a new Vector2
  2565. */
  2566. Vector2.prototype.floor = function () {
  2567. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2568. };
  2569. /**
  2570. * Gets a new Vector2 from current Vector2 floored values
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.fract = function () {
  2574. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. if (other.x < this.x)
  3174. this.x = other.x;
  3175. if (other.y < this.y)
  3176. this.y = other.y;
  3177. if (other.z < this.z)
  3178. this.z = other.z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3183. * @param other defines the second operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.maximizeInPlace = function (other) {
  3187. if (other.x > this.x)
  3188. this.x = other.x;
  3189. if (other.y > this.y)
  3190. this.y = other.y;
  3191. if (other.z > this.z)
  3192. this.z = other.z;
  3193. return this;
  3194. };
  3195. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3196. /**
  3197. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3198. */
  3199. get: function () {
  3200. var absX = Math.abs(this.x);
  3201. var absY = Math.abs(this.y);
  3202. if (absX !== absY) {
  3203. return true;
  3204. }
  3205. var absZ = Math.abs(this.z);
  3206. if (absX !== absZ) {
  3207. return true;
  3208. }
  3209. if (absY !== absZ) {
  3210. return true;
  3211. }
  3212. return false;
  3213. },
  3214. enumerable: true,
  3215. configurable: true
  3216. });
  3217. /**
  3218. * Gets a new Vector3 from current Vector3 floored values
  3219. * @returns a new Vector3
  3220. */
  3221. Vector3.prototype.floor = function () {
  3222. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3223. };
  3224. /**
  3225. * Gets a new Vector3 from current Vector3 floored values
  3226. * @returns a new Vector3
  3227. */
  3228. Vector3.prototype.fract = function () {
  3229. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3230. };
  3231. // Properties
  3232. /**
  3233. * Gets the length of the Vector3
  3234. * @returns the length of the Vecto3
  3235. */
  3236. Vector3.prototype.length = function () {
  3237. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3238. };
  3239. /**
  3240. * Gets the squared length of the Vector3
  3241. * @returns squared length of the Vector3
  3242. */
  3243. Vector3.prototype.lengthSquared = function () {
  3244. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3245. };
  3246. /**
  3247. * Normalize the current Vector3.
  3248. * Please note that this is an in place operation.
  3249. * @returns the current updated Vector3
  3250. */
  3251. Vector3.prototype.normalize = function () {
  3252. var len = this.length();
  3253. if (len === 0 || len === 1.0)
  3254. return this;
  3255. var num = 1.0 / len;
  3256. this.x *= num;
  3257. this.y *= num;
  3258. this.z *= num;
  3259. return this;
  3260. };
  3261. /**
  3262. * Normalize the current Vector3 to a new vector
  3263. * @returns the new Vector3
  3264. */
  3265. Vector3.prototype.normalizeToNew = function () {
  3266. var normalized = new Vector3(0, 0, 0);
  3267. this.normalizeToRef(normalized);
  3268. return normalized;
  3269. };
  3270. /**
  3271. * Normalize the current Vector3 to the reference
  3272. * @param reference define the Vector3 to update
  3273. * @returns the updated Vector3
  3274. */
  3275. Vector3.prototype.normalizeToRef = function (reference) {
  3276. var len = this.length();
  3277. if (len === 0 || len === 1.0) {
  3278. reference.set(this.x, this.y, this.z);
  3279. return reference;
  3280. }
  3281. var scale = 1.0 / len;
  3282. this.scaleToRef(scale, reference);
  3283. return reference;
  3284. };
  3285. /**
  3286. * Creates a new Vector3 copied from the current Vector3
  3287. * @returns the new Vector3
  3288. */
  3289. Vector3.prototype.clone = function () {
  3290. return new Vector3(this.x, this.y, this.z);
  3291. };
  3292. /**
  3293. * Copies the given vector coordinates to the current Vector3 ones
  3294. * @param source defines the source Vector3
  3295. * @returns the current updated Vector3
  3296. */
  3297. Vector3.prototype.copyFrom = function (source) {
  3298. this.x = source.x;
  3299. this.y = source.y;
  3300. this.z = source.z;
  3301. return this;
  3302. };
  3303. /**
  3304. * Copies the given floats to the current Vector3 coordinates
  3305. * @param x defines the x coordinate of the operand
  3306. * @param y defines the y coordinate of the operand
  3307. * @param z defines the z coordinate of the operand
  3308. * @returns the current updated Vector3
  3309. */
  3310. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3311. this.x = x;
  3312. this.y = y;
  3313. this.z = z;
  3314. return this;
  3315. };
  3316. /**
  3317. * Copies the given floats to the current Vector3 coordinates
  3318. * @param x defines the x coordinate of the operand
  3319. * @param y defines the y coordinate of the operand
  3320. * @param z defines the z coordinate of the operand
  3321. * @returns the current updated Vector3
  3322. */
  3323. Vector3.prototype.set = function (x, y, z) {
  3324. return this.copyFromFloats(x, y, z);
  3325. };
  3326. // Statics
  3327. /**
  3328. * Get the clip factor between two vectors
  3329. * @param vector0 defines the first operand
  3330. * @param vector1 defines the second operand
  3331. * @param axis defines the axis to use
  3332. * @param size defines the size along the axis
  3333. * @returns the clip factor
  3334. */
  3335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3336. var d0 = Vector3.Dot(vector0, axis) - size;
  3337. var d1 = Vector3.Dot(vector1, axis) - size;
  3338. var s = d0 / (d0 - d1);
  3339. return s;
  3340. };
  3341. /**
  3342. * Get angle between two vectors
  3343. * @param vector0 angle between vector0 and vector1
  3344. * @param vector1 angle between vector0 and vector1
  3345. * @param normal direction of the normal
  3346. * @return the angle between vector0 and vector1
  3347. */
  3348. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3349. var v0 = vector0.clone().normalize();
  3350. var v1 = vector1.clone().normalize();
  3351. var dot = Vector3.Dot(v0, v1);
  3352. var n = Vector3.Cross(v0, v1);
  3353. if (Vector3.Dot(n, normal) > 0) {
  3354. return Math.acos(dot);
  3355. }
  3356. return -Math.acos(dot);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set from the index "offset" of the given array
  3360. * @param array defines the source array
  3361. * @param offset defines the offset in the source array
  3362. * @returns the new Vector3
  3363. */
  3364. Vector3.FromArray = function (array, offset) {
  3365. if (!offset) {
  3366. offset = 0;
  3367. }
  3368. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3369. };
  3370. /**
  3371. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3372. * This function is deprecated. Use FromArray instead
  3373. * @param array defines the source array
  3374. * @param offset defines the offset in the source array
  3375. * @returns the new Vector3
  3376. */
  3377. Vector3.FromFloatArray = function (array, offset) {
  3378. return Vector3.FromArray(array, offset);
  3379. };
  3380. /**
  3381. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3382. * @param array defines the source array
  3383. * @param offset defines the offset in the source array
  3384. * @param result defines the Vector3 where to store the result
  3385. */
  3386. Vector3.FromArrayToRef = function (array, offset, result) {
  3387. result.x = array[offset];
  3388. result.y = array[offset + 1];
  3389. result.z = array[offset + 2];
  3390. };
  3391. /**
  3392. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3393. * This function is deprecated. Use FromArrayToRef instead.
  3394. * @param array defines the source array
  3395. * @param offset defines the offset in the source array
  3396. * @param result defines the Vector3 where to store the result
  3397. */
  3398. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3399. return Vector3.FromArrayToRef(array, offset, result);
  3400. };
  3401. /**
  3402. * Sets the given vector "result" with the given floats.
  3403. * @param x defines the x coordinate of the source
  3404. * @param y defines the y coordinate of the source
  3405. * @param z defines the z coordinate of the source
  3406. * @param result defines the Vector3 where to store the result
  3407. */
  3408. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3409. result.x = x;
  3410. result.y = y;
  3411. result.z = z;
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3415. * @returns a new empty Vector3
  3416. */
  3417. Vector3.Zero = function () {
  3418. return new Vector3(0.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3422. * @returns a new unit Vector3
  3423. */
  3424. Vector3.One = function () {
  3425. return new Vector3(1.0, 1.0, 1.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3429. * @returns a new up Vector3
  3430. */
  3431. Vector3.Up = function () {
  3432. return new Vector3(0.0, 1.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3436. * @returns a new down Vector3
  3437. */
  3438. Vector3.Down = function () {
  3439. return new Vector3(0.0, -1.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3443. * @returns a new forward Vector3
  3444. */
  3445. Vector3.Forward = function () {
  3446. return new Vector3(0.0, 0.0, 1.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3450. * @returns a new forward Vector3
  3451. */
  3452. Vector3.Backward = function () {
  3453. return new Vector3(0.0, 0.0, -1.0);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3457. * @returns a new right Vector3
  3458. */
  3459. Vector3.Right = function () {
  3460. return new Vector3(1.0, 0.0, 0.0);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3464. * @returns a new left Vector3
  3465. */
  3466. Vector3.Left = function () {
  3467. return new Vector3(-1.0, 0.0, 0.0);
  3468. };
  3469. /**
  3470. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3471. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3472. * @param vector defines the Vector3 to transform
  3473. * @param transformation defines the transformation matrix
  3474. * @returns the transformed Vector3
  3475. */
  3476. Vector3.TransformCoordinates = function (vector, transformation) {
  3477. var result = Vector3.Zero();
  3478. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3483. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3484. * @param vector defines the Vector3 to transform
  3485. * @param transformation defines the transformation matrix
  3486. * @param result defines the Vector3 where to store the result
  3487. */
  3488. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3489. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3490. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3491. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3492. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3493. result.x = x / w;
  3494. result.y = y / w;
  3495. result.z = z / w;
  3496. };
  3497. /**
  3498. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3499. * This method computes tranformed coordinates only, not transformed direction vectors
  3500. * @param x define the x coordinate of the source vector
  3501. * @param y define the y coordinate of the source vector
  3502. * @param z define the z coordinate of the source vector
  3503. * @param transformation defines the transformation matrix
  3504. * @param result defines the Vector3 where to store the result
  3505. */
  3506. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3507. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3508. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3509. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3510. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3511. result.x = rx / rw;
  3512. result.y = ry / rw;
  3513. result.z = rz / rw;
  3514. };
  3515. /**
  3516. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3517. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3518. * @param vector defines the Vector3 to transform
  3519. * @param transformation defines the transformation matrix
  3520. * @returns the new Vector3
  3521. */
  3522. Vector3.TransformNormal = function (vector, transformation) {
  3523. var result = Vector3.Zero();
  3524. Vector3.TransformNormalToRef(vector, transformation, result);
  3525. return result;
  3526. };
  3527. /**
  3528. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3529. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3530. * @param vector defines the Vector3 to transform
  3531. * @param transformation defines the transformation matrix
  3532. * @param result defines the Vector3 where to store the result
  3533. */
  3534. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3535. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3536. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3537. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3538. result.x = x;
  3539. result.y = y;
  3540. result.z = z;
  3541. };
  3542. /**
  3543. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3544. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3545. * @param x define the x coordinate of the source vector
  3546. * @param y define the y coordinate of the source vector
  3547. * @param z define the z coordinate of the source vector
  3548. * @param transformation defines the transformation matrix
  3549. * @param result defines the Vector3 where to store the result
  3550. */
  3551. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3552. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3553. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3554. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3555. };
  3556. /**
  3557. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3558. * @param value1 defines the first control point
  3559. * @param value2 defines the second control point
  3560. * @param value3 defines the third control point
  3561. * @param value4 defines the fourth control point
  3562. * @param amount defines the amount on the spline to use
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3566. var squared = amount * amount;
  3567. var cubed = amount * squared;
  3568. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3569. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3570. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3571. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3572. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3573. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3574. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3575. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3576. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * 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"
  3581. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3582. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3583. * @param value defines the current value
  3584. * @param min defines the lower range value
  3585. * @param max defines the upper range value
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Clamp = function (value, min, max) {
  3589. var x = value.x;
  3590. x = (x > max.x) ? max.x : x;
  3591. x = (x < min.x) ? min.x : x;
  3592. var y = value.y;
  3593. y = (y > max.y) ? max.y : y;
  3594. y = (y < min.y) ? min.y : y;
  3595. var z = value.z;
  3596. z = (z > max.z) ? max.z : z;
  3597. z = (z < min.z) ? min.z : z;
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3602. * @param value1 defines the first control point
  3603. * @param tangent1 defines the first tangent vector
  3604. * @param value2 defines the second control point
  3605. * @param tangent2 defines the second tangent vector
  3606. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3607. * @returns the new Vector3
  3608. */
  3609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3610. var squared = amount * amount;
  3611. var cubed = amount * squared;
  3612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3614. var part3 = (cubed - (2.0 * squared)) + amount;
  3615. var part4 = cubed - squared;
  3616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3619. return new Vector3(x, y, z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3623. * @param start defines the start value
  3624. * @param end defines the end value
  3625. * @param amount max defines amount between both (between 0 and 1)
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Lerp = function (start, end, amount) {
  3629. var result = new Vector3(0, 0, 0);
  3630. Vector3.LerpToRef(start, end, amount, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3635. * @param start defines the start value
  3636. * @param end defines the end value
  3637. * @param amount max defines amount between both (between 0 and 1)
  3638. * @param result defines the Vector3 where to store the result
  3639. */
  3640. Vector3.LerpToRef = function (start, end, amount, result) {
  3641. result.x = start.x + ((end.x - start.x) * amount);
  3642. result.y = start.y + ((end.y - start.y) * amount);
  3643. result.z = start.z + ((end.z - start.z) * amount);
  3644. };
  3645. /**
  3646. * Returns the dot product (float) between the vectors "left" and "right"
  3647. * @param left defines the left operand
  3648. * @param right defines the right operand
  3649. * @returns the dot product
  3650. */
  3651. Vector3.Dot = function (left, right) {
  3652. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3653. };
  3654. /**
  3655. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3656. * The cross product is then orthogonal to both "left" and "right"
  3657. * @param left defines the left operand
  3658. * @param right defines the right operand
  3659. * @returns the cross product
  3660. */
  3661. Vector3.Cross = function (left, right) {
  3662. var result = Vector3.Zero();
  3663. Vector3.CrossToRef(left, right, result);
  3664. return result;
  3665. };
  3666. /**
  3667. * Sets the given vector "result" with the cross product of "left" and "right"
  3668. * The cross product is then orthogonal to both "left" and "right"
  3669. * @param left defines the left operand
  3670. * @param right defines the right operand
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.CrossToRef = function (left, right, result) {
  3674. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3675. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3676. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3677. result.copyFrom(MathTmp.Vector3[0]);
  3678. };
  3679. /**
  3680. * Returns a new Vector3 as the normalization of the given vector
  3681. * @param vector defines the Vector3 to normalize
  3682. * @returns the new Vector3
  3683. */
  3684. Vector3.Normalize = function (vector) {
  3685. var result = Vector3.Zero();
  3686. Vector3.NormalizeToRef(vector, result);
  3687. return result;
  3688. };
  3689. /**
  3690. * Sets the given vector "result" with the normalization of the given first vector
  3691. * @param vector defines the Vector3 to normalize
  3692. * @param result defines the Vector3 where to store the result
  3693. */
  3694. Vector3.NormalizeToRef = function (vector, result) {
  3695. result.copyFrom(vector);
  3696. result.normalize();
  3697. };
  3698. /**
  3699. * Project a Vector3 onto screen space
  3700. * @param vector defines the Vector3 to project
  3701. * @param world defines the world matrix to use
  3702. * @param transform defines the transform (view x projection) matrix to use
  3703. * @param viewport defines the screen viewport to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.Project = function (vector, world, transform, viewport) {
  3707. var cw = viewport.width;
  3708. var ch = viewport.height;
  3709. var cx = viewport.x;
  3710. var cy = viewport.y;
  3711. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3712. 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);
  3713. var matrix = MathTmp.Matrix[0];
  3714. world.multiplyToRef(transform, matrix);
  3715. matrix.multiplyToRef(viewportMatrix, matrix);
  3716. return Vector3.TransformCoordinates(vector, matrix);
  3717. };
  3718. /**
  3719. * Unproject from screen space to object space
  3720. * @param source defines the screen space Vector3 to use
  3721. * @param viewportWidth defines the current width of the viewport
  3722. * @param viewportHeight defines the current height of the viewport
  3723. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3724. * @param transform defines the transform (view x projection) matrix to use
  3725. * @returns the new Vector3
  3726. */
  3727. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3728. var matrix = MathTmp.Matrix[0];
  3729. world.multiplyToRef(transform, matrix);
  3730. matrix.invert();
  3731. source.x = source.x / viewportWidth * 2 - 1;
  3732. source.y = -(source.y / viewportHeight * 2 - 1);
  3733. var vector = Vector3.TransformCoordinates(source, matrix);
  3734. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3735. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3736. vector = vector.scale(1.0 / num);
  3737. }
  3738. return vector;
  3739. };
  3740. /**
  3741. * Unproject from screen space to object space
  3742. * @param source defines the screen space Vector3 to use
  3743. * @param viewportWidth defines the current width of the viewport
  3744. * @param viewportHeight defines the current height of the viewport
  3745. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3746. * @param view defines the view matrix to use
  3747. * @param projection defines the projection matrix to use
  3748. * @returns the new Vector3
  3749. */
  3750. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3751. var result = Vector3.Zero();
  3752. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3753. return result;
  3754. };
  3755. /**
  3756. * Unproject from screen space to object space
  3757. * @param source defines the screen space Vector3 to use
  3758. * @param viewportWidth defines the current width of the viewport
  3759. * @param viewportHeight defines the current height of the viewport
  3760. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3761. * @param view defines the view matrix to use
  3762. * @param projection defines the projection matrix to use
  3763. * @param result defines the Vector3 where to store the result
  3764. */
  3765. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3766. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3767. };
  3768. /**
  3769. * Unproject from screen space to object space
  3770. * @param sourceX defines the screen space x coordinate to use
  3771. * @param sourceY defines the screen space y coordinate to use
  3772. * @param sourceZ defines the screen space z coordinate to use
  3773. * @param viewportWidth defines the current width of the viewport
  3774. * @param viewportHeight defines the current height of the viewport
  3775. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3776. * @param view defines the view matrix to use
  3777. * @param projection defines the projection matrix to use
  3778. * @param result defines the Vector3 where to store the result
  3779. */
  3780. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3781. var matrix = MathTmp.Matrix[0];
  3782. world.multiplyToRef(view, matrix);
  3783. matrix.multiplyToRef(projection, matrix);
  3784. matrix.invert();
  3785. var screenSource = MathTmp.Vector3[0];
  3786. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3787. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3788. screenSource.z = 2 * sourceZ - 1.0;
  3789. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3790. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3791. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3792. result.scaleInPlace(1.0 / num);
  3793. }
  3794. };
  3795. /**
  3796. * Gets the minimal coordinate values between two Vector3
  3797. * @param left defines the first operand
  3798. * @param right defines the second operand
  3799. * @returns the new Vector3
  3800. */
  3801. Vector3.Minimize = function (left, right) {
  3802. var min = left.clone();
  3803. min.minimizeInPlace(right);
  3804. return min;
  3805. };
  3806. /**
  3807. * Gets the maximal coordinate values between two Vector3
  3808. * @param left defines the first operand
  3809. * @param right defines the second operand
  3810. * @returns the new Vector3
  3811. */
  3812. Vector3.Maximize = function (left, right) {
  3813. var max = left.clone();
  3814. max.maximizeInPlace(right);
  3815. return max;
  3816. };
  3817. /**
  3818. * Returns the distance between the vectors "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the distance
  3822. */
  3823. Vector3.Distance = function (value1, value2) {
  3824. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3825. };
  3826. /**
  3827. * Returns the squared distance between the vectors "value1" and "value2"
  3828. * @param value1 defines the first operand
  3829. * @param value2 defines the second operand
  3830. * @returns the squared distance
  3831. */
  3832. Vector3.DistanceSquared = function (value1, value2) {
  3833. var x = value1.x - value2.x;
  3834. var y = value1.y - value2.y;
  3835. var z = value1.z - value2.z;
  3836. return (x * x) + (y * y) + (z * z);
  3837. };
  3838. /**
  3839. * Returns a new Vector3 located at the center between "value1" and "value2"
  3840. * @param value1 defines the first operand
  3841. * @param value2 defines the second operand
  3842. * @returns the new Vector3
  3843. */
  3844. Vector3.Center = function (value1, value2) {
  3845. var center = value1.add(value2);
  3846. center.scaleInPlace(0.5);
  3847. return center;
  3848. };
  3849. /**
  3850. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3851. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3852. * to something in order to rotate it from its local system to the given target system
  3853. * Note: axis1, axis2 and axis3 are normalized during this operation
  3854. * @param axis1 defines the first axis
  3855. * @param axis2 defines the second axis
  3856. * @param axis3 defines the third axis
  3857. * @returns a new Vector3
  3858. */
  3859. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3860. var rotation = Vector3.Zero();
  3861. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3862. return rotation;
  3863. };
  3864. /**
  3865. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3866. * @param axis1 defines the first axis
  3867. * @param axis2 defines the second axis
  3868. * @param axis3 defines the third axis
  3869. * @param ref defines the Vector3 where to store the result
  3870. */
  3871. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3872. var quat = MathTmp.Quaternion[0];
  3873. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3874. quat.toEulerAnglesToRef(ref);
  3875. };
  3876. return Vector3;
  3877. }());
  3878. BABYLON.Vector3 = Vector3;
  3879. /**
  3880. * Vector4 class created for EulerAngle class conversion to Quaternion
  3881. */
  3882. var Vector4 = /** @class */ (function () {
  3883. /**
  3884. * Creates a Vector4 object from the given floats.
  3885. * @param x x value of the vector
  3886. * @param y y value of the vector
  3887. * @param z z value of the vector
  3888. * @param w w value of the vector
  3889. */
  3890. function Vector4(
  3891. /** x value of the vector */
  3892. x,
  3893. /** y value of the vector */
  3894. y,
  3895. /** z value of the vector */
  3896. z,
  3897. /** w value of the vector */
  3898. w) {
  3899. this.x = x;
  3900. this.y = y;
  3901. this.z = z;
  3902. this.w = w;
  3903. }
  3904. /**
  3905. * Returns the string with the Vector4 coordinates.
  3906. * @returns a string containing all the vector values
  3907. */
  3908. Vector4.prototype.toString = function () {
  3909. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3910. };
  3911. /**
  3912. * Returns the string "Vector4".
  3913. * @returns "Vector4"
  3914. */
  3915. Vector4.prototype.getClassName = function () {
  3916. return "Vector4";
  3917. };
  3918. /**
  3919. * Returns the Vector4 hash code.
  3920. * @returns a unique hash code
  3921. */
  3922. Vector4.prototype.getHashCode = function () {
  3923. var hash = this.x || 0;
  3924. hash = (hash * 397) ^ (this.y || 0);
  3925. hash = (hash * 397) ^ (this.z || 0);
  3926. hash = (hash * 397) ^ (this.w || 0);
  3927. return hash;
  3928. };
  3929. // Operators
  3930. /**
  3931. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3932. * @returns the resulting array
  3933. */
  3934. Vector4.prototype.asArray = function () {
  3935. var result = new Array();
  3936. this.toArray(result, 0);
  3937. return result;
  3938. };
  3939. /**
  3940. * Populates the given array from the given index with the Vector4 coordinates.
  3941. * @param array array to populate
  3942. * @param index index of the array to start at (default: 0)
  3943. * @returns the Vector4.
  3944. */
  3945. Vector4.prototype.toArray = function (array, index) {
  3946. if (index === undefined) {
  3947. index = 0;
  3948. }
  3949. array[index] = this.x;
  3950. array[index + 1] = this.y;
  3951. array[index + 2] = this.z;
  3952. array[index + 3] = this.w;
  3953. return this;
  3954. };
  3955. /**
  3956. * Adds the given vector to the current Vector4.
  3957. * @param otherVector the vector to add
  3958. * @returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.addInPlace = function (otherVector) {
  3961. this.x += otherVector.x;
  3962. this.y += otherVector.y;
  3963. this.z += otherVector.z;
  3964. this.w += otherVector.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3969. * @param otherVector the vector to add
  3970. * @returns the resulting vector
  3971. */
  3972. Vector4.prototype.add = function (otherVector) {
  3973. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3974. };
  3975. /**
  3976. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3977. * @param otherVector the vector to add
  3978. * @param result the vector to store the result
  3979. * @returns the current Vector4.
  3980. */
  3981. Vector4.prototype.addToRef = function (otherVector, result) {
  3982. result.x = this.x + otherVector.x;
  3983. result.y = this.y + otherVector.y;
  3984. result.z = this.z + otherVector.z;
  3985. result.w = this.w + otherVector.w;
  3986. return this;
  3987. };
  3988. /**
  3989. * Subtract in place the given vector from the current Vector4.
  3990. * @param otherVector the vector to subtract
  3991. * @returns the updated Vector4.
  3992. */
  3993. Vector4.prototype.subtractInPlace = function (otherVector) {
  3994. this.x -= otherVector.x;
  3995. this.y -= otherVector.y;
  3996. this.z -= otherVector.z;
  3997. this.w -= otherVector.w;
  3998. return this;
  3999. };
  4000. /**
  4001. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4002. * @param otherVector the vector to add
  4003. * @returns the new vector with the result
  4004. */
  4005. Vector4.prototype.subtract = function (otherVector) {
  4006. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4007. };
  4008. /**
  4009. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4010. * @param otherVector the vector to subtract
  4011. * @param result the vector to store the result
  4012. * @returns the current Vector4.
  4013. */
  4014. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4015. result.x = this.x - otherVector.x;
  4016. result.y = this.y - otherVector.y;
  4017. result.z = this.z - otherVector.z;
  4018. result.w = this.w - otherVector.w;
  4019. return this;
  4020. };
  4021. /**
  4022. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4023. */
  4024. /**
  4025. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4026. * @param x value to subtract
  4027. * @param y value to subtract
  4028. * @param z value to subtract
  4029. * @param w value to subtract
  4030. * @returns new vector containing the result
  4031. */
  4032. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4033. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4034. };
  4035. /**
  4036. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4037. * @param x value to subtract
  4038. * @param y value to subtract
  4039. * @param z value to subtract
  4040. * @param w value to subtract
  4041. * @param result the vector to store the result in
  4042. * @returns the current Vector4.
  4043. */
  4044. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4045. result.x = this.x - x;
  4046. result.y = this.y - y;
  4047. result.z = this.z - z;
  4048. result.w = this.w - w;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4053. * @returns a new vector with the negated values
  4054. */
  4055. Vector4.prototype.negate = function () {
  4056. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4057. };
  4058. /**
  4059. * Multiplies the current Vector4 coordinates by scale (float).
  4060. * @param scale the number to scale with
  4061. * @returns the updated Vector4.
  4062. */
  4063. Vector4.prototype.scaleInPlace = function (scale) {
  4064. this.x *= scale;
  4065. this.y *= scale;
  4066. this.z *= scale;
  4067. this.w *= scale;
  4068. return this;
  4069. };
  4070. /**
  4071. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4072. * @param scale the number to scale with
  4073. * @returns a new vector with the result
  4074. */
  4075. Vector4.prototype.scale = function (scale) {
  4076. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4077. };
  4078. /**
  4079. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4080. * @param scale the number to scale with
  4081. * @param result a vector to store the result in
  4082. * @returns the current Vector4.
  4083. */
  4084. Vector4.prototype.scaleToRef = function (scale, result) {
  4085. result.x = this.x * scale;
  4086. result.y = this.y * scale;
  4087. result.z = this.z * scale;
  4088. result.w = this.w * scale;
  4089. return this;
  4090. };
  4091. /**
  4092. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4093. * @param scale defines the scale factor
  4094. * @param result defines the Vector4 object where to store the result
  4095. * @returns the unmodified current Vector4
  4096. */
  4097. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4098. result.x += this.x * scale;
  4099. result.y += this.y * scale;
  4100. result.z += this.z * scale;
  4101. result.w += this.w * scale;
  4102. return this;
  4103. };
  4104. /**
  4105. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4106. * @param otherVector the vector to compare against
  4107. * @returns true if they are equal
  4108. */
  4109. Vector4.prototype.equals = function (otherVector) {
  4110. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4111. };
  4112. /**
  4113. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4114. * @param otherVector vector to compare against
  4115. * @param epsilon (Default: very small number)
  4116. * @returns true if they are equal
  4117. */
  4118. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4119. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4120. return otherVector
  4121. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4122. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4123. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4124. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4125. };
  4126. /**
  4127. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4128. * @param x x value to compare against
  4129. * @param y y value to compare against
  4130. * @param z z value to compare against
  4131. * @param w w value to compare against
  4132. * @returns true if equal
  4133. */
  4134. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4135. return this.x === x && this.y === y && this.z === z && this.w === w;
  4136. };
  4137. /**
  4138. * Multiplies in place the current Vector4 by the given one.
  4139. * @param otherVector vector to multiple with
  4140. * @returns the updated Vector4.
  4141. */
  4142. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4143. this.x *= otherVector.x;
  4144. this.y *= otherVector.y;
  4145. this.z *= otherVector.z;
  4146. this.w *= otherVector.w;
  4147. return this;
  4148. };
  4149. /**
  4150. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4151. * @param otherVector vector to multiple with
  4152. * @returns resulting new vector
  4153. */
  4154. Vector4.prototype.multiply = function (otherVector) {
  4155. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4156. };
  4157. /**
  4158. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4159. * @param otherVector vector to multiple with
  4160. * @param result vector to store the result
  4161. * @returns the current Vector4.
  4162. */
  4163. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4164. result.x = this.x * otherVector.x;
  4165. result.y = this.y * otherVector.y;
  4166. result.z = this.z * otherVector.z;
  4167. result.w = this.w * otherVector.w;
  4168. return this;
  4169. };
  4170. /**
  4171. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4172. * @param x x value multiply with
  4173. * @param y y value multiply with
  4174. * @param z z value multiply with
  4175. * @param w w value multiply with
  4176. * @returns resulting new vector
  4177. */
  4178. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4179. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4180. };
  4181. /**
  4182. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4183. * @param otherVector vector to devide with
  4184. * @returns resulting new vector
  4185. */
  4186. Vector4.prototype.divide = function (otherVector) {
  4187. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4188. };
  4189. /**
  4190. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4191. * @param otherVector vector to devide with
  4192. * @param result vector to store the result
  4193. * @returns the current Vector4.
  4194. */
  4195. Vector4.prototype.divideToRef = function (otherVector, result) {
  4196. result.x = this.x / otherVector.x;
  4197. result.y = this.y / otherVector.y;
  4198. result.z = this.z / otherVector.z;
  4199. result.w = this.w / otherVector.w;
  4200. return this;
  4201. };
  4202. /**
  4203. * Divides the current Vector3 coordinates by the given ones.
  4204. * @param otherVector vector to devide with
  4205. * @returns the updated Vector3.
  4206. */
  4207. Vector4.prototype.divideInPlace = function (otherVector) {
  4208. return this.divideToRef(otherVector, this);
  4209. };
  4210. /**
  4211. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4212. * @param other defines the second operand
  4213. * @returns the current updated Vector4
  4214. */
  4215. Vector4.prototype.minimizeInPlace = function (other) {
  4216. if (other.x < this.x)
  4217. this.x = other.x;
  4218. if (other.y < this.y)
  4219. this.y = other.y;
  4220. if (other.z < this.z)
  4221. this.z = other.z;
  4222. if (other.w < this.w)
  4223. this.w = other.w;
  4224. return this;
  4225. };
  4226. /**
  4227. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4228. * @param other defines the second operand
  4229. * @returns the current updated Vector4
  4230. */
  4231. Vector4.prototype.maximizeInPlace = function (other) {
  4232. if (other.x > this.x)
  4233. this.x = other.x;
  4234. if (other.y > this.y)
  4235. this.y = other.y;
  4236. if (other.z > this.z)
  4237. this.z = other.z;
  4238. if (other.w > this.w)
  4239. this.w = other.w;
  4240. return this;
  4241. };
  4242. /**
  4243. * Gets a new Vector4 from current Vector4 floored values
  4244. * @returns a new Vector4
  4245. */
  4246. Vector4.prototype.floor = function () {
  4247. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4248. };
  4249. /**
  4250. * Gets a new Vector4 from current Vector3 floored values
  4251. * @returns a new Vector4
  4252. */
  4253. Vector4.prototype.fract = function () {
  4254. 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));
  4255. };
  4256. // Properties
  4257. /**
  4258. * Returns the Vector4 length (float).
  4259. * @returns the length
  4260. */
  4261. Vector4.prototype.length = function () {
  4262. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4263. };
  4264. /**
  4265. * Returns the Vector4 squared length (float).
  4266. * @returns the length squared
  4267. */
  4268. Vector4.prototype.lengthSquared = function () {
  4269. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4270. };
  4271. // Methods
  4272. /**
  4273. * Normalizes in place the Vector4.
  4274. * @returns the updated Vector4.
  4275. */
  4276. Vector4.prototype.normalize = function () {
  4277. var len = this.length();
  4278. if (len === 0)
  4279. return this;
  4280. var num = 1.0 / len;
  4281. this.x *= num;
  4282. this.y *= num;
  4283. this.z *= num;
  4284. this.w *= num;
  4285. return this;
  4286. };
  4287. /**
  4288. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4289. * @returns this converted to a new vector3
  4290. */
  4291. Vector4.prototype.toVector3 = function () {
  4292. return new Vector3(this.x, this.y, this.z);
  4293. };
  4294. /**
  4295. * Returns a new Vector4 copied from the current one.
  4296. * @returns the new cloned vector
  4297. */
  4298. Vector4.prototype.clone = function () {
  4299. return new Vector4(this.x, this.y, this.z, this.w);
  4300. };
  4301. /**
  4302. * Updates the current Vector4 with the given one coordinates.
  4303. * @param source the source vector to copy from
  4304. * @returns the updated Vector4.
  4305. */
  4306. Vector4.prototype.copyFrom = function (source) {
  4307. this.x = source.x;
  4308. this.y = source.y;
  4309. this.z = source.z;
  4310. this.w = source.w;
  4311. return this;
  4312. };
  4313. /**
  4314. * Updates the current Vector4 coordinates with the given floats.
  4315. * @param x float to copy from
  4316. * @param y float to copy from
  4317. * @param z float to copy from
  4318. * @param w float to copy from
  4319. * @returns the updated Vector4.
  4320. */
  4321. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4322. this.x = x;
  4323. this.y = y;
  4324. this.z = z;
  4325. this.w = w;
  4326. return this;
  4327. };
  4328. /**
  4329. * Updates the current Vector4 coordinates with the given floats.
  4330. * @param x float to set from
  4331. * @param y float to set from
  4332. * @param z float to set from
  4333. * @param w float to set from
  4334. * @returns the updated Vector4.
  4335. */
  4336. Vector4.prototype.set = function (x, y, z, w) {
  4337. return this.copyFromFloats(x, y, z, w);
  4338. };
  4339. // Statics
  4340. /**
  4341. * Returns a new Vector4 set from the starting index of the given array.
  4342. * @param array the array to pull values from
  4343. * @param offset the offset into the array to start at
  4344. * @returns the new vector
  4345. */
  4346. Vector4.FromArray = function (array, offset) {
  4347. if (!offset) {
  4348. offset = 0;
  4349. }
  4350. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4351. };
  4352. /**
  4353. * Updates the given vector "result" from the starting index of the given array.
  4354. * @param array the array to pull values from
  4355. * @param offset the offset into the array to start at
  4356. * @param result the vector to store the result in
  4357. */
  4358. Vector4.FromArrayToRef = function (array, offset, result) {
  4359. result.x = array[offset];
  4360. result.y = array[offset + 1];
  4361. result.z = array[offset + 2];
  4362. result.w = array[offset + 3];
  4363. };
  4364. /**
  4365. * Updates the given vector "result" from the starting index of the given Float32Array.
  4366. * @param array the array to pull values from
  4367. * @param offset the offset into the array to start at
  4368. * @param result the vector to store the result in
  4369. */
  4370. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4371. Vector4.FromArrayToRef(array, offset, result);
  4372. };
  4373. /**
  4374. * Updates the given vector "result" coordinates from the given floats.
  4375. * @param x float to set from
  4376. * @param y float to set from
  4377. * @param z float to set from
  4378. * @param w float to set from
  4379. * @param result the vector to the floats in
  4380. */
  4381. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4382. result.x = x;
  4383. result.y = y;
  4384. result.z = z;
  4385. result.w = w;
  4386. };
  4387. /**
  4388. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4389. * @returns the new vector
  4390. */
  4391. Vector4.Zero = function () {
  4392. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4393. };
  4394. /**
  4395. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4396. * @returns the new vector
  4397. */
  4398. Vector4.One = function () {
  4399. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4400. };
  4401. /**
  4402. * Returns a new normalized Vector4 from the given one.
  4403. * @param vector the vector to normalize
  4404. * @returns the vector
  4405. */
  4406. Vector4.Normalize = function (vector) {
  4407. var result = Vector4.Zero();
  4408. Vector4.NormalizeToRef(vector, result);
  4409. return result;
  4410. };
  4411. /**
  4412. * Updates the given vector "result" from the normalization of the given one.
  4413. * @param vector the vector to normalize
  4414. * @param result the vector to store the result in
  4415. */
  4416. Vector4.NormalizeToRef = function (vector, result) {
  4417. result.copyFrom(vector);
  4418. result.normalize();
  4419. };
  4420. /**
  4421. * Returns a vector with the minimum values from the left and right vectors
  4422. * @param left left vector to minimize
  4423. * @param right right vector to minimize
  4424. * @returns a new vector with the minimum of the left and right vector values
  4425. */
  4426. Vector4.Minimize = function (left, right) {
  4427. var min = left.clone();
  4428. min.minimizeInPlace(right);
  4429. return min;
  4430. };
  4431. /**
  4432. * Returns a vector with the maximum values from the left and right vectors
  4433. * @param left left vector to maximize
  4434. * @param right right vector to maximize
  4435. * @returns a new vector with the maximum of the left and right vector values
  4436. */
  4437. Vector4.Maximize = function (left, right) {
  4438. var max = left.clone();
  4439. max.maximizeInPlace(right);
  4440. return max;
  4441. };
  4442. /**
  4443. * Returns the distance (float) between the vectors "value1" and "value2".
  4444. * @param value1 value to calulate the distance between
  4445. * @param value2 value to calulate the distance between
  4446. * @return the distance between the two vectors
  4447. */
  4448. Vector4.Distance = function (value1, value2) {
  4449. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4450. };
  4451. /**
  4452. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4453. * @param value1 value to calulate the distance between
  4454. * @param value2 value to calulate the distance between
  4455. * @return the distance between the two vectors squared
  4456. */
  4457. Vector4.DistanceSquared = function (value1, value2) {
  4458. var x = value1.x - value2.x;
  4459. var y = value1.y - value2.y;
  4460. var z = value1.z - value2.z;
  4461. var w = value1.w - value2.w;
  4462. return (x * x) + (y * y) + (z * z) + (w * w);
  4463. };
  4464. /**
  4465. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4466. * @param value1 value to calulate the center between
  4467. * @param value2 value to calulate the center between
  4468. * @return the center between the two vectors
  4469. */
  4470. Vector4.Center = function (value1, value2) {
  4471. var center = value1.add(value2);
  4472. center.scaleInPlace(0.5);
  4473. return center;
  4474. };
  4475. /**
  4476. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4477. * This methods computes transformed normalized direction vectors only.
  4478. * @param vector the vector to transform
  4479. * @param transformation the transformation matrix to apply
  4480. * @returns the new vector
  4481. */
  4482. Vector4.TransformNormal = function (vector, transformation) {
  4483. var result = Vector4.Zero();
  4484. Vector4.TransformNormalToRef(vector, transformation, result);
  4485. return result;
  4486. };
  4487. /**
  4488. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4489. * This methods computes transformed normalized direction vectors only.
  4490. * @param vector the vector to transform
  4491. * @param transformation the transformation matrix to apply
  4492. * @param result the vector to store the result in
  4493. */
  4494. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4495. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4496. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4497. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4498. result.x = x;
  4499. result.y = y;
  4500. result.z = z;
  4501. result.w = vector.w;
  4502. };
  4503. /**
  4504. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4505. * This methods computes transformed normalized direction vectors only.
  4506. * @param x value to transform
  4507. * @param y value to transform
  4508. * @param z value to transform
  4509. * @param w value to transform
  4510. * @param transformation the transformation matrix to apply
  4511. * @param result the vector to store the results in
  4512. */
  4513. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4514. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4515. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4516. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4517. result.w = w;
  4518. };
  4519. return Vector4;
  4520. }());
  4521. BABYLON.Vector4 = Vector4;
  4522. /**
  4523. * Size containing widht and height
  4524. */
  4525. var Size = /** @class */ (function () {
  4526. /**
  4527. * Creates a Size object from the given width and height (floats).
  4528. * @param width width of the new size
  4529. * @param height height of the new size
  4530. */
  4531. function Size(width, height) {
  4532. this.width = width;
  4533. this.height = height;
  4534. }
  4535. /**
  4536. * Returns a string with the Size width and height
  4537. * @returns a string with the Size width and height
  4538. */
  4539. Size.prototype.toString = function () {
  4540. return "{W: " + this.width + ", H: " + this.height + "}";
  4541. };
  4542. /**
  4543. * "Size"
  4544. * @returns the string "Size"
  4545. */
  4546. Size.prototype.getClassName = function () {
  4547. return "Size";
  4548. };
  4549. /**
  4550. * Returns the Size hash code.
  4551. * @returns a hash code for a unique width and height
  4552. */
  4553. Size.prototype.getHashCode = function () {
  4554. var hash = this.width || 0;
  4555. hash = (hash * 397) ^ (this.height || 0);
  4556. return hash;
  4557. };
  4558. /**
  4559. * Updates the current size from the given one.
  4560. * @param src the given size
  4561. */
  4562. Size.prototype.copyFrom = function (src) {
  4563. this.width = src.width;
  4564. this.height = src.height;
  4565. };
  4566. /**
  4567. * Updates in place the current Size from the given floats.
  4568. * @param width width of the new size
  4569. * @param height height of the new size
  4570. * @returns the updated Size.
  4571. */
  4572. Size.prototype.copyFromFloats = function (width, height) {
  4573. this.width = width;
  4574. this.height = height;
  4575. return this;
  4576. };
  4577. /**
  4578. * Updates in place the current Size from the given floats.
  4579. * @param width width to set
  4580. * @param height height to set
  4581. * @returns the updated Size.
  4582. */
  4583. Size.prototype.set = function (width, height) {
  4584. return this.copyFromFloats(width, height);
  4585. };
  4586. /**
  4587. * Multiplies the width and height by numbers
  4588. * @param w factor to multiple the width by
  4589. * @param h factor to multiple the height by
  4590. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4591. */
  4592. Size.prototype.multiplyByFloats = function (w, h) {
  4593. return new Size(this.width * w, this.height * h);
  4594. };
  4595. /**
  4596. * Clones the size
  4597. * @returns a new Size copied from the given one.
  4598. */
  4599. Size.prototype.clone = function () {
  4600. return new Size(this.width, this.height);
  4601. };
  4602. /**
  4603. * True if the current Size and the given one width and height are strictly equal.
  4604. * @param other the other size to compare against
  4605. * @returns True if the current Size and the given one width and height are strictly equal.
  4606. */
  4607. Size.prototype.equals = function (other) {
  4608. if (!other) {
  4609. return false;
  4610. }
  4611. return (this.width === other.width) && (this.height === other.height);
  4612. };
  4613. Object.defineProperty(Size.prototype, "surface", {
  4614. /**
  4615. * The surface of the Size : width * height (float).
  4616. */
  4617. get: function () {
  4618. return this.width * this.height;
  4619. },
  4620. enumerable: true,
  4621. configurable: true
  4622. });
  4623. /**
  4624. * Create a new size of zero
  4625. * @returns a new Size set to (0.0, 0.0)
  4626. */
  4627. Size.Zero = function () {
  4628. return new Size(0.0, 0.0);
  4629. };
  4630. /**
  4631. * Sums the width and height of two sizes
  4632. * @param otherSize size to add to this size
  4633. * @returns a new Size set as the addition result of the current Size and the given one.
  4634. */
  4635. Size.prototype.add = function (otherSize) {
  4636. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4637. return r;
  4638. };
  4639. /**
  4640. * Subtracts the width and height of two
  4641. * @param otherSize size to subtract to this size
  4642. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4643. */
  4644. Size.prototype.subtract = function (otherSize) {
  4645. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4646. return r;
  4647. };
  4648. /**
  4649. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4650. * @param start starting size to lerp between
  4651. * @param end end size to lerp between
  4652. * @param amount amount to lerp between the start and end values
  4653. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4654. */
  4655. Size.Lerp = function (start, end, amount) {
  4656. var w = start.width + ((end.width - start.width) * amount);
  4657. var h = start.height + ((end.height - start.height) * amount);
  4658. return new Size(w, h);
  4659. };
  4660. return Size;
  4661. }());
  4662. BABYLON.Size = Size;
  4663. /**
  4664. * Class used to store quaternion data
  4665. * @see https://en.wikipedia.org/wiki/Quaternion
  4666. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4667. */
  4668. var Quaternion = /** @class */ (function () {
  4669. /**
  4670. * Creates a new Quaternion from the given floats
  4671. * @param x defines the first component (0 by default)
  4672. * @param y defines the second component (0 by default)
  4673. * @param z defines the third component (0 by default)
  4674. * @param w defines the fourth component (1.0 by default)
  4675. */
  4676. function Quaternion(
  4677. /** defines the first component (0 by default) */
  4678. x,
  4679. /** defines the second component (0 by default) */
  4680. y,
  4681. /** defines the third component (0 by default) */
  4682. z,
  4683. /** defines the fourth component (1.0 by default) */
  4684. w) {
  4685. if (x === void 0) { x = 0.0; }
  4686. if (y === void 0) { y = 0.0; }
  4687. if (z === void 0) { z = 0.0; }
  4688. if (w === void 0) { w = 1.0; }
  4689. this.x = x;
  4690. this.y = y;
  4691. this.z = z;
  4692. this.w = w;
  4693. }
  4694. /**
  4695. * Gets a string representation for the current quaternion
  4696. * @returns a string with the Quaternion coordinates
  4697. */
  4698. Quaternion.prototype.toString = function () {
  4699. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4700. };
  4701. /**
  4702. * Gets the class name of the quaternion
  4703. * @returns the string "Quaternion"
  4704. */
  4705. Quaternion.prototype.getClassName = function () {
  4706. return "Quaternion";
  4707. };
  4708. /**
  4709. * Gets a hash code for this quaternion
  4710. * @returns the quaternion hash code
  4711. */
  4712. Quaternion.prototype.getHashCode = function () {
  4713. var hash = this.x || 0;
  4714. hash = (hash * 397) ^ (this.y || 0);
  4715. hash = (hash * 397) ^ (this.z || 0);
  4716. hash = (hash * 397) ^ (this.w || 0);
  4717. return hash;
  4718. };
  4719. /**
  4720. * Copy the quaternion to an array
  4721. * @returns a new array populated with 4 elements from the quaternion coordinates
  4722. */
  4723. Quaternion.prototype.asArray = function () {
  4724. return [this.x, this.y, this.z, this.w];
  4725. };
  4726. /**
  4727. * Check if two quaternions are equals
  4728. * @param otherQuaternion defines the second operand
  4729. * @return true if the current quaternion and the given one coordinates are strictly equals
  4730. */
  4731. Quaternion.prototype.equals = function (otherQuaternion) {
  4732. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4733. };
  4734. /**
  4735. * Clone the current quaternion
  4736. * @returns a new quaternion copied from the current one
  4737. */
  4738. Quaternion.prototype.clone = function () {
  4739. return new Quaternion(this.x, this.y, this.z, this.w);
  4740. };
  4741. /**
  4742. * Copy a quaternion to the current one
  4743. * @param other defines the other quaternion
  4744. * @returns the updated current quaternion
  4745. */
  4746. Quaternion.prototype.copyFrom = function (other) {
  4747. this.x = other.x;
  4748. this.y = other.y;
  4749. this.z = other.z;
  4750. this.w = other.w;
  4751. return this;
  4752. };
  4753. /**
  4754. * Updates the current quaternion with the given float coordinates
  4755. * @param x defines the x coordinate
  4756. * @param y defines the y coordinate
  4757. * @param z defines the z coordinate
  4758. * @param w defines the w coordinate
  4759. * @returns the updated current quaternion
  4760. */
  4761. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4762. this.x = x;
  4763. this.y = y;
  4764. this.z = z;
  4765. this.w = w;
  4766. return this;
  4767. };
  4768. /**
  4769. * Updates the current quaternion from the given float coordinates
  4770. * @param x defines the x coordinate
  4771. * @param y defines the y coordinate
  4772. * @param z defines the z coordinate
  4773. * @param w defines the w coordinate
  4774. * @returns the updated current quaternion
  4775. */
  4776. Quaternion.prototype.set = function (x, y, z, w) {
  4777. return this.copyFromFloats(x, y, z, w);
  4778. };
  4779. /**
  4780. * Adds two quaternions
  4781. * @param other defines the second operand
  4782. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4783. */
  4784. Quaternion.prototype.add = function (other) {
  4785. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4786. };
  4787. /**
  4788. * Add a quaternion to the current one
  4789. * @param other defines the quaternion to add
  4790. * @returns the current quaternion
  4791. */
  4792. Quaternion.prototype.addInPlace = function (other) {
  4793. this.x += other.x;
  4794. this.y += other.y;
  4795. this.z += other.z;
  4796. this.w += other.w;
  4797. return this;
  4798. };
  4799. /**
  4800. * Subtract two quaternions
  4801. * @param other defines the second operand
  4802. * @returns a new quaternion as the subtraction result of the given one from the current one
  4803. */
  4804. Quaternion.prototype.subtract = function (other) {
  4805. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4806. };
  4807. /**
  4808. * Multiplies the current quaternion by a scale factor
  4809. * @param value defines the scale factor
  4810. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4811. */
  4812. Quaternion.prototype.scale = function (value) {
  4813. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4814. };
  4815. /**
  4816. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4817. * @param scale defines the scale factor
  4818. * @param result defines the Quaternion object where to store the result
  4819. * @returns the unmodified current quaternion
  4820. */
  4821. Quaternion.prototype.scaleToRef = function (scale, result) {
  4822. result.x = this.x * scale;
  4823. result.y = this.y * scale;
  4824. result.z = this.z * scale;
  4825. result.w = this.w * scale;
  4826. return this;
  4827. };
  4828. /**
  4829. * Multiplies in place the current quaternion by a scale factor
  4830. * @param value defines the scale factor
  4831. * @returns the current modified quaternion
  4832. */
  4833. Quaternion.prototype.scaleInPlace = function (value) {
  4834. this.x *= value;
  4835. this.y *= value;
  4836. this.z *= value;
  4837. this.w *= value;
  4838. return this;
  4839. };
  4840. /**
  4841. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4842. * @param scale defines the scale factor
  4843. * @param result defines the Quaternion object where to store the result
  4844. * @returns the unmodified current quaternion
  4845. */
  4846. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4847. result.x += this.x * scale;
  4848. result.y += this.y * scale;
  4849. result.z += this.z * scale;
  4850. result.w += this.w * scale;
  4851. return this;
  4852. };
  4853. /**
  4854. * Multiplies two quaternions
  4855. * @param q1 defines the second operand
  4856. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4857. */
  4858. Quaternion.prototype.multiply = function (q1) {
  4859. var result = new Quaternion(0, 0, 0, 1.0);
  4860. this.multiplyToRef(q1, result);
  4861. return result;
  4862. };
  4863. /**
  4864. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4865. * @param q1 defines the second operand
  4866. * @param result defines the target quaternion
  4867. * @returns the current quaternion
  4868. */
  4869. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4870. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4871. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4872. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4873. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4874. result.copyFromFloats(x, y, z, w);
  4875. return this;
  4876. };
  4877. /**
  4878. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4879. * @param q1 defines the second operand
  4880. * @returns the currentupdated quaternion
  4881. */
  4882. Quaternion.prototype.multiplyInPlace = function (q1) {
  4883. this.multiplyToRef(q1, this);
  4884. return this;
  4885. };
  4886. /**
  4887. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4888. * @param ref defines the target quaternion
  4889. * @returns the current quaternion
  4890. */
  4891. Quaternion.prototype.conjugateToRef = function (ref) {
  4892. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4893. return this;
  4894. };
  4895. /**
  4896. * Conjugates in place (1-q) the current quaternion
  4897. * @returns the current updated quaternion
  4898. */
  4899. Quaternion.prototype.conjugateInPlace = function () {
  4900. this.x *= -1;
  4901. this.y *= -1;
  4902. this.z *= -1;
  4903. return this;
  4904. };
  4905. /**
  4906. * Conjugates in place (1-q) the current quaternion
  4907. * @returns a new quaternion
  4908. */
  4909. Quaternion.prototype.conjugate = function () {
  4910. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4911. return result;
  4912. };
  4913. /**
  4914. * Gets length of current quaternion
  4915. * @returns the quaternion length (float)
  4916. */
  4917. Quaternion.prototype.length = function () {
  4918. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4919. };
  4920. /**
  4921. * Normalize in place the current quaternion
  4922. * @returns the current updated quaternion
  4923. */
  4924. Quaternion.prototype.normalize = function () {
  4925. var length = 1.0 / this.length();
  4926. this.x *= length;
  4927. this.y *= length;
  4928. this.z *= length;
  4929. this.w *= length;
  4930. return this;
  4931. };
  4932. /**
  4933. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4934. * @param order is a reserved parameter and is ignore for now
  4935. * @returns a new Vector3 containing the Euler angles
  4936. */
  4937. Quaternion.prototype.toEulerAngles = function (order) {
  4938. if (order === void 0) { order = "YZX"; }
  4939. var result = Vector3.Zero();
  4940. this.toEulerAnglesToRef(result, order);
  4941. return result;
  4942. };
  4943. /**
  4944. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4945. * @param result defines the vector which will be filled with the Euler angles
  4946. * @param order is a reserved parameter and is ignore for now
  4947. * @returns the current unchanged quaternion
  4948. */
  4949. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4950. if (order === void 0) { order = "YZX"; }
  4951. var qz = this.z;
  4952. var qx = this.x;
  4953. var qy = this.y;
  4954. var qw = this.w;
  4955. var sqw = qw * qw;
  4956. var sqz = qz * qz;
  4957. var sqx = qx * qx;
  4958. var sqy = qy * qy;
  4959. var zAxisY = qy * qz - qx * qw;
  4960. var limit = .4999999;
  4961. if (zAxisY < -limit) {
  4962. result.y = 2 * Math.atan2(qy, qw);
  4963. result.x = Math.PI / 2;
  4964. result.z = 0;
  4965. }
  4966. else if (zAxisY > limit) {
  4967. result.y = 2 * Math.atan2(qy, qw);
  4968. result.x = -Math.PI / 2;
  4969. result.z = 0;
  4970. }
  4971. else {
  4972. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4973. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4974. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4975. }
  4976. return this;
  4977. };
  4978. /**
  4979. * Updates the given rotation matrix with the current quaternion values
  4980. * @param result defines the target matrix
  4981. * @returns the current unchanged quaternion
  4982. */
  4983. Quaternion.prototype.toRotationMatrix = function (result) {
  4984. var xx = this.x * this.x;
  4985. var yy = this.y * this.y;
  4986. var zz = this.z * this.z;
  4987. var xy = this.x * this.y;
  4988. var zw = this.z * this.w;
  4989. var zx = this.z * this.x;
  4990. var yw = this.y * this.w;
  4991. var yz = this.y * this.z;
  4992. var xw = this.x * this.w;
  4993. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4994. result.m[1] = 2.0 * (xy + zw);
  4995. result.m[2] = 2.0 * (zx - yw);
  4996. result.m[3] = 0;
  4997. result.m[4] = 2.0 * (xy - zw);
  4998. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4999. result.m[6] = 2.0 * (yz + xw);
  5000. result.m[7] = 0;
  5001. result.m[8] = 2.0 * (zx + yw);
  5002. result.m[9] = 2.0 * (yz - xw);
  5003. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5004. result.m[11] = 0;
  5005. result.m[12] = 0;
  5006. result.m[13] = 0;
  5007. result.m[14] = 0;
  5008. result.m[15] = 1.0;
  5009. result._markAsUpdated();
  5010. return this;
  5011. };
  5012. /**
  5013. * Updates the current quaternion from the given rotation matrix values
  5014. * @param matrix defines the source matrix
  5015. * @returns the current updated quaternion
  5016. */
  5017. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5018. Quaternion.FromRotationMatrixToRef(matrix, this);
  5019. return this;
  5020. };
  5021. // Statics
  5022. /**
  5023. * Creates a new quaternion from a rotation matrix
  5024. * @param matrix defines the source matrix
  5025. * @returns a new quaternion created from the given rotation matrix values
  5026. */
  5027. Quaternion.FromRotationMatrix = function (matrix) {
  5028. var result = new Quaternion();
  5029. Quaternion.FromRotationMatrixToRef(matrix, result);
  5030. return result;
  5031. };
  5032. /**
  5033. * Updates the given quaternion with the given rotation matrix values
  5034. * @param matrix defines the source matrix
  5035. * @param result defines the target quaternion
  5036. */
  5037. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5038. var data = matrix.m;
  5039. var m11 = data[0], m12 = data[4], m13 = data[8];
  5040. var m21 = data[1], m22 = data[5], m23 = data[9];
  5041. var m31 = data[2], m32 = data[6], m33 = data[10];
  5042. var trace = m11 + m22 + m33;
  5043. var s;
  5044. if (trace > 0) {
  5045. s = 0.5 / Math.sqrt(trace + 1.0);
  5046. result.w = 0.25 / s;
  5047. result.x = (m32 - m23) * s;
  5048. result.y = (m13 - m31) * s;
  5049. result.z = (m21 - m12) * s;
  5050. }
  5051. else if (m11 > m22 && m11 > m33) {
  5052. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5053. result.w = (m32 - m23) / s;
  5054. result.x = 0.25 * s;
  5055. result.y = (m12 + m21) / s;
  5056. result.z = (m13 + m31) / s;
  5057. }
  5058. else if (m22 > m33) {
  5059. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5060. result.w = (m13 - m31) / s;
  5061. result.x = (m12 + m21) / s;
  5062. result.y = 0.25 * s;
  5063. result.z = (m23 + m32) / s;
  5064. }
  5065. else {
  5066. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5067. result.w = (m21 - m12) / s;
  5068. result.x = (m13 + m31) / s;
  5069. result.y = (m23 + m32) / s;
  5070. result.z = 0.25 * s;
  5071. }
  5072. };
  5073. /**
  5074. * Returns the dot product (float) between the quaternions "left" and "right"
  5075. * @param left defines the left operand
  5076. * @param right defines the right operand
  5077. * @returns the dot product
  5078. */
  5079. Quaternion.Dot = function (left, right) {
  5080. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5081. };
  5082. /**
  5083. * Checks if the two quaternions are close to each other
  5084. * @param quat0 defines the first quaternion to check
  5085. * @param quat1 defines the second quaternion to check
  5086. * @returns true if the two quaternions are close to each other
  5087. */
  5088. Quaternion.AreClose = function (quat0, quat1) {
  5089. var dot = Quaternion.Dot(quat0, quat1);
  5090. return dot >= 0;
  5091. };
  5092. /**
  5093. * Creates an empty quaternion
  5094. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5095. */
  5096. Quaternion.Zero = function () {
  5097. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5098. };
  5099. /**
  5100. * Inverse a given quaternion
  5101. * @param q defines the source quaternion
  5102. * @returns a new quaternion as the inverted current quaternion
  5103. */
  5104. Quaternion.Inverse = function (q) {
  5105. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5106. };
  5107. /**
  5108. * Creates an identity quaternion
  5109. * @returns the identity quaternion
  5110. */
  5111. Quaternion.Identity = function () {
  5112. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5113. };
  5114. /**
  5115. * Gets a boolean indicating if the given quaternion is identity
  5116. * @param quaternion defines the quaternion to check
  5117. * @returns true if the quaternion is identity
  5118. */
  5119. Quaternion.IsIdentity = function (quaternion) {
  5120. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5121. };
  5122. /**
  5123. * Creates a quaternion from a rotation around an axis
  5124. * @param axis defines the axis to use
  5125. * @param angle defines the angle to use
  5126. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5127. */
  5128. Quaternion.RotationAxis = function (axis, angle) {
  5129. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5130. };
  5131. /**
  5132. * Creates a rotation around an axis and stores it into the given quaternion
  5133. * @param axis defines the axis to use
  5134. * @param angle defines the angle to use
  5135. * @param result defines the target quaternion
  5136. * @returns the target quaternion
  5137. */
  5138. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5139. var sin = Math.sin(angle / 2);
  5140. axis.normalize();
  5141. result.w = Math.cos(angle / 2);
  5142. result.x = axis.x * sin;
  5143. result.y = axis.y * sin;
  5144. result.z = axis.z * sin;
  5145. return result;
  5146. };
  5147. /**
  5148. * Creates a new quaternion from data stored into an array
  5149. * @param array defines the data source
  5150. * @param offset defines the offset in the source array where the data starts
  5151. * @returns a new quaternion
  5152. */
  5153. Quaternion.FromArray = function (array, offset) {
  5154. if (!offset) {
  5155. offset = 0;
  5156. }
  5157. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5158. };
  5159. /**
  5160. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5161. * @param yaw defines the rotation around Y axis
  5162. * @param pitch defines the rotation around X axis
  5163. * @param roll defines the rotation around Z axis
  5164. * @returns the new quaternion
  5165. */
  5166. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5167. var q = new Quaternion();
  5168. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5169. return q;
  5170. };
  5171. /**
  5172. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5173. * @param yaw defines the rotation around Y axis
  5174. * @param pitch defines the rotation around X axis
  5175. * @param roll defines the rotation around Z axis
  5176. * @param result defines the target quaternion
  5177. */
  5178. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5179. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5180. var halfRoll = roll * 0.5;
  5181. var halfPitch = pitch * 0.5;
  5182. var halfYaw = yaw * 0.5;
  5183. var sinRoll = Math.sin(halfRoll);
  5184. var cosRoll = Math.cos(halfRoll);
  5185. var sinPitch = Math.sin(halfPitch);
  5186. var cosPitch = Math.cos(halfPitch);
  5187. var sinYaw = Math.sin(halfYaw);
  5188. var cosYaw = Math.cos(halfYaw);
  5189. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5190. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5191. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5192. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5193. };
  5194. /**
  5195. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5196. * @param alpha defines the rotation around first axis
  5197. * @param beta defines the rotation around second axis
  5198. * @param gamma defines the rotation around third axis
  5199. * @returns the new quaternion
  5200. */
  5201. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5202. var result = new Quaternion();
  5203. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5204. return result;
  5205. };
  5206. /**
  5207. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5208. * @param alpha defines the rotation around first axis
  5209. * @param beta defines the rotation around second axis
  5210. * @param gamma defines the rotation around third axis
  5211. * @param result defines the target quaternion
  5212. */
  5213. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5214. // Produces a quaternion from Euler angles in the z-x-z orientation
  5215. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5216. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5217. var halfBeta = beta * 0.5;
  5218. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5219. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5220. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5221. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5222. };
  5223. /**
  5224. * 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)
  5225. * @param axis1 defines the first axis
  5226. * @param axis2 defines the second axis
  5227. * @param axis3 defines the third axis
  5228. * @returns the new quaternion
  5229. */
  5230. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5231. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5232. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5233. return quat;
  5234. };
  5235. /**
  5236. * 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
  5237. * @param axis1 defines the first axis
  5238. * @param axis2 defines the second axis
  5239. * @param axis3 defines the third axis
  5240. * @param ref defines the target quaternion
  5241. */
  5242. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5243. var rotMat = MathTmp.Matrix[0];
  5244. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5245. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5246. };
  5247. /**
  5248. * Interpolates between two quaternions
  5249. * @param left defines first quaternion
  5250. * @param right defines second quaternion
  5251. * @param amount defines the gradient to use
  5252. * @returns the new interpolated quaternion
  5253. */
  5254. Quaternion.Slerp = function (left, right, amount) {
  5255. var result = Quaternion.Identity();
  5256. Quaternion.SlerpToRef(left, right, amount, result);
  5257. return result;
  5258. };
  5259. /**
  5260. * Interpolates between two quaternions and stores it into a target quaternion
  5261. * @param left defines first quaternion
  5262. * @param right defines second quaternion
  5263. * @param amount defines the gradient to use
  5264. * @param result defines the target quaternion
  5265. */
  5266. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5267. var num2;
  5268. var num3;
  5269. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5270. var flag = false;
  5271. if (num4 < 0) {
  5272. flag = true;
  5273. num4 = -num4;
  5274. }
  5275. if (num4 > 0.999999) {
  5276. num3 = 1 - amount;
  5277. num2 = flag ? -amount : amount;
  5278. }
  5279. else {
  5280. var num5 = Math.acos(num4);
  5281. var num6 = (1.0 / Math.sin(num5));
  5282. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5283. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5284. }
  5285. result.x = (num3 * left.x) + (num2 * right.x);
  5286. result.y = (num3 * left.y) + (num2 * right.y);
  5287. result.z = (num3 * left.z) + (num2 * right.z);
  5288. result.w = (num3 * left.w) + (num2 * right.w);
  5289. };
  5290. /**
  5291. * Interpolate between two quaternions using Hermite interpolation
  5292. * @param value1 defines first quaternion
  5293. * @param tangent1 defines the incoming tangent
  5294. * @param value2 defines second quaternion
  5295. * @param tangent2 defines the outgoing tangent
  5296. * @param amount defines the target quaternion
  5297. * @returns the new interpolated quaternion
  5298. */
  5299. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5300. var squared = amount * amount;
  5301. var cubed = amount * squared;
  5302. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5303. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5304. var part3 = (cubed - (2.0 * squared)) + amount;
  5305. var part4 = cubed - squared;
  5306. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5307. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5308. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5309. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5310. return new Quaternion(x, y, z, w);
  5311. };
  5312. return Quaternion;
  5313. }());
  5314. BABYLON.Quaternion = Quaternion;
  5315. /**
  5316. * Class used to store matrix data (4x4)
  5317. */
  5318. var Matrix = /** @class */ (function () {
  5319. /**
  5320. * Creates an empty matrix (filled with zeros)
  5321. */
  5322. function Matrix() {
  5323. this._isIdentity = false;
  5324. this._isIdentityDirty = true;
  5325. /**
  5326. * Gets or sets the internal data of the matrix
  5327. */
  5328. this.m = new Float32Array(16);
  5329. this._markAsUpdated();
  5330. }
  5331. /** @hidden */
  5332. Matrix.prototype._markAsUpdated = function () {
  5333. this.updateFlag = Matrix._updateFlagSeed++;
  5334. this._isIdentityDirty = true;
  5335. };
  5336. // Properties
  5337. /**
  5338. * Check if the current matrix is indentity
  5339. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5340. * @returns true is the matrix is the identity matrix
  5341. */
  5342. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5343. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5344. if (this._isIdentityDirty) {
  5345. this._isIdentityDirty = false;
  5346. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5347. this._isIdentity = false;
  5348. }
  5349. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5350. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5351. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5352. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5353. this._isIdentity = false;
  5354. }
  5355. else {
  5356. this._isIdentity = true;
  5357. }
  5358. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5359. this._isIdentity = false;
  5360. }
  5361. }
  5362. return this._isIdentity;
  5363. };
  5364. /**
  5365. * Gets the determinant of the matrix
  5366. * @returns the matrix determinant
  5367. */
  5368. Matrix.prototype.determinant = function () {
  5369. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5370. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5371. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5372. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5373. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5374. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5375. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5376. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5377. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5378. };
  5379. // Methods
  5380. /**
  5381. * Returns the matrix as a Float32Array
  5382. * @returns the matrix underlying array
  5383. */
  5384. Matrix.prototype.toArray = function () {
  5385. return this.m;
  5386. };
  5387. /**
  5388. * Returns the matrix as a Float32Array
  5389. * @returns the matrix underlying array.
  5390. */
  5391. Matrix.prototype.asArray = function () {
  5392. return this.toArray();
  5393. };
  5394. /**
  5395. * Inverts the current matrix in place
  5396. * @returns the current inverted matrix
  5397. */
  5398. Matrix.prototype.invert = function () {
  5399. this.invertToRef(this);
  5400. return this;
  5401. };
  5402. /**
  5403. * Sets all the matrix elements to zero
  5404. * @returns the current matrix
  5405. */
  5406. Matrix.prototype.reset = function () {
  5407. for (var index = 0; index < 16; index++) {
  5408. this.m[index] = 0.0;
  5409. }
  5410. this._markAsUpdated();
  5411. return this;
  5412. };
  5413. /**
  5414. * Adds the current matrix with a second one
  5415. * @param other defines the matrix to add
  5416. * @returns a new matrix as the addition of the current matrix and the given one
  5417. */
  5418. Matrix.prototype.add = function (other) {
  5419. var result = new Matrix();
  5420. this.addToRef(other, result);
  5421. return result;
  5422. };
  5423. /**
  5424. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5425. * @param other defines the matrix to add
  5426. * @param result defines the target matrix
  5427. * @returns the current matrix
  5428. */
  5429. Matrix.prototype.addToRef = function (other, result) {
  5430. for (var index = 0; index < 16; index++) {
  5431. result.m[index] = this.m[index] + other.m[index];
  5432. }
  5433. result._markAsUpdated();
  5434. return this;
  5435. };
  5436. /**
  5437. * Adds in place the given matrix to the current matrix
  5438. * @param other defines the second operand
  5439. * @returns the current updated matrix
  5440. */
  5441. Matrix.prototype.addToSelf = function (other) {
  5442. for (var index = 0; index < 16; index++) {
  5443. this.m[index] += other.m[index];
  5444. }
  5445. this._markAsUpdated();
  5446. return this;
  5447. };
  5448. /**
  5449. * Sets the given matrix to the current inverted Matrix
  5450. * @param other defines the target matrix
  5451. * @returns the unmodified current matrix
  5452. */
  5453. Matrix.prototype.invertToRef = function (other) {
  5454. var l1 = this.m[0];
  5455. var l2 = this.m[1];
  5456. var l3 = this.m[2];
  5457. var l4 = this.m[3];
  5458. var l5 = this.m[4];
  5459. var l6 = this.m[5];
  5460. var l7 = this.m[6];
  5461. var l8 = this.m[7];
  5462. var l9 = this.m[8];
  5463. var l10 = this.m[9];
  5464. var l11 = this.m[10];
  5465. var l12 = this.m[11];
  5466. var l13 = this.m[12];
  5467. var l14 = this.m[13];
  5468. var l15 = this.m[14];
  5469. var l16 = this.m[15];
  5470. var l17 = (l11 * l16) - (l12 * l15);
  5471. var l18 = (l10 * l16) - (l12 * l14);
  5472. var l19 = (l10 * l15) - (l11 * l14);
  5473. var l20 = (l9 * l16) - (l12 * l13);
  5474. var l21 = (l9 * l15) - (l11 * l13);
  5475. var l22 = (l9 * l14) - (l10 * l13);
  5476. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5477. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5478. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5479. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5480. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5481. var l28 = (l7 * l16) - (l8 * l15);
  5482. var l29 = (l6 * l16) - (l8 * l14);
  5483. var l30 = (l6 * l15) - (l7 * l14);
  5484. var l31 = (l5 * l16) - (l8 * l13);
  5485. var l32 = (l5 * l15) - (l7 * l13);
  5486. var l33 = (l5 * l14) - (l6 * l13);
  5487. var l34 = (l7 * l12) - (l8 * l11);
  5488. var l35 = (l6 * l12) - (l8 * l10);
  5489. var l36 = (l6 * l11) - (l7 * l10);
  5490. var l37 = (l5 * l12) - (l8 * l9);
  5491. var l38 = (l5 * l11) - (l7 * l9);
  5492. var l39 = (l5 * l10) - (l6 * l9);
  5493. other.m[0] = l23 * l27;
  5494. other.m[4] = l24 * l27;
  5495. other.m[8] = l25 * l27;
  5496. other.m[12] = l26 * l27;
  5497. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5498. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5499. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5500. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5501. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5502. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5503. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5504. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5505. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5506. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5507. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5508. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5509. other._markAsUpdated();
  5510. return this;
  5511. };
  5512. /**
  5513. * Inserts the translation vector (using 3 floats) in the current matrix
  5514. * @param x defines the 1st component of the translation
  5515. * @param y defines the 2nd component of the translation
  5516. * @param z defines the 3rd component of the translation
  5517. * @returns the current updated matrix
  5518. */
  5519. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5520. this.m[12] = x;
  5521. this.m[13] = y;
  5522. this.m[14] = z;
  5523. this._markAsUpdated();
  5524. return this;
  5525. };
  5526. /**
  5527. * Inserts the translation vector in the current matrix
  5528. * @param vector3 defines the translation to insert
  5529. * @returns the current updated matrix
  5530. */
  5531. Matrix.prototype.setTranslation = function (vector3) {
  5532. this.m[12] = vector3.x;
  5533. this.m[13] = vector3.y;
  5534. this.m[14] = vector3.z;
  5535. this._markAsUpdated();
  5536. return this;
  5537. };
  5538. /**
  5539. * Gets the translation value of the current matrix
  5540. * @returns a new Vector3 as the extracted translation from the matrix
  5541. */
  5542. Matrix.prototype.getTranslation = function () {
  5543. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5544. };
  5545. /**
  5546. * Fill a Vector3 with the extracted translation from the matrix
  5547. * @param result defines the Vector3 where to store the translation
  5548. * @returns the current matrix
  5549. */
  5550. Matrix.prototype.getTranslationToRef = function (result) {
  5551. result.x = this.m[12];
  5552. result.y = this.m[13];
  5553. result.z = this.m[14];
  5554. return this;
  5555. };
  5556. /**
  5557. * Remove rotation and scaling part from the matrix
  5558. * @returns the updated matrix
  5559. */
  5560. Matrix.prototype.removeRotationAndScaling = function () {
  5561. this.setRowFromFloats(0, 1, 0, 0, 0);
  5562. this.setRowFromFloats(1, 0, 1, 0, 0);
  5563. this.setRowFromFloats(2, 0, 0, 1, 0);
  5564. return this;
  5565. };
  5566. /**
  5567. * Multiply two matrices
  5568. * @param other defines the second operand
  5569. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5570. */
  5571. Matrix.prototype.multiply = function (other) {
  5572. var result = new Matrix();
  5573. this.multiplyToRef(other, result);
  5574. return result;
  5575. };
  5576. /**
  5577. * Copy the current matrix from the given one
  5578. * @param other defines the source matrix
  5579. * @returns the current updated matrix
  5580. */
  5581. Matrix.prototype.copyFrom = function (other) {
  5582. for (var index = 0; index < 16; index++) {
  5583. this.m[index] = other.m[index];
  5584. }
  5585. this._markAsUpdated();
  5586. return this;
  5587. };
  5588. /**
  5589. * Populates the given array from the starting index with the current matrix values
  5590. * @param array defines the target array
  5591. * @param offset defines the offset in the target array where to start storing values
  5592. * @returns the current matrix
  5593. */
  5594. Matrix.prototype.copyToArray = function (array, offset) {
  5595. if (offset === void 0) { offset = 0; }
  5596. for (var index = 0; index < 16; index++) {
  5597. array[offset + index] = this.m[index];
  5598. }
  5599. return this;
  5600. };
  5601. /**
  5602. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5603. * @param other defines the second operand
  5604. * @param result defines the matrix where to store the multiplication
  5605. * @returns the current matrix
  5606. */
  5607. Matrix.prototype.multiplyToRef = function (other, result) {
  5608. this.multiplyToArray(other, result.m, 0);
  5609. result._markAsUpdated();
  5610. return this;
  5611. };
  5612. /**
  5613. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5614. * @param other defines the second operand
  5615. * @param result defines the array where to store the multiplication
  5616. * @param offset defines the offset in the target array where to start storing values
  5617. * @returns the current matrix
  5618. */
  5619. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5620. var tm0 = this.m[0];
  5621. var tm1 = this.m[1];
  5622. var tm2 = this.m[2];
  5623. var tm3 = this.m[3];
  5624. var tm4 = this.m[4];
  5625. var tm5 = this.m[5];
  5626. var tm6 = this.m[6];
  5627. var tm7 = this.m[7];
  5628. var tm8 = this.m[8];
  5629. var tm9 = this.m[9];
  5630. var tm10 = this.m[10];
  5631. var tm11 = this.m[11];
  5632. var tm12 = this.m[12];
  5633. var tm13 = this.m[13];
  5634. var tm14 = this.m[14];
  5635. var tm15 = this.m[15];
  5636. var om0 = other.m[0];
  5637. var om1 = other.m[1];
  5638. var om2 = other.m[2];
  5639. var om3 = other.m[3];
  5640. var om4 = other.m[4];
  5641. var om5 = other.m[5];
  5642. var om6 = other.m[6];
  5643. var om7 = other.m[7];
  5644. var om8 = other.m[8];
  5645. var om9 = other.m[9];
  5646. var om10 = other.m[10];
  5647. var om11 = other.m[11];
  5648. var om12 = other.m[12];
  5649. var om13 = other.m[13];
  5650. var om14 = other.m[14];
  5651. var om15 = other.m[15];
  5652. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5653. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5654. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5655. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5656. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5657. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5658. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5659. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5660. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5661. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5662. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5663. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5664. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5665. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5666. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5667. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5668. return this;
  5669. };
  5670. /**
  5671. * Check equality between this matrix and a second one
  5672. * @param value defines the second matrix to compare
  5673. * @returns true is the current matrix and the given one values are strictly equal
  5674. */
  5675. Matrix.prototype.equals = function (value) {
  5676. return value &&
  5677. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5678. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5679. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5680. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5681. };
  5682. /**
  5683. * Clone the current matrix
  5684. * @returns a new matrix from the current matrix
  5685. */
  5686. Matrix.prototype.clone = function () {
  5687. 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]);
  5688. };
  5689. /**
  5690. * Returns the name of the current matrix class
  5691. * @returns the string "Matrix"
  5692. */
  5693. Matrix.prototype.getClassName = function () {
  5694. return "Matrix";
  5695. };
  5696. /**
  5697. * Gets the hash code of the current matrix
  5698. * @returns the hash code
  5699. */
  5700. Matrix.prototype.getHashCode = function () {
  5701. var hash = this.m[0] || 0;
  5702. for (var i = 1; i < 16; i++) {
  5703. hash = (hash * 397) ^ (this.m[i] || 0);
  5704. }
  5705. return hash;
  5706. };
  5707. /**
  5708. * Decomposes the current Matrix into a translation, rotation and scaling components
  5709. * @param scale defines the scale vector3 given as a reference to update
  5710. * @param rotation defines the rotation quaternion given as a reference to update
  5711. * @param translation defines the translation vector3 given as a reference to update
  5712. * @returns true if operation was successful
  5713. */
  5714. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5715. if (translation) {
  5716. translation.x = this.m[12];
  5717. translation.y = this.m[13];
  5718. translation.z = this.m[14];
  5719. }
  5720. scale = scale || MathTmp.Vector3[0];
  5721. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5722. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5723. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5724. if (this.determinant() <= 0) {
  5725. scale.y *= -1;
  5726. }
  5727. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5728. if (rotation) {
  5729. rotation.x = 0;
  5730. rotation.y = 0;
  5731. rotation.z = 0;
  5732. rotation.w = 1;
  5733. }
  5734. return false;
  5735. }
  5736. if (rotation) {
  5737. 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]);
  5738. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5739. }
  5740. return true;
  5741. };
  5742. /**
  5743. * Gets specific row of the matrix
  5744. * @param index defines the number of the row to get
  5745. * @returns the index-th row of the current matrix as a new Vector4
  5746. */
  5747. Matrix.prototype.getRow = function (index) {
  5748. if (index < 0 || index > 3) {
  5749. return null;
  5750. }
  5751. var i = index * 4;
  5752. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5753. };
  5754. /**
  5755. * Sets the index-th row of the current matrix to the vector4 values
  5756. * @param index defines the number of the row to set
  5757. * @param row defines the target vector4
  5758. * @returns the updated current matrix
  5759. */
  5760. Matrix.prototype.setRow = function (index, row) {
  5761. if (index < 0 || index > 3) {
  5762. return this;
  5763. }
  5764. var i = index * 4;
  5765. this.m[i + 0] = row.x;
  5766. this.m[i + 1] = row.y;
  5767. this.m[i + 2] = row.z;
  5768. this.m[i + 3] = row.w;
  5769. this._markAsUpdated();
  5770. return this;
  5771. };
  5772. /**
  5773. * Compute the transpose of the matrix
  5774. * @returns the new transposed matrix
  5775. */
  5776. Matrix.prototype.transpose = function () {
  5777. return Matrix.Transpose(this);
  5778. };
  5779. /**
  5780. * Compute the transpose of the matrix and store it in a given matrix
  5781. * @param result defines the target matrix
  5782. * @returns the current matrix
  5783. */
  5784. Matrix.prototype.transposeToRef = function (result) {
  5785. Matrix.TransposeToRef(this, result);
  5786. return this;
  5787. };
  5788. /**
  5789. * Sets the index-th row of the current matrix with the given 4 x float values
  5790. * @param index defines the row index
  5791. * @param x defines the x component to set
  5792. * @param y defines the y component to set
  5793. * @param z defines the z component to set
  5794. * @param w defines the w component to set
  5795. * @returns the updated current matrix
  5796. */
  5797. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5798. if (index < 0 || index > 3) {
  5799. return this;
  5800. }
  5801. var i = index * 4;
  5802. this.m[i + 0] = x;
  5803. this.m[i + 1] = y;
  5804. this.m[i + 2] = z;
  5805. this.m[i + 3] = w;
  5806. this._markAsUpdated();
  5807. return this;
  5808. };
  5809. /**
  5810. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5811. * @param scale defines the scale factor
  5812. * @returns a new matrix
  5813. */
  5814. Matrix.prototype.scale = function (scale) {
  5815. var result = new Matrix();
  5816. this.scaleToRef(scale, result);
  5817. return result;
  5818. };
  5819. /**
  5820. * Scale the current matrix values by a factor to a given result matrix
  5821. * @param scale defines the scale factor
  5822. * @param result defines the matrix to store the result
  5823. * @returns the current matrix
  5824. */
  5825. Matrix.prototype.scaleToRef = function (scale, result) {
  5826. for (var index = 0; index < 16; index++) {
  5827. result.m[index] = this.m[index] * scale;
  5828. }
  5829. result._markAsUpdated();
  5830. return this;
  5831. };
  5832. /**
  5833. * Scale the current matrix values by a factor and add the result to a given matrix
  5834. * @param scale defines the scale factor
  5835. * @param result defines the Matrix to store the result
  5836. * @returns the current matrix
  5837. */
  5838. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5839. for (var index = 0; index < 16; index++) {
  5840. result.m[index] += this.m[index] * scale;
  5841. }
  5842. result._markAsUpdated();
  5843. return this;
  5844. };
  5845. /**
  5846. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5847. * @param ref matrix to store the result
  5848. */
  5849. Matrix.prototype.toNormalMatrix = function (ref) {
  5850. this.invertToRef(ref);
  5851. ref.transpose();
  5852. var m = ref.m;
  5853. 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);
  5854. };
  5855. /**
  5856. * Gets only rotation part of the current matrix
  5857. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5858. */
  5859. Matrix.prototype.getRotationMatrix = function () {
  5860. var result = Matrix.Identity();
  5861. this.getRotationMatrixToRef(result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5866. * @param result defines the target matrix to store data to
  5867. * @returns the current matrix
  5868. */
  5869. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5870. var m = this.m;
  5871. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5872. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5873. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5874. if (this.determinant() <= 0) {
  5875. sy *= -1;
  5876. }
  5877. if (sx === 0 || sy === 0 || sz === 0) {
  5878. Matrix.IdentityToRef(result);
  5879. }
  5880. else {
  5881. 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);
  5882. }
  5883. return this;
  5884. };
  5885. // Statics
  5886. /**
  5887. * Creates a matrix from an array
  5888. * @param array defines the source array
  5889. * @param offset defines an offset in the source array
  5890. * @returns a new Matrix set from the starting index of the given array
  5891. */
  5892. Matrix.FromArray = function (array, offset) {
  5893. var result = new Matrix();
  5894. if (!offset) {
  5895. offset = 0;
  5896. }
  5897. Matrix.FromArrayToRef(array, offset, result);
  5898. return result;
  5899. };
  5900. /**
  5901. * Copy the content of an array into a given matrix
  5902. * @param array defines the source array
  5903. * @param offset defines an offset in the source array
  5904. * @param result defines the target matrix
  5905. */
  5906. Matrix.FromArrayToRef = function (array, offset, result) {
  5907. for (var index = 0; index < 16; index++) {
  5908. result.m[index] = array[index + offset];
  5909. }
  5910. result._markAsUpdated();
  5911. };
  5912. /**
  5913. * Stores an array into a matrix after having multiplied each component by a given factor
  5914. * @param array defines the source array
  5915. * @param offset defines the offset in the source array
  5916. * @param scale defines the scaling factor
  5917. * @param result defines the target matrix
  5918. */
  5919. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5920. for (var index = 0; index < 16; index++) {
  5921. result.m[index] = array[index + offset] * scale;
  5922. }
  5923. result._markAsUpdated();
  5924. };
  5925. /**
  5926. * Stores a list of values (16) inside a given matrix
  5927. * @param initialM11 defines 1st value of 1st row
  5928. * @param initialM12 defines 2nd value of 1st row
  5929. * @param initialM13 defines 3rd value of 1st row
  5930. * @param initialM14 defines 4th value of 1st row
  5931. * @param initialM21 defines 1st value of 2nd row
  5932. * @param initialM22 defines 2nd value of 2nd row
  5933. * @param initialM23 defines 3rd value of 2nd row
  5934. * @param initialM24 defines 4th value of 2nd row
  5935. * @param initialM31 defines 1st value of 3rd row
  5936. * @param initialM32 defines 2nd value of 3rd row
  5937. * @param initialM33 defines 3rd value of 3rd row
  5938. * @param initialM34 defines 4th value of 3rd row
  5939. * @param initialM41 defines 1st value of 4th row
  5940. * @param initialM42 defines 2nd value of 4th row
  5941. * @param initialM43 defines 3rd value of 4th row
  5942. * @param initialM44 defines 4th value of 4th row
  5943. * @param result defines the target matrix
  5944. */
  5945. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5946. result.m[0] = initialM11;
  5947. result.m[1] = initialM12;
  5948. result.m[2] = initialM13;
  5949. result.m[3] = initialM14;
  5950. result.m[4] = initialM21;
  5951. result.m[5] = initialM22;
  5952. result.m[6] = initialM23;
  5953. result.m[7] = initialM24;
  5954. result.m[8] = initialM31;
  5955. result.m[9] = initialM32;
  5956. result.m[10] = initialM33;
  5957. result.m[11] = initialM34;
  5958. result.m[12] = initialM41;
  5959. result.m[13] = initialM42;
  5960. result.m[14] = initialM43;
  5961. result.m[15] = initialM44;
  5962. result._markAsUpdated();
  5963. };
  5964. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5965. /**
  5966. * Gets an identity matrix that must not be updated
  5967. */
  5968. get: function () {
  5969. return Matrix._identityReadOnly;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. });
  5974. /**
  5975. * Creates new matrix from a list of values (16)
  5976. * @param initialM11 defines 1st value of 1st row
  5977. * @param initialM12 defines 2nd value of 1st row
  5978. * @param initialM13 defines 3rd value of 1st row
  5979. * @param initialM14 defines 4th value of 1st row
  5980. * @param initialM21 defines 1st value of 2nd row
  5981. * @param initialM22 defines 2nd value of 2nd row
  5982. * @param initialM23 defines 3rd value of 2nd row
  5983. * @param initialM24 defines 4th value of 2nd row
  5984. * @param initialM31 defines 1st value of 3rd row
  5985. * @param initialM32 defines 2nd value of 3rd row
  5986. * @param initialM33 defines 3rd value of 3rd row
  5987. * @param initialM34 defines 4th value of 3rd row
  5988. * @param initialM41 defines 1st value of 4th row
  5989. * @param initialM42 defines 2nd value of 4th row
  5990. * @param initialM43 defines 3rd value of 4th row
  5991. * @param initialM44 defines 4th value of 4th row
  5992. * @returns the new matrix
  5993. */
  5994. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5995. var result = new Matrix();
  5996. result.m[0] = initialM11;
  5997. result.m[1] = initialM12;
  5998. result.m[2] = initialM13;
  5999. result.m[3] = initialM14;
  6000. result.m[4] = initialM21;
  6001. result.m[5] = initialM22;
  6002. result.m[6] = initialM23;
  6003. result.m[7] = initialM24;
  6004. result.m[8] = initialM31;
  6005. result.m[9] = initialM32;
  6006. result.m[10] = initialM33;
  6007. result.m[11] = initialM34;
  6008. result.m[12] = initialM41;
  6009. result.m[13] = initialM42;
  6010. result.m[14] = initialM43;
  6011. result.m[15] = initialM44;
  6012. return result;
  6013. };
  6014. /**
  6015. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6016. * @param scale defines the scale vector3
  6017. * @param rotation defines the rotation quaternion
  6018. * @param translation defines the translation vector3
  6019. * @returns a new matrix
  6020. */
  6021. Matrix.Compose = function (scale, rotation, translation) {
  6022. var result = Matrix.Identity();
  6023. Matrix.ComposeToRef(scale, rotation, translation, result);
  6024. return result;
  6025. };
  6026. /**
  6027. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6028. * @param scale defines the scale vector3
  6029. * @param rotation defines the rotation quaternion
  6030. * @param translation defines the translation vector3
  6031. * @param result defines the target matrix
  6032. */
  6033. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6034. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6035. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6036. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6037. result.setTranslation(translation);
  6038. };
  6039. /**
  6040. * Creates a new identity matrix
  6041. * @returns a new identity matrix
  6042. */
  6043. Matrix.Identity = function () {
  6044. 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);
  6045. };
  6046. /**
  6047. * Creates a new identity matrix and stores the result in a given matrix
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.IdentityToRef = function (result) {
  6051. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  6052. };
  6053. /**
  6054. * Creates a new zero matrix
  6055. * @returns a new zero matrix
  6056. */
  6057. Matrix.Zero = function () {
  6058. 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);
  6059. };
  6060. /**
  6061. * Creates a new rotation matrix for "angle" radians around the X axis
  6062. * @param angle defines the angle (in radians) to use
  6063. * @return the new matrix
  6064. */
  6065. Matrix.RotationX = function (angle) {
  6066. var result = new Matrix();
  6067. Matrix.RotationXToRef(angle, result);
  6068. return result;
  6069. };
  6070. /**
  6071. * Creates a new matrix as the invert of a given matrix
  6072. * @param source defines the source matrix
  6073. * @returns the new matrix
  6074. */
  6075. Matrix.Invert = function (source) {
  6076. var result = new Matrix();
  6077. source.invertToRef(result);
  6078. return result;
  6079. };
  6080. /**
  6081. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6082. * @param angle defines the angle (in radians) to use
  6083. * @param result defines the target matrix
  6084. */
  6085. Matrix.RotationXToRef = function (angle, result) {
  6086. var s = Math.sin(angle);
  6087. var c = Math.cos(angle);
  6088. result.m[0] = 1.0;
  6089. result.m[15] = 1.0;
  6090. result.m[5] = c;
  6091. result.m[10] = c;
  6092. result.m[9] = -s;
  6093. result.m[6] = s;
  6094. result.m[1] = 0.0;
  6095. result.m[2] = 0.0;
  6096. result.m[3] = 0.0;
  6097. result.m[4] = 0.0;
  6098. result.m[7] = 0.0;
  6099. result.m[8] = 0.0;
  6100. result.m[11] = 0.0;
  6101. result.m[12] = 0.0;
  6102. result.m[13] = 0.0;
  6103. result.m[14] = 0.0;
  6104. result._markAsUpdated();
  6105. };
  6106. /**
  6107. * Creates a new rotation matrix for "angle" radians around the Y axis
  6108. * @param angle defines the angle (in radians) to use
  6109. * @return the new matrix
  6110. */
  6111. Matrix.RotationY = function (angle) {
  6112. var result = new Matrix();
  6113. Matrix.RotationYToRef(angle, result);
  6114. return result;
  6115. };
  6116. /**
  6117. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6118. * @param angle defines the angle (in radians) to use
  6119. * @param result defines the target matrix
  6120. */
  6121. Matrix.RotationYToRef = function (angle, result) {
  6122. var s = Math.sin(angle);
  6123. var c = Math.cos(angle);
  6124. result.m[5] = 1.0;
  6125. result.m[15] = 1.0;
  6126. result.m[0] = c;
  6127. result.m[2] = -s;
  6128. result.m[8] = s;
  6129. result.m[10] = c;
  6130. result.m[1] = 0.0;
  6131. result.m[3] = 0.0;
  6132. result.m[4] = 0.0;
  6133. result.m[6] = 0.0;
  6134. result.m[7] = 0.0;
  6135. result.m[9] = 0.0;
  6136. result.m[11] = 0.0;
  6137. result.m[12] = 0.0;
  6138. result.m[13] = 0.0;
  6139. result.m[14] = 0.0;
  6140. result._markAsUpdated();
  6141. };
  6142. /**
  6143. * Creates a new rotation matrix for "angle" radians around the Z axis
  6144. * @param angle defines the angle (in radians) to use
  6145. * @return the new matrix
  6146. */
  6147. Matrix.RotationZ = function (angle) {
  6148. var result = new Matrix();
  6149. Matrix.RotationZToRef(angle, result);
  6150. return result;
  6151. };
  6152. /**
  6153. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6154. * @param angle defines the angle (in radians) to use
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.RotationZToRef = function (angle, result) {
  6158. var s = Math.sin(angle);
  6159. var c = Math.cos(angle);
  6160. result.m[10] = 1.0;
  6161. result.m[15] = 1.0;
  6162. result.m[0] = c;
  6163. result.m[1] = s;
  6164. result.m[4] = -s;
  6165. result.m[5] = c;
  6166. result.m[2] = 0.0;
  6167. result.m[3] = 0.0;
  6168. result.m[6] = 0.0;
  6169. result.m[7] = 0.0;
  6170. result.m[8] = 0.0;
  6171. result.m[9] = 0.0;
  6172. result.m[11] = 0.0;
  6173. result.m[12] = 0.0;
  6174. result.m[13] = 0.0;
  6175. result.m[14] = 0.0;
  6176. result._markAsUpdated();
  6177. };
  6178. /**
  6179. * Creates a new rotation matrix for "angle" radians around the given axis
  6180. * @param axis defines the axis to use
  6181. * @param angle defines the angle (in radians) to use
  6182. * @return the new matrix
  6183. */
  6184. Matrix.RotationAxis = function (axis, angle) {
  6185. var result = Matrix.Zero();
  6186. Matrix.RotationAxisToRef(axis, angle, result);
  6187. return result;
  6188. };
  6189. /**
  6190. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6191. * @param axis defines the axis to use
  6192. * @param angle defines the angle (in radians) to use
  6193. * @param result defines the target matrix
  6194. */
  6195. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6196. var s = Math.sin(-angle);
  6197. var c = Math.cos(-angle);
  6198. var c1 = 1 - c;
  6199. axis.normalize();
  6200. result.m[0] = (axis.x * axis.x) * c1 + c;
  6201. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6202. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6203. result.m[3] = 0.0;
  6204. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6205. result.m[5] = (axis.y * axis.y) * c1 + c;
  6206. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6207. result.m[7] = 0.0;
  6208. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6209. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6210. result.m[10] = (axis.z * axis.z) * c1 + c;
  6211. result.m[11] = 0.0;
  6212. result.m[15] = 1.0;
  6213. result._markAsUpdated();
  6214. };
  6215. /**
  6216. * Creates a rotation matrix
  6217. * @param yaw defines the yaw angle in radians (Y axis)
  6218. * @param pitch defines the pitch angle in radians (X axis)
  6219. * @param roll defines the roll angle in radians (X axis)
  6220. * @returns the new rotation matrix
  6221. */
  6222. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6223. var result = new Matrix();
  6224. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6225. return result;
  6226. };
  6227. /**
  6228. * Creates a rotation matrix and stores it in a given matrix
  6229. * @param yaw defines the yaw angle in radians (Y axis)
  6230. * @param pitch defines the pitch angle in radians (X axis)
  6231. * @param roll defines the roll angle in radians (X axis)
  6232. * @param result defines the target matrix
  6233. */
  6234. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6235. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6236. this._tempQuaternion.toRotationMatrix(result);
  6237. };
  6238. /**
  6239. * Creates a scaling matrix
  6240. * @param x defines the scale factor on X axis
  6241. * @param y defines the scale factor on Y axis
  6242. * @param z defines the scale factor on Z axis
  6243. * @returns the new matrix
  6244. */
  6245. Matrix.Scaling = function (x, y, z) {
  6246. var result = Matrix.Zero();
  6247. Matrix.ScalingToRef(x, y, z, result);
  6248. return result;
  6249. };
  6250. /**
  6251. * Creates a scaling matrix and stores it in a given matrix
  6252. * @param x defines the scale factor on X axis
  6253. * @param y defines the scale factor on Y axis
  6254. * @param z defines the scale factor on Z axis
  6255. * @param result defines the target matrix
  6256. */
  6257. Matrix.ScalingToRef = function (x, y, z, result) {
  6258. result.m[0] = x;
  6259. result.m[1] = 0.0;
  6260. result.m[2] = 0.0;
  6261. result.m[3] = 0.0;
  6262. result.m[4] = 0.0;
  6263. result.m[5] = y;
  6264. result.m[6] = 0.0;
  6265. result.m[7] = 0.0;
  6266. result.m[8] = 0.0;
  6267. result.m[9] = 0.0;
  6268. result.m[10] = z;
  6269. result.m[11] = 0.0;
  6270. result.m[12] = 0.0;
  6271. result.m[13] = 0.0;
  6272. result.m[14] = 0.0;
  6273. result.m[15] = 1.0;
  6274. result._markAsUpdated();
  6275. };
  6276. /**
  6277. * Creates a translation matrix
  6278. * @param x defines the translation on X axis
  6279. * @param y defines the translation on Y axis
  6280. * @param z defines the translationon Z axis
  6281. * @returns the new matrix
  6282. */
  6283. Matrix.Translation = function (x, y, z) {
  6284. var result = Matrix.Identity();
  6285. Matrix.TranslationToRef(x, y, z, result);
  6286. return result;
  6287. };
  6288. /**
  6289. * Creates a translation matrix and stores it in a given matrix
  6290. * @param x defines the translation on X axis
  6291. * @param y defines the translation on Y axis
  6292. * @param z defines the translationon Z axis
  6293. * @param result defines the target matrix
  6294. */
  6295. Matrix.TranslationToRef = function (x, y, z, result) {
  6296. 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);
  6297. };
  6298. /**
  6299. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6300. * @param startValue defines the start value
  6301. * @param endValue defines the end value
  6302. * @param gradient defines the gradient factor
  6303. * @returns the new matrix
  6304. */
  6305. Matrix.Lerp = function (startValue, endValue, gradient) {
  6306. var result = Matrix.Zero();
  6307. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6308. return result;
  6309. };
  6310. /**
  6311. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6312. * @param startValue defines the start value
  6313. * @param endValue defines the end value
  6314. * @param gradient defines the gradient factor
  6315. * @param result defines the Matrix object where to store data
  6316. */
  6317. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6318. for (var index = 0; index < 16; index++) {
  6319. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6320. }
  6321. result._markAsUpdated();
  6322. };
  6323. /**
  6324. * Builds a new matrix whose values are computed by:
  6325. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6326. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6327. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6328. * @param startValue defines the first matrix
  6329. * @param endValue defines the second matrix
  6330. * @param gradient defines the gradient between the two matrices
  6331. * @returns the new matrix
  6332. */
  6333. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6334. var result = Matrix.Zero();
  6335. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6336. return result;
  6337. };
  6338. /**
  6339. * Update a matrix to values which are computed by:
  6340. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6341. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6342. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6343. * @param startValue defines the first matrix
  6344. * @param endValue defines the second matrix
  6345. * @param gradient defines the gradient between the two matrices
  6346. * @param result defines the target matrix
  6347. */
  6348. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6349. var startScale = MathTmp.Vector3[0];
  6350. var startRotation = MathTmp.Quaternion[0];
  6351. var startTranslation = MathTmp.Vector3[1];
  6352. startValue.decompose(startScale, startRotation, startTranslation);
  6353. var endScale = MathTmp.Vector3[2];
  6354. var endRotation = MathTmp.Quaternion[1];
  6355. var endTranslation = MathTmp.Vector3[3];
  6356. endValue.decompose(endScale, endRotation, endTranslation);
  6357. var resultScale = MathTmp.Vector3[4];
  6358. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6359. var resultRotation = MathTmp.Quaternion[2];
  6360. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6361. var resultTranslation = MathTmp.Vector3[5];
  6362. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6363. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6364. };
  6365. /**
  6366. * 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"
  6367. * This function works in left handed mode
  6368. * @param eye defines the final position of the entity
  6369. * @param target defines where the entity should look at
  6370. * @param up defines the up vector for the entity
  6371. * @returns the new matrix
  6372. */
  6373. Matrix.LookAtLH = function (eye, target, up) {
  6374. var result = Matrix.Zero();
  6375. Matrix.LookAtLHToRef(eye, target, up, result);
  6376. return result;
  6377. };
  6378. /**
  6379. * 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".
  6380. * This function works in left handed mode
  6381. * @param eye defines the final position of the entity
  6382. * @param target defines where the entity should look at
  6383. * @param up defines the up vector for the entity
  6384. * @param result defines the target matrix
  6385. */
  6386. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6387. // Z axis
  6388. target.subtractToRef(eye, this._zAxis);
  6389. this._zAxis.normalize();
  6390. // X axis
  6391. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6392. if (this._xAxis.lengthSquared() === 0) {
  6393. this._xAxis.x = 1.0;
  6394. }
  6395. else {
  6396. this._xAxis.normalize();
  6397. }
  6398. // Y axis
  6399. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6400. this._yAxis.normalize();
  6401. // Eye angles
  6402. var ex = -Vector3.Dot(this._xAxis, eye);
  6403. var ey = -Vector3.Dot(this._yAxis, eye);
  6404. var ez = -Vector3.Dot(this._zAxis, eye);
  6405. 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);
  6406. };
  6407. /**
  6408. * 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"
  6409. * This function works in right handed mode
  6410. * @param eye defines the final position of the entity
  6411. * @param target defines where the entity should look at
  6412. * @param up defines the up vector for the entity
  6413. * @returns the new matrix
  6414. */
  6415. Matrix.LookAtRH = function (eye, target, up) {
  6416. var result = Matrix.Zero();
  6417. Matrix.LookAtRHToRef(eye, target, up, result);
  6418. return result;
  6419. };
  6420. /**
  6421. * 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".
  6422. * This function works in right handed mode
  6423. * @param eye defines the final position of the entity
  6424. * @param target defines where the entity should look at
  6425. * @param up defines the up vector for the entity
  6426. * @param result defines the target matrix
  6427. */
  6428. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6429. // Z axis
  6430. eye.subtractToRef(target, this._zAxis);
  6431. this._zAxis.normalize();
  6432. // X axis
  6433. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6434. if (this._xAxis.lengthSquared() === 0) {
  6435. this._xAxis.x = 1.0;
  6436. }
  6437. else {
  6438. this._xAxis.normalize();
  6439. }
  6440. // Y axis
  6441. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6442. this._yAxis.normalize();
  6443. // Eye angles
  6444. var ex = -Vector3.Dot(this._xAxis, eye);
  6445. var ey = -Vector3.Dot(this._yAxis, eye);
  6446. var ez = -Vector3.Dot(this._zAxis, eye);
  6447. 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);
  6448. };
  6449. /**
  6450. * Create a left-handed orthographic projection matrix
  6451. * @param width defines the viewport width
  6452. * @param height defines the viewport height
  6453. * @param znear defines the near clip plane
  6454. * @param zfar defines the far clip plane
  6455. * @returns a new matrix as a left-handed orthographic projection matrix
  6456. */
  6457. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6458. var matrix = Matrix.Zero();
  6459. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6460. return matrix;
  6461. };
  6462. /**
  6463. * Store a left-handed orthographic projection to a given matrix
  6464. * @param width defines the viewport width
  6465. * @param height defines the viewport height
  6466. * @param znear defines the near clip plane
  6467. * @param zfar defines the far clip plane
  6468. * @param result defines the target matrix
  6469. */
  6470. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6471. var n = znear;
  6472. var f = zfar;
  6473. var a = 2.0 / width;
  6474. var b = 2.0 / height;
  6475. var c = 2.0 / (f - n);
  6476. var d = -(f + n) / (f - n);
  6477. 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);
  6478. };
  6479. /**
  6480. * Create a left-handed orthographic projection matrix
  6481. * @param left defines the viewport left coordinate
  6482. * @param right defines the viewport right coordinate
  6483. * @param bottom defines the viewport bottom coordinate
  6484. * @param top defines the viewport top coordinate
  6485. * @param znear defines the near clip plane
  6486. * @param zfar defines the far clip plane
  6487. * @returns a new matrix as a left-handed orthographic projection matrix
  6488. */
  6489. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6490. var matrix = Matrix.Zero();
  6491. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6492. return matrix;
  6493. };
  6494. /**
  6495. * Stores a left-handed orthographic projection into a given matrix
  6496. * @param left defines the viewport left coordinate
  6497. * @param right defines the viewport right coordinate
  6498. * @param bottom defines the viewport bottom coordinate
  6499. * @param top defines the viewport top coordinate
  6500. * @param znear defines the near clip plane
  6501. * @param zfar defines the far clip plane
  6502. * @param result defines the target matrix
  6503. */
  6504. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6505. var n = znear;
  6506. var f = zfar;
  6507. var a = 2.0 / (right - left);
  6508. var b = 2.0 / (top - bottom);
  6509. var c = 2.0 / (f - n);
  6510. var d = -(f + n) / (f - n);
  6511. var i0 = (left + right) / (left - right);
  6512. var i1 = (top + bottom) / (bottom - top);
  6513. 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);
  6514. };
  6515. /**
  6516. * Creates a right-handed orthographic projection matrix
  6517. * @param left defines the viewport left coordinate
  6518. * @param right defines the viewport right coordinate
  6519. * @param bottom defines the viewport bottom coordinate
  6520. * @param top defines the viewport top coordinate
  6521. * @param znear defines the near clip plane
  6522. * @param zfar defines the far clip plane
  6523. * @returns a new matrix as a right-handed orthographic projection matrix
  6524. */
  6525. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6526. var matrix = Matrix.Zero();
  6527. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6528. return matrix;
  6529. };
  6530. /**
  6531. * Stores a right-handed orthographic projection into a given matrix
  6532. * @param left defines the viewport left coordinate
  6533. * @param right defines the viewport right coordinate
  6534. * @param bottom defines the viewport bottom coordinate
  6535. * @param top defines the viewport top coordinate
  6536. * @param znear defines the near clip plane
  6537. * @param zfar defines the far clip plane
  6538. * @param result defines the target matrix
  6539. */
  6540. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6541. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6542. result.m[10] *= -1.0;
  6543. };
  6544. /**
  6545. * Creates a left-handed perspective projection matrix
  6546. * @param width defines the viewport width
  6547. * @param height defines the viewport height
  6548. * @param znear defines the near clip plane
  6549. * @param zfar defines the far clip plane
  6550. * @returns a new matrix as a left-handed perspective projection matrix
  6551. */
  6552. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6553. var matrix = Matrix.Zero();
  6554. var n = znear;
  6555. var f = zfar;
  6556. var a = 2.0 * n / width;
  6557. var b = 2.0 * n / height;
  6558. var c = (f + n) / (f - n);
  6559. var d = -2.0 * f * n / (f - n);
  6560. 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);
  6561. return matrix;
  6562. };
  6563. /**
  6564. * Creates a left-handed perspective projection matrix
  6565. * @param fov defines the horizontal field of view
  6566. * @param aspect defines the aspect ratio
  6567. * @param znear defines the near clip plane
  6568. * @param zfar defines the far clip plane
  6569. * @returns a new matrix as a left-handed perspective projection matrix
  6570. */
  6571. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6572. var matrix = Matrix.Zero();
  6573. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6574. return matrix;
  6575. };
  6576. /**
  6577. * Stores a left-handed perspective projection into a given matrix
  6578. * @param fov defines the horizontal field of view
  6579. * @param aspect defines the aspect ratio
  6580. * @param znear defines the near clip plane
  6581. * @param zfar defines the far clip plane
  6582. * @param result defines the target matrix
  6583. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6584. */
  6585. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6586. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6587. var n = znear;
  6588. var f = zfar;
  6589. var t = 1.0 / (Math.tan(fov * 0.5));
  6590. var a = isVerticalFovFixed ? (t / aspect) : t;
  6591. var b = isVerticalFovFixed ? t : (t * aspect);
  6592. var c = (f + n) / (f - n);
  6593. var d = -2.0 * f * n / (f - n);
  6594. 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);
  6595. };
  6596. /**
  6597. * Creates a right-handed perspective projection matrix
  6598. * @param fov defines the horizontal field of view
  6599. * @param aspect defines the aspect ratio
  6600. * @param znear defines the near clip plane
  6601. * @param zfar defines the far clip plane
  6602. * @returns a new matrix as a right-handed perspective projection matrix
  6603. */
  6604. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6605. var matrix = Matrix.Zero();
  6606. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6607. return matrix;
  6608. };
  6609. /**
  6610. * Stores a right-handed perspective projection into a given matrix
  6611. * @param fov defines the horizontal field of view
  6612. * @param aspect defines the aspect ratio
  6613. * @param znear defines the near clip plane
  6614. * @param zfar defines the far clip plane
  6615. * @param result defines the target matrix
  6616. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6617. */
  6618. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6619. //alternatively this could be expressed as:
  6620. // m = PerspectiveFovLHToRef
  6621. // m[10] *= -1.0;
  6622. // m[11] *= -1.0;
  6623. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6624. var n = znear;
  6625. var f = zfar;
  6626. var t = 1.0 / (Math.tan(fov * 0.5));
  6627. var a = isVerticalFovFixed ? (t / aspect) : t;
  6628. var b = isVerticalFovFixed ? t : (t * aspect);
  6629. var c = -(f + n) / (f - n);
  6630. var d = -2 * f * n / (f - n);
  6631. 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);
  6632. };
  6633. /**
  6634. * Stores a perspective projection for WebVR info a given matrix
  6635. * @param fov defines the field of view
  6636. * @param znear defines the near clip plane
  6637. * @param zfar defines the far clip plane
  6638. * @param result defines the target matrix
  6639. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6640. */
  6641. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6642. if (rightHanded === void 0) { rightHanded = false; }
  6643. var rightHandedFactor = rightHanded ? -1 : 1;
  6644. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6645. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6646. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6647. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6648. var xScale = 2.0 / (leftTan + rightTan);
  6649. var yScale = 2.0 / (upTan + downTan);
  6650. result.m[0] = xScale;
  6651. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6652. result.m[5] = yScale;
  6653. result.m[6] = result.m[7] = 0.0;
  6654. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6655. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6656. result.m[10] = -zfar / (znear - zfar);
  6657. result.m[11] = 1.0 * rightHandedFactor;
  6658. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6659. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6660. result._markAsUpdated();
  6661. };
  6662. /**
  6663. * Computes a complete transformation matrix
  6664. * @param viewport defines the viewport to use
  6665. * @param world defines the world matrix
  6666. * @param view defines the view matrix
  6667. * @param projection defines the projection matrix
  6668. * @param zmin defines the near clip plane
  6669. * @param zmax defines the far clip plane
  6670. * @returns the transformation matrix
  6671. */
  6672. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6673. var cw = viewport.width;
  6674. var ch = viewport.height;
  6675. var cx = viewport.x;
  6676. var cy = viewport.y;
  6677. 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);
  6678. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6679. };
  6680. /**
  6681. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6682. * @param matrix defines the matrix to use
  6683. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6684. */
  6685. Matrix.GetAsMatrix2x2 = function (matrix) {
  6686. return new Float32Array([
  6687. matrix.m[0], matrix.m[1],
  6688. matrix.m[4], matrix.m[5]
  6689. ]);
  6690. };
  6691. /**
  6692. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6693. * @param matrix defines the matrix to use
  6694. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6695. */
  6696. Matrix.GetAsMatrix3x3 = function (matrix) {
  6697. return new Float32Array([
  6698. matrix.m[0], matrix.m[1], matrix.m[2],
  6699. matrix.m[4], matrix.m[5], matrix.m[6],
  6700. matrix.m[8], matrix.m[9], matrix.m[10]
  6701. ]);
  6702. };
  6703. /**
  6704. * Compute the transpose of a given matrix
  6705. * @param matrix defines the matrix to transpose
  6706. * @returns the new matrix
  6707. */
  6708. Matrix.Transpose = function (matrix) {
  6709. var result = new Matrix();
  6710. Matrix.TransposeToRef(matrix, result);
  6711. return result;
  6712. };
  6713. /**
  6714. * Compute the transpose of a matrix and store it in a target matrix
  6715. * @param matrix defines the matrix to transpose
  6716. * @param result defines the target matrix
  6717. */
  6718. Matrix.TransposeToRef = function (matrix, result) {
  6719. result.m[0] = matrix.m[0];
  6720. result.m[1] = matrix.m[4];
  6721. result.m[2] = matrix.m[8];
  6722. result.m[3] = matrix.m[12];
  6723. result.m[4] = matrix.m[1];
  6724. result.m[5] = matrix.m[5];
  6725. result.m[6] = matrix.m[9];
  6726. result.m[7] = matrix.m[13];
  6727. result.m[8] = matrix.m[2];
  6728. result.m[9] = matrix.m[6];
  6729. result.m[10] = matrix.m[10];
  6730. result.m[11] = matrix.m[14];
  6731. result.m[12] = matrix.m[3];
  6732. result.m[13] = matrix.m[7];
  6733. result.m[14] = matrix.m[11];
  6734. result.m[15] = matrix.m[15];
  6735. };
  6736. /**
  6737. * Computes a reflection matrix from a plane
  6738. * @param plane defines the reflection plane
  6739. * @returns a new matrix
  6740. */
  6741. Matrix.Reflection = function (plane) {
  6742. var matrix = new Matrix();
  6743. Matrix.ReflectionToRef(plane, matrix);
  6744. return matrix;
  6745. };
  6746. /**
  6747. * Computes a reflection matrix from a plane
  6748. * @param plane defines the reflection plane
  6749. * @param result defines the target matrix
  6750. */
  6751. Matrix.ReflectionToRef = function (plane, result) {
  6752. plane.normalize();
  6753. var x = plane.normal.x;
  6754. var y = plane.normal.y;
  6755. var z = plane.normal.z;
  6756. var temp = -2 * x;
  6757. var temp2 = -2 * y;
  6758. var temp3 = -2 * z;
  6759. result.m[0] = (temp * x) + 1;
  6760. result.m[1] = temp2 * x;
  6761. result.m[2] = temp3 * x;
  6762. result.m[3] = 0.0;
  6763. result.m[4] = temp * y;
  6764. result.m[5] = (temp2 * y) + 1;
  6765. result.m[6] = temp3 * y;
  6766. result.m[7] = 0.0;
  6767. result.m[8] = temp * z;
  6768. result.m[9] = temp2 * z;
  6769. result.m[10] = (temp3 * z) + 1;
  6770. result.m[11] = 0.0;
  6771. result.m[12] = temp * plane.d;
  6772. result.m[13] = temp2 * plane.d;
  6773. result.m[14] = temp3 * plane.d;
  6774. result.m[15] = 1.0;
  6775. result._markAsUpdated();
  6776. };
  6777. /**
  6778. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6779. * @param xaxis defines the value of the 1st axis
  6780. * @param yaxis defines the value of the 2nd axis
  6781. * @param zaxis defines the value of the 3rd axis
  6782. * @param result defines the target matrix
  6783. */
  6784. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6785. result.m[0] = xaxis.x;
  6786. result.m[1] = xaxis.y;
  6787. result.m[2] = xaxis.z;
  6788. result.m[3] = 0.0;
  6789. result.m[4] = yaxis.x;
  6790. result.m[5] = yaxis.y;
  6791. result.m[6] = yaxis.z;
  6792. result.m[7] = 0.0;
  6793. result.m[8] = zaxis.x;
  6794. result.m[9] = zaxis.y;
  6795. result.m[10] = zaxis.z;
  6796. result.m[11] = 0.0;
  6797. result.m[12] = 0.0;
  6798. result.m[13] = 0.0;
  6799. result.m[14] = 0.0;
  6800. result.m[15] = 1.0;
  6801. result._markAsUpdated();
  6802. };
  6803. /**
  6804. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6805. * @param quat defines the quaternion to use
  6806. * @param result defines the target matrix
  6807. */
  6808. Matrix.FromQuaternionToRef = function (quat, result) {
  6809. var xx = quat.x * quat.x;
  6810. var yy = quat.y * quat.y;
  6811. var zz = quat.z * quat.z;
  6812. var xy = quat.x * quat.y;
  6813. var zw = quat.z * quat.w;
  6814. var zx = quat.z * quat.x;
  6815. var yw = quat.y * quat.w;
  6816. var yz = quat.y * quat.z;
  6817. var xw = quat.x * quat.w;
  6818. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6819. result.m[1] = 2.0 * (xy + zw);
  6820. result.m[2] = 2.0 * (zx - yw);
  6821. result.m[3] = 0.0;
  6822. result.m[4] = 2.0 * (xy - zw);
  6823. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6824. result.m[6] = 2.0 * (yz + xw);
  6825. result.m[7] = 0.0;
  6826. result.m[8] = 2.0 * (zx + yw);
  6827. result.m[9] = 2.0 * (yz - xw);
  6828. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6829. result.m[11] = 0.0;
  6830. result.m[12] = 0.0;
  6831. result.m[13] = 0.0;
  6832. result.m[14] = 0.0;
  6833. result.m[15] = 1.0;
  6834. result._markAsUpdated();
  6835. };
  6836. Matrix._tempQuaternion = new Quaternion();
  6837. Matrix._xAxis = Vector3.Zero();
  6838. Matrix._yAxis = Vector3.Zero();
  6839. Matrix._zAxis = Vector3.Zero();
  6840. Matrix._updateFlagSeed = 0;
  6841. Matrix._identityReadOnly = Matrix.Identity();
  6842. return Matrix;
  6843. }());
  6844. BABYLON.Matrix = Matrix;
  6845. /**
  6846. * Represens a plane by the equation ax + by + cz + d = 0
  6847. */
  6848. var Plane = /** @class */ (function () {
  6849. /**
  6850. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6851. * @param a a component of the plane
  6852. * @param b b component of the plane
  6853. * @param c c component of the plane
  6854. * @param d d component of the plane
  6855. */
  6856. function Plane(a, b, c, d) {
  6857. this.normal = new Vector3(a, b, c);
  6858. this.d = d;
  6859. }
  6860. /**
  6861. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6862. */
  6863. Plane.prototype.asArray = function () {
  6864. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6865. };
  6866. // Methods
  6867. /**
  6868. * @returns a new plane copied from the current Plane.
  6869. */
  6870. Plane.prototype.clone = function () {
  6871. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6872. };
  6873. /**
  6874. * @returns the string "Plane".
  6875. */
  6876. Plane.prototype.getClassName = function () {
  6877. return "Plane";
  6878. };
  6879. /**
  6880. * @returns the Plane hash code.
  6881. */
  6882. Plane.prototype.getHashCode = function () {
  6883. var hash = this.normal.getHashCode();
  6884. hash = (hash * 397) ^ (this.d || 0);
  6885. return hash;
  6886. };
  6887. /**
  6888. * Normalize the current Plane in place.
  6889. * @returns the updated Plane.
  6890. */
  6891. Plane.prototype.normalize = function () {
  6892. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6893. var magnitude = 0.0;
  6894. if (norm !== 0) {
  6895. magnitude = 1.0 / norm;
  6896. }
  6897. this.normal.x *= magnitude;
  6898. this.normal.y *= magnitude;
  6899. this.normal.z *= magnitude;
  6900. this.d *= magnitude;
  6901. return this;
  6902. };
  6903. /**
  6904. * Applies a transformation the plane and returns the result
  6905. * @param transformation the transformation matrix to be applied to the plane
  6906. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6907. */
  6908. Plane.prototype.transform = function (transformation) {
  6909. var transposedMatrix = Matrix.Transpose(transformation);
  6910. var x = this.normal.x;
  6911. var y = this.normal.y;
  6912. var z = this.normal.z;
  6913. var d = this.d;
  6914. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6915. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6916. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6917. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6918. return new Plane(normalX, normalY, normalZ, finalD);
  6919. };
  6920. /**
  6921. * Calcualtte the dot product between the point and the plane normal
  6922. * @param point point to calculate the dot product with
  6923. * @returns the dot product (float) of the point coordinates and the plane normal.
  6924. */
  6925. Plane.prototype.dotCoordinate = function (point) {
  6926. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6927. };
  6928. /**
  6929. * Updates the current Plane from the plane defined by the three given points.
  6930. * @param point1 one of the points used to contruct the plane
  6931. * @param point2 one of the points used to contruct the plane
  6932. * @param point3 one of the points used to contruct the plane
  6933. * @returns the updated Plane.
  6934. */
  6935. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6936. var x1 = point2.x - point1.x;
  6937. var y1 = point2.y - point1.y;
  6938. var z1 = point2.z - point1.z;
  6939. var x2 = point3.x - point1.x;
  6940. var y2 = point3.y - point1.y;
  6941. var z2 = point3.z - point1.z;
  6942. var yz = (y1 * z2) - (z1 * y2);
  6943. var xz = (z1 * x2) - (x1 * z2);
  6944. var xy = (x1 * y2) - (y1 * x2);
  6945. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6946. var invPyth;
  6947. if (pyth !== 0) {
  6948. invPyth = 1.0 / pyth;
  6949. }
  6950. else {
  6951. invPyth = 0.0;
  6952. }
  6953. this.normal.x = yz * invPyth;
  6954. this.normal.y = xz * invPyth;
  6955. this.normal.z = xy * invPyth;
  6956. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6957. return this;
  6958. };
  6959. /**
  6960. * Checks if the plane is facing a given direction
  6961. * @param direction the direction to check if the plane is facing
  6962. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  6963. * @returns True is the vector "direction" is the same side than the plane normal.
  6964. */
  6965. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6966. var dot = Vector3.Dot(this.normal, direction);
  6967. return (dot <= epsilon);
  6968. };
  6969. /**
  6970. * Calculates the distance to a point
  6971. * @param point point to calculate distance to
  6972. * @returns the signed distance (float) from the given point to the Plane.
  6973. */
  6974. Plane.prototype.signedDistanceTo = function (point) {
  6975. return Vector3.Dot(point, this.normal) + this.d;
  6976. };
  6977. // Statics
  6978. /**
  6979. * Creates a plane from an array
  6980. * @param array the array to create a plane from
  6981. * @returns a new Plane from the given array.
  6982. */
  6983. Plane.FromArray = function (array) {
  6984. return new Plane(array[0], array[1], array[2], array[3]);
  6985. };
  6986. /**
  6987. * Creates a plane from three points
  6988. * @param point1 point used to create the plane
  6989. * @param point2 point used to create the plane
  6990. * @param point3 point used to create the plane
  6991. * @returns a new Plane defined by the three given points.
  6992. */
  6993. Plane.FromPoints = function (point1, point2, point3) {
  6994. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6995. result.copyFromPoints(point1, point2, point3);
  6996. return result;
  6997. };
  6998. /**
  6999. * Creates a plane from an origin point and a normal
  7000. * @param origin origin of the plane to be constructed
  7001. * @param normal normal of the plane to be constructed
  7002. * @returns a new Plane the normal vector to this plane at the given origin point.
  7003. * Note : the vector "normal" is updated because normalized.
  7004. */
  7005. Plane.FromPositionAndNormal = function (origin, normal) {
  7006. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7007. normal.normalize();
  7008. result.normal = normal;
  7009. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7010. return result;
  7011. };
  7012. /**
  7013. * Calculates the distance from a plane and a point
  7014. * @param origin origin of the plane to be constructed
  7015. * @param normal normal of the plane to be constructed
  7016. * @param point point to calculate distance to
  7017. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7018. */
  7019. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7020. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7021. return Vector3.Dot(point, normal) + d;
  7022. };
  7023. return Plane;
  7024. }());
  7025. BABYLON.Plane = Plane;
  7026. /**
  7027. * Class used to represent a viewport on screen
  7028. */
  7029. var Viewport = /** @class */ (function () {
  7030. /**
  7031. * Creates a Viewport object located at (x, y) and sized (width, height)
  7032. * @param x defines viewport left coordinate
  7033. * @param y defines viewport top coordinate
  7034. * @param width defines the viewport width
  7035. * @param height defines the viewport height
  7036. */
  7037. function Viewport(
  7038. /** viewport left coordinate */
  7039. x,
  7040. /** viewport top coordinate */
  7041. y,
  7042. /**viewport width */
  7043. width,
  7044. /** viewport height */
  7045. height) {
  7046. this.x = x;
  7047. this.y = y;
  7048. this.width = width;
  7049. this.height = height;
  7050. }
  7051. /**
  7052. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7053. * @param renderWidthOrEngine defines either an engine or the rendering width
  7054. * @param renderHeight defines the rendering height
  7055. * @returns a new Viewport
  7056. */
  7057. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7058. if (renderWidthOrEngine.getRenderWidth) {
  7059. var engine = renderWidthOrEngine;
  7060. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7061. }
  7062. var renderWidth = renderWidthOrEngine;
  7063. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7064. };
  7065. /**
  7066. * Returns a new Viewport copied from the current one
  7067. * @returns a new Viewport
  7068. */
  7069. Viewport.prototype.clone = function () {
  7070. return new Viewport(this.x, this.y, this.width, this.height);
  7071. };
  7072. return Viewport;
  7073. }());
  7074. BABYLON.Viewport = Viewport;
  7075. /**
  7076. * Reprasents a camera frustum
  7077. */
  7078. var Frustum = /** @class */ (function () {
  7079. function Frustum() {
  7080. }
  7081. /**
  7082. * Gets the planes representing the frustum
  7083. * @param transform matrix to be applied to the returned planes
  7084. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7085. */
  7086. Frustum.GetPlanes = function (transform) {
  7087. var frustumPlanes = [];
  7088. for (var index = 0; index < 6; index++) {
  7089. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7090. }
  7091. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7092. return frustumPlanes;
  7093. };
  7094. /**
  7095. * Gets the near frustum plane transformed by the transform matrix
  7096. * @param transform transformation matrix to be applied to the resulting frustum plane
  7097. * @param frustumPlane the resuling frustum plane
  7098. */
  7099. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7100. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7101. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7102. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7103. frustumPlane.d = transform.m[15] + transform.m[14];
  7104. frustumPlane.normalize();
  7105. };
  7106. /**
  7107. * Gets the far frustum plane transformed by the transform matrix
  7108. * @param transform transformation matrix to be applied to the resulting frustum plane
  7109. * @param frustumPlane the resuling frustum plane
  7110. */
  7111. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7112. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7113. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7114. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7115. frustumPlane.d = transform.m[15] - transform.m[14];
  7116. frustumPlane.normalize();
  7117. };
  7118. /**
  7119. * Gets the left frustum plane transformed by the transform matrix
  7120. * @param transform transformation matrix to be applied to the resulting frustum plane
  7121. * @param frustumPlane the resuling frustum plane
  7122. */
  7123. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7124. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7125. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7126. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7127. frustumPlane.d = transform.m[15] + transform.m[12];
  7128. frustumPlane.normalize();
  7129. };
  7130. /**
  7131. * Gets the right frustum plane transformed by the transform matrix
  7132. * @param transform transformation matrix to be applied to the resulting frustum plane
  7133. * @param frustumPlane the resuling frustum plane
  7134. */
  7135. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7136. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7137. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7138. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7139. frustumPlane.d = transform.m[15] - transform.m[12];
  7140. frustumPlane.normalize();
  7141. };
  7142. /**
  7143. * Gets the top frustum plane transformed by the transform matrix
  7144. * @param transform transformation matrix to be applied to the resulting frustum plane
  7145. * @param frustumPlane the resuling frustum plane
  7146. */
  7147. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7148. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7149. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7150. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7151. frustumPlane.d = transform.m[15] - transform.m[13];
  7152. frustumPlane.normalize();
  7153. };
  7154. /**
  7155. * Gets the bottom frustum plane transformed by the transform matrix
  7156. * @param transform transformation matrix to be applied to the resulting frustum plane
  7157. * @param frustumPlane the resuling frustum plane
  7158. */
  7159. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7160. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7161. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7162. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7163. frustumPlane.d = transform.m[15] + transform.m[13];
  7164. frustumPlane.normalize();
  7165. };
  7166. /**
  7167. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7168. * @param transform transformation matrix to be applied to the resulting frustum planes
  7169. * @param frustumPlanes the resuling frustum planes
  7170. */
  7171. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7172. // Near
  7173. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7174. // Far
  7175. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7176. // Left
  7177. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7178. // Right
  7179. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7180. // Top
  7181. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7182. // Bottom
  7183. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7184. };
  7185. return Frustum;
  7186. }());
  7187. BABYLON.Frustum = Frustum;
  7188. /** Defines supported spaces */
  7189. var Space;
  7190. (function (Space) {
  7191. /** Local (object) space */
  7192. Space[Space["LOCAL"] = 0] = "LOCAL";
  7193. /** World space */
  7194. Space[Space["WORLD"] = 1] = "WORLD";
  7195. /** Bone space */
  7196. Space[Space["BONE"] = 2] = "BONE";
  7197. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7198. /** Defines the 3 main axes */
  7199. var Axis = /** @class */ (function () {
  7200. function Axis() {
  7201. }
  7202. /** X axis */
  7203. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7204. /** Y axis */
  7205. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7206. /** Z axis */
  7207. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7208. return Axis;
  7209. }());
  7210. BABYLON.Axis = Axis;
  7211. ;
  7212. /** Class used to represent a Bezier curve */
  7213. var BezierCurve = /** @class */ (function () {
  7214. function BezierCurve() {
  7215. }
  7216. /**
  7217. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7218. * @param t defines the time
  7219. * @param x1 defines the left coordinate on X axis
  7220. * @param y1 defines the left coordinate on Y axis
  7221. * @param x2 defines the right coordinate on X axis
  7222. * @param y2 defines the right coordinate on Y axis
  7223. * @returns the interpolated value
  7224. */
  7225. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7226. // Extract X (which is equal to time here)
  7227. var f0 = 1 - 3 * x2 + 3 * x1;
  7228. var f1 = 3 * x2 - 6 * x1;
  7229. var f2 = 3 * x1;
  7230. var refinedT = t;
  7231. for (var i = 0; i < 5; i++) {
  7232. var refinedT2 = refinedT * refinedT;
  7233. var refinedT3 = refinedT2 * refinedT;
  7234. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7235. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7236. refinedT -= (x - t) * slope;
  7237. refinedT = Math.min(1, Math.max(0, refinedT));
  7238. }
  7239. // Resolve cubic bezier for the given x
  7240. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7241. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7242. Math.pow(refinedT, 3);
  7243. };
  7244. return BezierCurve;
  7245. }());
  7246. BABYLON.BezierCurve = BezierCurve;
  7247. /**
  7248. * Defines potential orientation for back face culling
  7249. */
  7250. var Orientation;
  7251. (function (Orientation) {
  7252. /**
  7253. * Clockwise
  7254. */
  7255. Orientation[Orientation["CW"] = 0] = "CW";
  7256. /** Counter clockwise */
  7257. Orientation[Orientation["CCW"] = 1] = "CCW";
  7258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7259. /**
  7260. * Defines angle representation
  7261. */
  7262. var Angle = /** @class */ (function () {
  7263. /**
  7264. * Creates an Angle object of "radians" radians (float).
  7265. */
  7266. function Angle(radians) {
  7267. this._radians = radians;
  7268. if (this._radians < 0.0)
  7269. this._radians += (2.0 * Math.PI);
  7270. }
  7271. /**
  7272. * Get value in degrees
  7273. * @returns the Angle value in degrees (float)
  7274. */
  7275. Angle.prototype.degrees = function () {
  7276. return this._radians * 180.0 / Math.PI;
  7277. };
  7278. /**
  7279. * Get value in radians
  7280. * @returns the Angle value in radians (float)
  7281. */
  7282. Angle.prototype.radians = function () {
  7283. return this._radians;
  7284. };
  7285. /**
  7286. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7287. * @param a defines first vector
  7288. * @param b defines second vector
  7289. * @returns a new Angle
  7290. */
  7291. Angle.BetweenTwoPoints = function (a, b) {
  7292. var delta = b.subtract(a);
  7293. var theta = Math.atan2(delta.y, delta.x);
  7294. return new Angle(theta);
  7295. };
  7296. /**
  7297. * Gets a new Angle object from the given float in radians
  7298. * @param radians defines the angle value in radians
  7299. * @returns a new Angle
  7300. */
  7301. Angle.FromRadians = function (radians) {
  7302. return new Angle(radians);
  7303. };
  7304. /**
  7305. * Gets a new Angle object from the given float in degrees
  7306. * @param degrees defines the angle value in degrees
  7307. * @returns a new Angle
  7308. */
  7309. Angle.FromDegrees = function (degrees) {
  7310. return new Angle(degrees * Math.PI / 180.0);
  7311. };
  7312. return Angle;
  7313. }());
  7314. BABYLON.Angle = Angle;
  7315. /**
  7316. * This represents an arc in a 2d space.
  7317. */
  7318. var Arc2 = /** @class */ (function () {
  7319. /**
  7320. * Creates an Arc object from the three given points : start, middle and end.
  7321. * @param startPoint Defines the start point of the arc
  7322. * @param midPoint Defines the midlle point of the arc
  7323. * @param endPoint Defines the end point of the arc
  7324. */
  7325. function Arc2(
  7326. /** Defines the start point of the arc */
  7327. startPoint,
  7328. /** Defines the mid point of the arc */
  7329. midPoint,
  7330. /** Defines the end point of the arc */
  7331. endPoint) {
  7332. this.startPoint = startPoint;
  7333. this.midPoint = midPoint;
  7334. this.endPoint = endPoint;
  7335. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7336. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7337. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7338. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7339. 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);
  7340. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7341. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7342. var a1 = this.startAngle.degrees();
  7343. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7344. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7345. // angles correction
  7346. if (a2 - a1 > +180.0)
  7347. a2 -= 360.0;
  7348. if (a2 - a1 < -180.0)
  7349. a2 += 360.0;
  7350. if (a3 - a2 > +180.0)
  7351. a3 -= 360.0;
  7352. if (a3 - a2 < -180.0)
  7353. a3 += 360.0;
  7354. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7355. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7356. }
  7357. return Arc2;
  7358. }());
  7359. BABYLON.Arc2 = Arc2;
  7360. /**
  7361. * Represents a 2D path made up of multiple 2D points
  7362. */
  7363. var Path2 = /** @class */ (function () {
  7364. /**
  7365. * Creates a Path2 object from the starting 2D coordinates x and y.
  7366. * @param x the starting points x value
  7367. * @param y the starting points y value
  7368. */
  7369. function Path2(x, y) {
  7370. this._points = new Array();
  7371. this._length = 0.0;
  7372. /**
  7373. * If the path start and end point are the same
  7374. */
  7375. this.closed = false;
  7376. this._points.push(new Vector2(x, y));
  7377. }
  7378. /**
  7379. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7380. * @param x the added points x value
  7381. * @param y the added points y value
  7382. * @returns the updated Path2.
  7383. */
  7384. Path2.prototype.addLineTo = function (x, y) {
  7385. if (this.closed) {
  7386. return this;
  7387. }
  7388. var newPoint = new Vector2(x, y);
  7389. var previousPoint = this._points[this._points.length - 1];
  7390. this._points.push(newPoint);
  7391. this._length += newPoint.subtract(previousPoint).length();
  7392. return this;
  7393. };
  7394. /**
  7395. * 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.
  7396. * @param midX middle point x value
  7397. * @param midY middle point y value
  7398. * @param endX end point x value
  7399. * @param endY end point y value
  7400. * @param numberOfSegments (default: 36)
  7401. * @returns the updated Path2.
  7402. */
  7403. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7404. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7405. if (this.closed) {
  7406. return this;
  7407. }
  7408. var startPoint = this._points[this._points.length - 1];
  7409. var midPoint = new Vector2(midX, midY);
  7410. var endPoint = new Vector2(endX, endY);
  7411. var arc = new Arc2(startPoint, midPoint, endPoint);
  7412. var increment = arc.angle.radians() / numberOfSegments;
  7413. if (arc.orientation === Orientation.CW)
  7414. increment *= -1;
  7415. var currentAngle = arc.startAngle.radians() + increment;
  7416. for (var i = 0; i < numberOfSegments; i++) {
  7417. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7418. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7419. this.addLineTo(x, y);
  7420. currentAngle += increment;
  7421. }
  7422. return this;
  7423. };
  7424. /**
  7425. * Closes the Path2.
  7426. * @returns the Path2.
  7427. */
  7428. Path2.prototype.close = function () {
  7429. this.closed = true;
  7430. return this;
  7431. };
  7432. /**
  7433. * Gets the sum of the distance between each sequential point in the path
  7434. * @returns the Path2 total length (float).
  7435. */
  7436. Path2.prototype.length = function () {
  7437. var result = this._length;
  7438. if (!this.closed) {
  7439. var lastPoint = this._points[this._points.length - 1];
  7440. var firstPoint = this._points[0];
  7441. result += (firstPoint.subtract(lastPoint).length());
  7442. }
  7443. return result;
  7444. };
  7445. /**
  7446. * Gets the points which construct the path
  7447. * @returns the Path2 internal array of points.
  7448. */
  7449. Path2.prototype.getPoints = function () {
  7450. return this._points;
  7451. };
  7452. /**
  7453. * Retreives the point at the distance aways from the starting point
  7454. * @param normalizedLengthPosition the length along the path to retreive the point from
  7455. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7456. */
  7457. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7458. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7459. return Vector2.Zero();
  7460. }
  7461. var lengthPosition = normalizedLengthPosition * this.length();
  7462. var previousOffset = 0;
  7463. for (var i = 0; i < this._points.length; i++) {
  7464. var j = (i + 1) % this._points.length;
  7465. var a = this._points[i];
  7466. var b = this._points[j];
  7467. var bToA = b.subtract(a);
  7468. var nextOffset = (bToA.length() + previousOffset);
  7469. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7470. var dir = bToA.normalize();
  7471. var localOffset = lengthPosition - previousOffset;
  7472. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7473. }
  7474. previousOffset = nextOffset;
  7475. }
  7476. return Vector2.Zero();
  7477. };
  7478. /**
  7479. * Creates a new path starting from an x and y position
  7480. * @param x starting x value
  7481. * @param y starting y value
  7482. * @returns a new Path2 starting at the coordinates (x, y).
  7483. */
  7484. Path2.StartingAt = function (x, y) {
  7485. return new Path2(x, y);
  7486. };
  7487. return Path2;
  7488. }());
  7489. BABYLON.Path2 = Path2;
  7490. /**
  7491. * Represents a 3D path made up of multiple 3D points
  7492. */
  7493. var Path3D = /** @class */ (function () {
  7494. /**
  7495. * new Path3D(path, normal, raw)
  7496. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7497. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7498. * @param path an array of Vector3, the curve axis of the Path3D
  7499. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7500. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7501. */
  7502. function Path3D(
  7503. /**
  7504. * an array of Vector3, the curve axis of the Path3D
  7505. */
  7506. path, firstNormal, raw) {
  7507. if (firstNormal === void 0) { firstNormal = null; }
  7508. this.path = path;
  7509. this._curve = new Array();
  7510. this._distances = new Array();
  7511. this._tangents = new Array();
  7512. this._normals = new Array();
  7513. this._binormals = new Array();
  7514. for (var p = 0; p < path.length; p++) {
  7515. this._curve[p] = path[p].clone(); // hard copy
  7516. }
  7517. this._raw = raw || false;
  7518. this._compute(firstNormal);
  7519. }
  7520. /**
  7521. * Returns the Path3D array of successive Vector3 designing its curve.
  7522. * @returns the Path3D array of successive Vector3 designing its curve.
  7523. */
  7524. Path3D.prototype.getCurve = function () {
  7525. return this._curve;
  7526. };
  7527. /**
  7528. * Returns an array populated with tangent vectors on each Path3D curve point.
  7529. * @returns an array populated with tangent vectors on each Path3D curve point.
  7530. */
  7531. Path3D.prototype.getTangents = function () {
  7532. return this._tangents;
  7533. };
  7534. /**
  7535. * Returns an array populated with normal vectors on each Path3D curve point.
  7536. * @returns an array populated with normal vectors on each Path3D curve point.
  7537. */
  7538. Path3D.prototype.getNormals = function () {
  7539. return this._normals;
  7540. };
  7541. /**
  7542. * Returns an array populated with binormal vectors on each Path3D curve point.
  7543. * @returns an array populated with binormal vectors on each Path3D curve point.
  7544. */
  7545. Path3D.prototype.getBinormals = function () {
  7546. return this._binormals;
  7547. };
  7548. /**
  7549. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7550. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7551. */
  7552. Path3D.prototype.getDistances = function () {
  7553. return this._distances;
  7554. };
  7555. /**
  7556. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7557. * @param path path which all values are copied into the curves points
  7558. * @param firstNormal which should be projected onto the curve
  7559. * @returns the same object updated.
  7560. */
  7561. Path3D.prototype.update = function (path, firstNormal) {
  7562. if (firstNormal === void 0) { firstNormal = null; }
  7563. for (var p = 0; p < path.length; p++) {
  7564. this._curve[p].x = path[p].x;
  7565. this._curve[p].y = path[p].y;
  7566. this._curve[p].z = path[p].z;
  7567. }
  7568. this._compute(firstNormal);
  7569. return this;
  7570. };
  7571. // private function compute() : computes tangents, normals and binormals
  7572. Path3D.prototype._compute = function (firstNormal) {
  7573. var l = this._curve.length;
  7574. // first and last tangents
  7575. this._tangents[0] = this._getFirstNonNullVector(0);
  7576. if (!this._raw) {
  7577. this._tangents[0].normalize();
  7578. }
  7579. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7580. if (!this._raw) {
  7581. this._tangents[l - 1].normalize();
  7582. }
  7583. // normals and binormals at first point : arbitrary vector with _normalVector()
  7584. var tg0 = this._tangents[0];
  7585. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7586. this._normals[0] = pp0;
  7587. if (!this._raw) {
  7588. this._normals[0].normalize();
  7589. }
  7590. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7591. if (!this._raw) {
  7592. this._binormals[0].normalize();
  7593. }
  7594. this._distances[0] = 0.0;
  7595. // normals and binormals : next points
  7596. var prev; // previous vector (segment)
  7597. var cur; // current vector (segment)
  7598. var curTang; // current tangent
  7599. // previous normal
  7600. var prevBinor; // previous binormal
  7601. for (var i = 1; i < l; i++) {
  7602. // tangents
  7603. prev = this._getLastNonNullVector(i);
  7604. if (i < l - 1) {
  7605. cur = this._getFirstNonNullVector(i);
  7606. this._tangents[i] = prev.add(cur);
  7607. this._tangents[i].normalize();
  7608. }
  7609. this._distances[i] = this._distances[i - 1] + prev.length();
  7610. // normals and binormals
  7611. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7612. curTang = this._tangents[i];
  7613. prevBinor = this._binormals[i - 1];
  7614. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7615. if (!this._raw) {
  7616. this._normals[i].normalize();
  7617. }
  7618. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7619. if (!this._raw) {
  7620. this._binormals[i].normalize();
  7621. }
  7622. }
  7623. };
  7624. // private function getFirstNonNullVector(index)
  7625. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7626. Path3D.prototype._getFirstNonNullVector = function (index) {
  7627. var i = 1;
  7628. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7629. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7630. i++;
  7631. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7632. }
  7633. return nNVector;
  7634. };
  7635. // private function getLastNonNullVector(index)
  7636. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7637. Path3D.prototype._getLastNonNullVector = function (index) {
  7638. var i = 1;
  7639. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7640. while (nLVector.length() === 0 && index > i + 1) {
  7641. i++;
  7642. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7643. }
  7644. return nLVector;
  7645. };
  7646. // private function normalVector(v0, vt, va) :
  7647. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7648. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7649. Path3D.prototype._normalVector = function (v0, vt, va) {
  7650. var normal0;
  7651. var tgl = vt.length();
  7652. if (tgl === 0.0) {
  7653. tgl = 1.0;
  7654. }
  7655. if (va === undefined || va === null) {
  7656. var point;
  7657. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7658. point = new Vector3(0.0, -1.0, 0.0);
  7659. }
  7660. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7661. point = new Vector3(1.0, 0.0, 0.0);
  7662. }
  7663. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7664. point = new Vector3(0.0, 0.0, 1.0);
  7665. }
  7666. else {
  7667. point = Vector3.Zero();
  7668. }
  7669. normal0 = Vector3.Cross(vt, point);
  7670. }
  7671. else {
  7672. normal0 = Vector3.Cross(vt, va);
  7673. Vector3.CrossToRef(normal0, vt, normal0);
  7674. }
  7675. normal0.normalize();
  7676. return normal0;
  7677. };
  7678. return Path3D;
  7679. }());
  7680. BABYLON.Path3D = Path3D;
  7681. /**
  7682. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7683. * A Curve3 is designed from a series of successive Vector3.
  7684. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7685. */
  7686. var Curve3 = /** @class */ (function () {
  7687. /**
  7688. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7689. * A Curve3 is designed from a series of successive Vector3.
  7690. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7691. * @param points points which make up the curve
  7692. */
  7693. function Curve3(points) {
  7694. this._length = 0.0;
  7695. this._points = points;
  7696. this._length = this._computeLength(points);
  7697. }
  7698. /**
  7699. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7700. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7701. * @param v1 (Vector3) the control point
  7702. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7703. * @param nbPoints (integer) the wanted number of points in the curve
  7704. * @returns the created Curve3
  7705. */
  7706. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7707. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7708. var bez = new Array();
  7709. var equation = function (t, val0, val1, val2) {
  7710. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7711. return res;
  7712. };
  7713. for (var i = 0; i <= nbPoints; i++) {
  7714. 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)));
  7715. }
  7716. return new Curve3(bez);
  7717. };
  7718. /**
  7719. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7720. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7721. * @param v1 (Vector3) the first control point
  7722. * @param v2 (Vector3) the second control point
  7723. * @param v3 (Vector3) the end point of the Cubic Bezier
  7724. * @param nbPoints (integer) the wanted number of points in the curve
  7725. * @returns the created Curve3
  7726. */
  7727. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7728. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7729. var bez = new Array();
  7730. var equation = function (t, val0, val1, val2, val3) {
  7731. 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;
  7732. return res;
  7733. };
  7734. for (var i = 0; i <= nbPoints; i++) {
  7735. 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)));
  7736. }
  7737. return new Curve3(bez);
  7738. };
  7739. /**
  7740. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7741. * @param p1 (Vector3) the origin point of the Hermite Spline
  7742. * @param t1 (Vector3) the tangent vector at the origin point
  7743. * @param p2 (Vector3) the end point of the Hermite Spline
  7744. * @param t2 (Vector3) the tangent vector at the end point
  7745. * @param nbPoints (integer) the wanted number of points in the curve
  7746. * @returns the created Curve3
  7747. */
  7748. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7749. var hermite = new Array();
  7750. var step = 1.0 / nbPoints;
  7751. for (var i = 0; i <= nbPoints; i++) {
  7752. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7753. }
  7754. return new Curve3(hermite);
  7755. };
  7756. /**
  7757. * Returns a Curve3 object along a CatmullRom Spline curve :
  7758. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7759. * @param nbPoints (integer) the wanted number of points between each curve control points
  7760. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7761. * @returns the created Curve3
  7762. */
  7763. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7764. var catmullRom = new Array();
  7765. var step = 1.0 / nbPoints;
  7766. var amount = 0.0;
  7767. if (closed) {
  7768. var pointsCount = points.length;
  7769. for (var i = 0; i < pointsCount; i++) {
  7770. amount = 0;
  7771. for (var c = 0; c < nbPoints; c++) {
  7772. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7773. amount += step;
  7774. }
  7775. }
  7776. catmullRom.push(catmullRom[0]);
  7777. }
  7778. else {
  7779. var totalPoints = new Array();
  7780. totalPoints.push(points[0].clone());
  7781. Array.prototype.push.apply(totalPoints, points);
  7782. totalPoints.push(points[points.length - 1].clone());
  7783. for (var i = 0; i < totalPoints.length - 3; i++) {
  7784. amount = 0;
  7785. for (var c = 0; c < nbPoints; c++) {
  7786. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7787. amount += step;
  7788. }
  7789. }
  7790. i--;
  7791. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7792. }
  7793. return new Curve3(catmullRom);
  7794. };
  7795. /**
  7796. * @returns the Curve3 stored array of successive Vector3
  7797. */
  7798. Curve3.prototype.getPoints = function () {
  7799. return this._points;
  7800. };
  7801. /**
  7802. * @returns the computed length (float) of the curve.
  7803. */
  7804. Curve3.prototype.length = function () {
  7805. return this._length;
  7806. };
  7807. /**
  7808. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7809. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7810. * curveA and curveB keep unchanged.
  7811. * @param curve the curve to continue from this curve
  7812. * @returns the newly constructed curve
  7813. */
  7814. Curve3.prototype.continue = function (curve) {
  7815. var lastPoint = this._points[this._points.length - 1];
  7816. var continuedPoints = this._points.slice();
  7817. var curvePoints = curve.getPoints();
  7818. for (var i = 1; i < curvePoints.length; i++) {
  7819. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7820. }
  7821. var continuedCurve = new Curve3(continuedPoints);
  7822. return continuedCurve;
  7823. };
  7824. Curve3.prototype._computeLength = function (path) {
  7825. var l = 0;
  7826. for (var i = 1; i < path.length; i++) {
  7827. l += (path[i].subtract(path[i - 1])).length();
  7828. }
  7829. return l;
  7830. };
  7831. return Curve3;
  7832. }());
  7833. BABYLON.Curve3 = Curve3;
  7834. // Vertex formats
  7835. /**
  7836. * Contains position and normal vectors for a vertex
  7837. */
  7838. var PositionNormalVertex = /** @class */ (function () {
  7839. /**
  7840. * Creates a PositionNormalVertex
  7841. * @param position the position of the vertex (defaut: 0,0,0)
  7842. * @param normal the normal of the vertex (defaut: 0,1,0)
  7843. */
  7844. function PositionNormalVertex(
  7845. /** the position of the vertex (defaut: 0,0,0) */
  7846. position,
  7847. /** the normal of the vertex (defaut: 0,1,0) */
  7848. normal) {
  7849. if (position === void 0) { position = Vector3.Zero(); }
  7850. if (normal === void 0) { normal = Vector3.Up(); }
  7851. this.position = position;
  7852. this.normal = normal;
  7853. }
  7854. /**
  7855. * Clones the PositionNormalVertex
  7856. * @returns the cloned PositionNormalVertex
  7857. */
  7858. PositionNormalVertex.prototype.clone = function () {
  7859. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7860. };
  7861. return PositionNormalVertex;
  7862. }());
  7863. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7864. /**
  7865. * Contains position, normal and uv vectors for a vertex
  7866. */
  7867. var PositionNormalTextureVertex = /** @class */ (function () {
  7868. /**
  7869. * Creates a PositionNormalTextureVertex
  7870. * @param position the position of the vertex (defaut: 0,0,0)
  7871. * @param normal the normal of the vertex (defaut: 0,1,0)
  7872. * @param uv the uv of the vertex (default: 0,0)
  7873. */
  7874. function PositionNormalTextureVertex(
  7875. /** the position of the vertex (defaut: 0,0,0) */
  7876. position,
  7877. /** the normal of the vertex (defaut: 0,1,0) */
  7878. normal,
  7879. /** the uv of the vertex (default: 0,0) */
  7880. uv) {
  7881. if (position === void 0) { position = Vector3.Zero(); }
  7882. if (normal === void 0) { normal = Vector3.Up(); }
  7883. if (uv === void 0) { uv = Vector2.Zero(); }
  7884. this.position = position;
  7885. this.normal = normal;
  7886. this.uv = uv;
  7887. }
  7888. /**
  7889. * Clones the PositionNormalTextureVertex
  7890. * @returns the cloned PositionNormalTextureVertex
  7891. */
  7892. PositionNormalTextureVertex.prototype.clone = function () {
  7893. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7894. };
  7895. return PositionNormalTextureVertex;
  7896. }());
  7897. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7898. // Temporary pre-allocated objects for engine internal use
  7899. // usage in any internal function :
  7900. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7901. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7902. /**
  7903. * @hidden
  7904. */
  7905. var Tmp = /** @class */ (function () {
  7906. function Tmp() {
  7907. }
  7908. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7909. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7910. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7911. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7912. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7913. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7914. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7915. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7916. Matrix.Zero(), Matrix.Zero(),
  7917. Matrix.Zero(), Matrix.Zero(),
  7918. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7919. return Tmp;
  7920. }());
  7921. BABYLON.Tmp = Tmp;
  7922. /**
  7923. * @hidden
  7924. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7925. */
  7926. var MathTmp = /** @class */ (function () {
  7927. function MathTmp() {
  7928. }
  7929. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7930. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7931. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7932. return MathTmp;
  7933. }());
  7934. })(BABYLON || (BABYLON = {}));
  7935. //# sourceMappingURL=babylon.math.js.map
  7936. var BABYLON;
  7937. (function (BABYLON) {
  7938. var Scalar = /** @class */ (function () {
  7939. function Scalar() {
  7940. }
  7941. /**
  7942. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7943. */
  7944. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7945. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7946. var num = a - b;
  7947. return -epsilon <= num && num <= epsilon;
  7948. };
  7949. /**
  7950. * Returns a string : the upper case translation of the number i to hexadecimal.
  7951. */
  7952. Scalar.ToHex = function (i) {
  7953. var str = i.toString(16);
  7954. if (i <= 15) {
  7955. return ("0" + str).toUpperCase();
  7956. }
  7957. return str.toUpperCase();
  7958. };
  7959. /**
  7960. * Returns -1 if value is negative and +1 is value is positive.
  7961. * Returns the value itself if it's equal to zero.
  7962. */
  7963. Scalar.Sign = function (value) {
  7964. value = +value; // convert to a number
  7965. if (value === 0 || isNaN(value))
  7966. return value;
  7967. return value > 0 ? 1 : -1;
  7968. };
  7969. /**
  7970. * Returns the value itself if it's between min and max.
  7971. * Returns min if the value is lower than min.
  7972. * Returns max if the value is greater than max.
  7973. */
  7974. Scalar.Clamp = function (value, min, max) {
  7975. if (min === void 0) { min = 0; }
  7976. if (max === void 0) { max = 1; }
  7977. return Math.min(max, Math.max(min, value));
  7978. };
  7979. /**
  7980. * Returns the log2 of value.
  7981. */
  7982. Scalar.Log2 = function (value) {
  7983. return Math.log(value) * Math.LOG2E;
  7984. };
  7985. /**
  7986. * Loops the value, so that it is never larger than length and never smaller than 0.
  7987. *
  7988. * This is similar to the modulo operator but it works with floating point numbers.
  7989. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7990. * With t = 5 and length = 2.5, the result would be 0.0.
  7991. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7992. */
  7993. Scalar.Repeat = function (value, length) {
  7994. return value - Math.floor(value / length) * length;
  7995. };
  7996. /**
  7997. * Normalize the value between 0.0 and 1.0 using min and max values
  7998. */
  7999. Scalar.Normalize = function (value, min, max) {
  8000. return (value - min) / (max - min);
  8001. };
  8002. /**
  8003. * Denormalize the value from 0.0 and 1.0 using min and max values
  8004. */
  8005. Scalar.Denormalize = function (normalized, min, max) {
  8006. return (normalized * (max - min) + min);
  8007. };
  8008. /**
  8009. * Calculates the shortest difference between two given angles given in degrees.
  8010. */
  8011. Scalar.DeltaAngle = function (current, target) {
  8012. var num = Scalar.Repeat(target - current, 360.0);
  8013. if (num > 180.0) {
  8014. num -= 360.0;
  8015. }
  8016. return num;
  8017. };
  8018. /**
  8019. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8020. *
  8021. * The returned value will move back and forth between 0 and length
  8022. */
  8023. Scalar.PingPong = function (tx, length) {
  8024. var t = Scalar.Repeat(tx, length * 2.0);
  8025. return length - Math.abs(t - length);
  8026. };
  8027. /**
  8028. * Interpolates between min and max with smoothing at the limits.
  8029. *
  8030. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8031. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8032. */
  8033. Scalar.SmoothStep = function (from, to, tx) {
  8034. var t = Scalar.Clamp(tx);
  8035. t = -2.0 * t * t * t + 3.0 * t * t;
  8036. return to * t + from * (1.0 - t);
  8037. };
  8038. /**
  8039. * Moves a value current towards target.
  8040. *
  8041. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8042. * Negative values of maxDelta pushes the value away from target.
  8043. */
  8044. Scalar.MoveTowards = function (current, target, maxDelta) {
  8045. var result = 0;
  8046. if (Math.abs(target - current) <= maxDelta) {
  8047. result = target;
  8048. }
  8049. else {
  8050. result = current + Scalar.Sign(target - current) * maxDelta;
  8051. }
  8052. return result;
  8053. };
  8054. /**
  8055. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8056. *
  8057. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8058. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8059. */
  8060. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8061. var num = Scalar.DeltaAngle(current, target);
  8062. var result = 0;
  8063. if (-maxDelta < num && num < maxDelta) {
  8064. result = target;
  8065. }
  8066. else {
  8067. target = current + num;
  8068. result = Scalar.MoveTowards(current, target, maxDelta);
  8069. }
  8070. return result;
  8071. };
  8072. /**
  8073. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8074. */
  8075. Scalar.Lerp = function (start, end, amount) {
  8076. return start + ((end - start) * amount);
  8077. };
  8078. /**
  8079. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8080. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8081. */
  8082. Scalar.LerpAngle = function (start, end, amount) {
  8083. var num = Scalar.Repeat(end - start, 360.0);
  8084. if (num > 180.0) {
  8085. num -= 360.0;
  8086. }
  8087. return start + num * Scalar.Clamp(amount);
  8088. };
  8089. /**
  8090. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8091. */
  8092. Scalar.InverseLerp = function (a, b, value) {
  8093. var result = 0;
  8094. if (a != b) {
  8095. result = Scalar.Clamp((value - a) / (b - a));
  8096. }
  8097. else {
  8098. result = 0.0;
  8099. }
  8100. return result;
  8101. };
  8102. /**
  8103. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8104. */
  8105. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8106. var squared = amount * amount;
  8107. var cubed = amount * squared;
  8108. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8109. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8110. var part3 = (cubed - (2.0 * squared)) + amount;
  8111. var part4 = cubed - squared;
  8112. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8113. };
  8114. /**
  8115. * Returns a random float number between and min and max values
  8116. */
  8117. Scalar.RandomRange = function (min, max) {
  8118. if (min === max)
  8119. return min;
  8120. return ((Math.random() * (max - min)) + min);
  8121. };
  8122. /**
  8123. * This function returns percentage of a number in a given range.
  8124. *
  8125. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8126. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8127. */
  8128. Scalar.RangeToPercent = function (number, min, max) {
  8129. return ((number - min) / (max - min));
  8130. };
  8131. /**
  8132. * This function returns number that corresponds to the percentage in a given range.
  8133. *
  8134. * PercentToRange(0.34,0,100) will return 34.
  8135. */
  8136. Scalar.PercentToRange = function (percent, min, max) {
  8137. return ((max - min) * percent + min);
  8138. };
  8139. /**
  8140. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8141. * @param angle The angle to normalize in radian.
  8142. * @return The converted angle.
  8143. */
  8144. Scalar.NormalizeRadians = function (angle) {
  8145. // More precise but slower version kept for reference.
  8146. // angle = angle % Tools.TwoPi;
  8147. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8148. //if (angle > Math.PI) {
  8149. // angle -= Tools.TwoPi;
  8150. //}
  8151. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8152. return angle;
  8153. };
  8154. /**
  8155. * Two pi constants convenient for computation.
  8156. */
  8157. Scalar.TwoPi = Math.PI * 2;
  8158. return Scalar;
  8159. }());
  8160. BABYLON.Scalar = Scalar;
  8161. })(BABYLON || (BABYLON = {}));
  8162. //# sourceMappingURL=babylon.math.scalar.js.map
  8163. //# sourceMappingURL=babylon.mixins.js.map
  8164. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8165. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8166. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8167. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8168. //# sourceMappingURL=babylon.webgl2.js.map
  8169. var BABYLON;
  8170. (function (BABYLON) {
  8171. var __decoratorInitialStore = {};
  8172. var __mergedStore = {};
  8173. var _copySource = function (creationFunction, source, instanciate) {
  8174. var destination = creationFunction();
  8175. // Tags
  8176. if (BABYLON.Tags) {
  8177. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8178. }
  8179. var classStore = getMergedStore(destination);
  8180. // Properties
  8181. for (var property in classStore) {
  8182. var propertyDescriptor = classStore[property];
  8183. var sourceProperty = source[property];
  8184. var propertyType = propertyDescriptor.type;
  8185. if (sourceProperty !== undefined && sourceProperty !== null) {
  8186. switch (propertyType) {
  8187. case 0: // Value
  8188. case 6: // Mesh reference
  8189. case 11: // Camera reference
  8190. destination[property] = sourceProperty;
  8191. break;
  8192. case 1: // Texture
  8193. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8194. break;
  8195. case 2: // Color3
  8196. case 3: // FresnelParameters
  8197. case 4: // Vector2
  8198. case 5: // Vector3
  8199. case 7: // Color Curves
  8200. case 10: // Quaternion
  8201. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8202. break;
  8203. }
  8204. }
  8205. }
  8206. return destination;
  8207. };
  8208. function getDirectStore(target) {
  8209. var classKey = target.getClassName();
  8210. if (!__decoratorInitialStore[classKey]) {
  8211. __decoratorInitialStore[classKey] = {};
  8212. }
  8213. return __decoratorInitialStore[classKey];
  8214. }
  8215. /**
  8216. * Return the list of properties flagged as serializable
  8217. * @param target: host object
  8218. */
  8219. function getMergedStore(target) {
  8220. var classKey = target.getClassName();
  8221. if (__mergedStore[classKey]) {
  8222. return __mergedStore[classKey];
  8223. }
  8224. __mergedStore[classKey] = {};
  8225. var store = __mergedStore[classKey];
  8226. var currentTarget = target;
  8227. var currentKey = classKey;
  8228. while (currentKey) {
  8229. var initialStore = __decoratorInitialStore[currentKey];
  8230. for (var property in initialStore) {
  8231. store[property] = initialStore[property];
  8232. }
  8233. var parent_1 = void 0;
  8234. var done = false;
  8235. do {
  8236. parent_1 = Object.getPrototypeOf(currentTarget);
  8237. if (!parent_1.getClassName) {
  8238. done = true;
  8239. break;
  8240. }
  8241. if (parent_1.getClassName() !== currentKey) {
  8242. break;
  8243. }
  8244. currentTarget = parent_1;
  8245. } while (parent_1);
  8246. if (done) {
  8247. break;
  8248. }
  8249. currentKey = parent_1.getClassName();
  8250. currentTarget = parent_1;
  8251. }
  8252. return store;
  8253. }
  8254. function generateSerializableMember(type, sourceName) {
  8255. return function (target, propertyKey) {
  8256. var classStore = getDirectStore(target);
  8257. if (!classStore[propertyKey]) {
  8258. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8259. }
  8260. };
  8261. }
  8262. function generateExpandMember(setCallback, targetKey) {
  8263. if (targetKey === void 0) { targetKey = null; }
  8264. return function (target, propertyKey) {
  8265. var key = targetKey || ("_" + propertyKey);
  8266. Object.defineProperty(target, propertyKey, {
  8267. get: function () {
  8268. return this[key];
  8269. },
  8270. set: function (value) {
  8271. if (this[key] === value) {
  8272. return;
  8273. }
  8274. this[key] = value;
  8275. target[setCallback].apply(this);
  8276. },
  8277. enumerable: true,
  8278. configurable: true
  8279. });
  8280. };
  8281. }
  8282. function expandToProperty(callback, targetKey) {
  8283. if (targetKey === void 0) { targetKey = null; }
  8284. return generateExpandMember(callback, targetKey);
  8285. }
  8286. BABYLON.expandToProperty = expandToProperty;
  8287. function serialize(sourceName) {
  8288. return generateSerializableMember(0, sourceName); // value member
  8289. }
  8290. BABYLON.serialize = serialize;
  8291. function serializeAsTexture(sourceName) {
  8292. return generateSerializableMember(1, sourceName); // texture member
  8293. }
  8294. BABYLON.serializeAsTexture = serializeAsTexture;
  8295. function serializeAsColor3(sourceName) {
  8296. return generateSerializableMember(2, sourceName); // color3 member
  8297. }
  8298. BABYLON.serializeAsColor3 = serializeAsColor3;
  8299. function serializeAsFresnelParameters(sourceName) {
  8300. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8301. }
  8302. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8303. function serializeAsVector2(sourceName) {
  8304. return generateSerializableMember(4, sourceName); // vector2 member
  8305. }
  8306. BABYLON.serializeAsVector2 = serializeAsVector2;
  8307. function serializeAsVector3(sourceName) {
  8308. return generateSerializableMember(5, sourceName); // vector3 member
  8309. }
  8310. BABYLON.serializeAsVector3 = serializeAsVector3;
  8311. function serializeAsMeshReference(sourceName) {
  8312. return generateSerializableMember(6, sourceName); // mesh reference member
  8313. }
  8314. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8315. function serializeAsColorCurves(sourceName) {
  8316. return generateSerializableMember(7, sourceName); // color curves
  8317. }
  8318. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8319. function serializeAsColor4(sourceName) {
  8320. return generateSerializableMember(8, sourceName); // color 4
  8321. }
  8322. BABYLON.serializeAsColor4 = serializeAsColor4;
  8323. function serializeAsImageProcessingConfiguration(sourceName) {
  8324. return generateSerializableMember(9, sourceName); // image processing
  8325. }
  8326. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8327. function serializeAsQuaternion(sourceName) {
  8328. return generateSerializableMember(10, sourceName); // quaternion member
  8329. }
  8330. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8331. /**
  8332. * Decorator used to define property that can be serialized as reference to a camera
  8333. * @param sourceName defines the name of the property to decorate
  8334. */
  8335. function serializeAsCameraReference(sourceName) {
  8336. return generateSerializableMember(11, sourceName); // camera reference member
  8337. }
  8338. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8339. var SerializationHelper = /** @class */ (function () {
  8340. function SerializationHelper() {
  8341. }
  8342. SerializationHelper.Serialize = function (entity, serializationObject) {
  8343. if (!serializationObject) {
  8344. serializationObject = {};
  8345. }
  8346. // Tags
  8347. if (BABYLON.Tags) {
  8348. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8349. }
  8350. var serializedProperties = getMergedStore(entity);
  8351. // Properties
  8352. for (var property in serializedProperties) {
  8353. var propertyDescriptor = serializedProperties[property];
  8354. var targetPropertyName = propertyDescriptor.sourceName || property;
  8355. var propertyType = propertyDescriptor.type;
  8356. var sourceProperty = entity[property];
  8357. if (sourceProperty !== undefined && sourceProperty !== null) {
  8358. switch (propertyType) {
  8359. case 0: // Value
  8360. serializationObject[targetPropertyName] = sourceProperty;
  8361. break;
  8362. case 1: // Texture
  8363. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8364. break;
  8365. case 2: // Color3
  8366. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8367. break;
  8368. case 3: // FresnelParameters
  8369. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8370. break;
  8371. case 4: // Vector2
  8372. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8373. break;
  8374. case 5: // Vector3
  8375. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8376. break;
  8377. case 6: // Mesh reference
  8378. serializationObject[targetPropertyName] = sourceProperty.id;
  8379. break;
  8380. case 7: // Color Curves
  8381. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8382. break;
  8383. case 8: // Color 4
  8384. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8385. break;
  8386. case 9: // Image Processing
  8387. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8388. break;
  8389. case 10: // Quaternion
  8390. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8391. break;
  8392. case 11: // Camera reference
  8393. serializationObject[targetPropertyName] = sourceProperty.id;
  8394. break;
  8395. }
  8396. }
  8397. }
  8398. return serializationObject;
  8399. };
  8400. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8401. if (rootUrl === void 0) { rootUrl = null; }
  8402. var destination = creationFunction();
  8403. if (!rootUrl) {
  8404. rootUrl = "";
  8405. }
  8406. // Tags
  8407. if (BABYLON.Tags) {
  8408. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8409. }
  8410. var classStore = getMergedStore(destination);
  8411. // Properties
  8412. for (var property in classStore) {
  8413. var propertyDescriptor = classStore[property];
  8414. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8415. var propertyType = propertyDescriptor.type;
  8416. if (sourceProperty !== undefined && sourceProperty !== null) {
  8417. var dest = destination;
  8418. switch (propertyType) {
  8419. case 0: // Value
  8420. dest[property] = sourceProperty;
  8421. break;
  8422. case 1: // Texture
  8423. if (scene) {
  8424. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8425. }
  8426. break;
  8427. case 2: // Color3
  8428. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8429. break;
  8430. case 3: // FresnelParameters
  8431. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8432. break;
  8433. case 4: // Vector2
  8434. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8435. break;
  8436. case 5: // Vector3
  8437. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8438. break;
  8439. case 6: // Mesh reference
  8440. if (scene) {
  8441. dest[property] = scene.getLastMeshByID(sourceProperty);
  8442. }
  8443. break;
  8444. case 7: // Color Curves
  8445. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8446. break;
  8447. case 8: // Color 4
  8448. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8449. break;
  8450. case 9: // Image Processing
  8451. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8452. break;
  8453. case 10: // Quaternion
  8454. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8455. break;
  8456. case 11: // Camera reference
  8457. if (scene) {
  8458. dest[property] = scene.getCameraByID(sourceProperty);
  8459. }
  8460. break;
  8461. }
  8462. }
  8463. }
  8464. return destination;
  8465. };
  8466. SerializationHelper.Clone = function (creationFunction, source) {
  8467. return _copySource(creationFunction, source, false);
  8468. };
  8469. SerializationHelper.Instanciate = function (creationFunction, source) {
  8470. return _copySource(creationFunction, source, true);
  8471. };
  8472. return SerializationHelper;
  8473. }());
  8474. BABYLON.SerializationHelper = SerializationHelper;
  8475. })(BABYLON || (BABYLON = {}));
  8476. //# sourceMappingURL=babylon.decorators.js.map
  8477. var BABYLON;
  8478. (function (BABYLON) {
  8479. /**
  8480. * Wrapper class for promise with external resolve and reject.
  8481. */
  8482. var Deferred = /** @class */ (function () {
  8483. /**
  8484. * Constructor for this deferred object.
  8485. */
  8486. function Deferred() {
  8487. var _this = this;
  8488. this.promise = new Promise(function (resolve, reject) {
  8489. _this._resolve = resolve;
  8490. _this._reject = reject;
  8491. });
  8492. }
  8493. Object.defineProperty(Deferred.prototype, "resolve", {
  8494. /**
  8495. * The resolve method of the promise associated with this deferred object.
  8496. */
  8497. get: function () {
  8498. return this._resolve;
  8499. },
  8500. enumerable: true,
  8501. configurable: true
  8502. });
  8503. Object.defineProperty(Deferred.prototype, "reject", {
  8504. /**
  8505. * The reject method of the promise associated with this deferred object.
  8506. */
  8507. get: function () {
  8508. return this._reject;
  8509. },
  8510. enumerable: true,
  8511. configurable: true
  8512. });
  8513. return Deferred;
  8514. }());
  8515. BABYLON.Deferred = Deferred;
  8516. })(BABYLON || (BABYLON = {}));
  8517. //# sourceMappingURL=babylon.deferred.js.map
  8518. var BABYLON;
  8519. (function (BABYLON) {
  8520. /**
  8521. * A class serves as a medium between the observable and its observers
  8522. */
  8523. var EventState = /** @class */ (function () {
  8524. /**
  8525. * Create a new EventState
  8526. * @param mask defines the mask associated with this state
  8527. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8528. * @param target defines the original target of the state
  8529. * @param currentTarget defines the current target of the state
  8530. */
  8531. function EventState(mask, skipNextObservers, target, currentTarget) {
  8532. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8533. this.initalize(mask, skipNextObservers, target, currentTarget);
  8534. }
  8535. /**
  8536. * Initialize the current event state
  8537. * @param mask defines the mask associated with this state
  8538. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8539. * @param target defines the original target of the state
  8540. * @param currentTarget defines the current target of the state
  8541. * @returns the current event state
  8542. */
  8543. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8544. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8545. this.mask = mask;
  8546. this.skipNextObservers = skipNextObservers;
  8547. this.target = target;
  8548. this.currentTarget = currentTarget;
  8549. return this;
  8550. };
  8551. return EventState;
  8552. }());
  8553. BABYLON.EventState = EventState;
  8554. /**
  8555. * Represent an Observer registered to a given Observable object.
  8556. */
  8557. var Observer = /** @class */ (function () {
  8558. /**
  8559. * Creates a new observer
  8560. * @param callback defines the callback to call when the observer is notified
  8561. * @param mask defines the mask of the observer (used to filter notifications)
  8562. * @param scope defines the current scope used to restore the JS context
  8563. */
  8564. function Observer(
  8565. /**
  8566. * Defines the callback to call when the observer is notified
  8567. */
  8568. callback,
  8569. /**
  8570. * Defines the mask of the observer (used to filter notifications)
  8571. */
  8572. mask,
  8573. /**
  8574. * Defines the current scope used to restore the JS context
  8575. */
  8576. scope) {
  8577. if (scope === void 0) { scope = null; }
  8578. this.callback = callback;
  8579. this.mask = mask;
  8580. this.scope = scope;
  8581. /** @hidden */
  8582. this._willBeUnregistered = false;
  8583. /**
  8584. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8585. */
  8586. this.unregisterOnNextCall = false;
  8587. }
  8588. return Observer;
  8589. }());
  8590. BABYLON.Observer = Observer;
  8591. /**
  8592. * Represent a list of observers registered to multiple Observables object.
  8593. */
  8594. var MultiObserver = /** @class */ (function () {
  8595. function MultiObserver() {
  8596. }
  8597. /**
  8598. * Release associated resources
  8599. */
  8600. MultiObserver.prototype.dispose = function () {
  8601. if (this._observers && this._observables) {
  8602. for (var index = 0; index < this._observers.length; index++) {
  8603. this._observables[index].remove(this._observers[index]);
  8604. }
  8605. }
  8606. this._observers = null;
  8607. this._observables = null;
  8608. };
  8609. /**
  8610. * Raise a callback when one of the observable will notify
  8611. * @param observables defines a list of observables to watch
  8612. * @param callback defines the callback to call on notification
  8613. * @param mask defines the mask used to filter notifications
  8614. * @param scope defines the current scope used to restore the JS context
  8615. * @returns the new MultiObserver
  8616. */
  8617. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8618. if (mask === void 0) { mask = -1; }
  8619. if (scope === void 0) { scope = null; }
  8620. var result = new MultiObserver();
  8621. result._observers = new Array();
  8622. result._observables = observables;
  8623. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8624. var observable = observables_1[_i];
  8625. var observer = observable.add(callback, mask, false, scope);
  8626. if (observer) {
  8627. result._observers.push(observer);
  8628. }
  8629. }
  8630. return result;
  8631. };
  8632. return MultiObserver;
  8633. }());
  8634. BABYLON.MultiObserver = MultiObserver;
  8635. /**
  8636. * The Observable class is a simple implementation of the Observable pattern.
  8637. *
  8638. * 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.
  8639. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8640. * 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).
  8641. * 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.
  8642. */
  8643. var Observable = /** @class */ (function () {
  8644. /**
  8645. * Creates a new observable
  8646. * @param onObserverAdded defines a callback to call when a new observer is added
  8647. */
  8648. function Observable(onObserverAdded) {
  8649. this._observers = new Array();
  8650. this._eventState = new EventState(0);
  8651. if (onObserverAdded) {
  8652. this._onObserverAdded = onObserverAdded;
  8653. }
  8654. }
  8655. /**
  8656. * Create a new Observer with the specified callback
  8657. * @param callback the callback that will be executed for that Observer
  8658. * @param mask the mask used to filter observers
  8659. * @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.
  8660. * @param scope optional scope for the callback to be called from
  8661. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8662. * @returns the new observer created for the callback
  8663. */
  8664. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8665. if (mask === void 0) { mask = -1; }
  8666. if (insertFirst === void 0) { insertFirst = false; }
  8667. if (scope === void 0) { scope = null; }
  8668. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8669. if (!callback) {
  8670. return null;
  8671. }
  8672. var observer = new Observer(callback, mask, scope);
  8673. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8674. if (insertFirst) {
  8675. this._observers.unshift(observer);
  8676. }
  8677. else {
  8678. this._observers.push(observer);
  8679. }
  8680. if (this._onObserverAdded) {
  8681. this._onObserverAdded(observer);
  8682. }
  8683. return observer;
  8684. };
  8685. /**
  8686. * Create a new Observer with the specified callback and unregisters after the next notification
  8687. * @param callback the callback that will be executed for that Observer
  8688. * @returns the new observer created for the callback
  8689. */
  8690. Observable.prototype.addOnce = function (callback) {
  8691. return this.add(callback, undefined, undefined, undefined, true);
  8692. };
  8693. /**
  8694. * Remove an Observer from the Observable object
  8695. * @param observer the instance of the Observer to remove
  8696. * @returns false if it doesn't belong to this Observable
  8697. */
  8698. Observable.prototype.remove = function (observer) {
  8699. if (!observer) {
  8700. return false;
  8701. }
  8702. var index = this._observers.indexOf(observer);
  8703. if (index !== -1) {
  8704. this._deferUnregister(observer);
  8705. return true;
  8706. }
  8707. return false;
  8708. };
  8709. /**
  8710. * Remove a callback from the Observable object
  8711. * @param callback the callback to remove
  8712. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8713. * @returns false if it doesn't belong to this Observable
  8714. */
  8715. Observable.prototype.removeCallback = function (callback, scope) {
  8716. for (var index = 0; index < this._observers.length; index++) {
  8717. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8718. this._deferUnregister(this._observers[index]);
  8719. return true;
  8720. }
  8721. }
  8722. return false;
  8723. };
  8724. Observable.prototype._deferUnregister = function (observer) {
  8725. var _this = this;
  8726. observer.unregisterOnNextCall = false;
  8727. observer._willBeUnregistered = true;
  8728. BABYLON.Tools.SetImmediate(function () {
  8729. _this._remove(observer);
  8730. });
  8731. };
  8732. // This should only be called when not iterating over _observers to avoid callback skipping.
  8733. // Removes an observer from the _observer Array.
  8734. Observable.prototype._remove = function (observer) {
  8735. if (!observer) {
  8736. return false;
  8737. }
  8738. var index = this._observers.indexOf(observer);
  8739. if (index !== -1) {
  8740. this._observers.splice(index, 1);
  8741. return true;
  8742. }
  8743. return false;
  8744. };
  8745. /**
  8746. * Notify all Observers by calling their respective callback with the given data
  8747. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8748. * @param eventData defines the data to send to all observers
  8749. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8750. * @param target defines the original target of the state
  8751. * @param currentTarget defines the current target of the state
  8752. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8753. */
  8754. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8755. if (mask === void 0) { mask = -1; }
  8756. if (!this._observers.length) {
  8757. return true;
  8758. }
  8759. var state = this._eventState;
  8760. state.mask = mask;
  8761. state.target = target;
  8762. state.currentTarget = currentTarget;
  8763. state.skipNextObservers = false;
  8764. state.lastReturnValue = eventData;
  8765. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8766. var obs = _a[_i];
  8767. if (obs._willBeUnregistered) {
  8768. continue;
  8769. }
  8770. if (obs.mask & mask) {
  8771. if (obs.scope) {
  8772. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8773. }
  8774. else {
  8775. state.lastReturnValue = obs.callback(eventData, state);
  8776. }
  8777. if (obs.unregisterOnNextCall) {
  8778. this._deferUnregister(obs);
  8779. }
  8780. }
  8781. if (state.skipNextObservers) {
  8782. return false;
  8783. }
  8784. }
  8785. return true;
  8786. };
  8787. /**
  8788. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8789. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8790. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8791. * and it is crucial that all callbacks will be executed.
  8792. * The order of the callbacks is kept, callbacks are not executed parallel.
  8793. *
  8794. * @param eventData The data to be sent to each callback
  8795. * @param mask is used to filter observers defaults to -1
  8796. * @param target defines the callback target (see EventState)
  8797. * @param currentTarget defines he current object in the bubbling phase
  8798. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8799. */
  8800. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8801. var _this = this;
  8802. if (mask === void 0) { mask = -1; }
  8803. // create an empty promise
  8804. var p = Promise.resolve(eventData);
  8805. // no observers? return this promise.
  8806. if (!this._observers.length) {
  8807. return p;
  8808. }
  8809. var state = this._eventState;
  8810. state.mask = mask;
  8811. state.target = target;
  8812. state.currentTarget = currentTarget;
  8813. state.skipNextObservers = false;
  8814. // execute one callback after another (not using Promise.all, the order is important)
  8815. this._observers.forEach(function (obs) {
  8816. if (state.skipNextObservers) {
  8817. return;
  8818. }
  8819. if (obs._willBeUnregistered) {
  8820. return;
  8821. }
  8822. if (obs.mask & mask) {
  8823. if (obs.scope) {
  8824. p = p.then(function (lastReturnedValue) {
  8825. state.lastReturnValue = lastReturnedValue;
  8826. return obs.callback.apply(obs.scope, [eventData, state]);
  8827. });
  8828. }
  8829. else {
  8830. p = p.then(function (lastReturnedValue) {
  8831. state.lastReturnValue = lastReturnedValue;
  8832. return obs.callback(eventData, state);
  8833. });
  8834. }
  8835. if (obs.unregisterOnNextCall) {
  8836. _this._deferUnregister(obs);
  8837. }
  8838. }
  8839. });
  8840. // return the eventData
  8841. return p.then(function () { return eventData; });
  8842. };
  8843. /**
  8844. * Notify a specific observer
  8845. * @param observer defines the observer to notify
  8846. * @param eventData defines the data to be sent to each callback
  8847. * @param mask is used to filter observers defaults to -1
  8848. */
  8849. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8850. if (mask === void 0) { mask = -1; }
  8851. var state = this._eventState;
  8852. state.mask = mask;
  8853. state.skipNextObservers = false;
  8854. observer.callback(eventData, state);
  8855. };
  8856. /**
  8857. * Gets a boolean indicating if the observable has at least one observer
  8858. * @returns true is the Observable has at least one Observer registered
  8859. */
  8860. Observable.prototype.hasObservers = function () {
  8861. return this._observers.length > 0;
  8862. };
  8863. /**
  8864. * Clear the list of observers
  8865. */
  8866. Observable.prototype.clear = function () {
  8867. this._observers = new Array();
  8868. this._onObserverAdded = null;
  8869. };
  8870. /**
  8871. * Clone the current observable
  8872. * @returns a new observable
  8873. */
  8874. Observable.prototype.clone = function () {
  8875. var result = new Observable();
  8876. result._observers = this._observers.slice(0);
  8877. return result;
  8878. };
  8879. /**
  8880. * Does this observable handles observer registered with a given mask
  8881. * @param mask defines the mask to be tested
  8882. * @return whether or not one observer registered with the given mask is handeled
  8883. **/
  8884. Observable.prototype.hasSpecificMask = function (mask) {
  8885. if (mask === void 0) { mask = -1; }
  8886. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8887. var obs = _a[_i];
  8888. if (obs.mask & mask || obs.mask === mask) {
  8889. return true;
  8890. }
  8891. }
  8892. return false;
  8893. };
  8894. return Observable;
  8895. }());
  8896. BABYLON.Observable = Observable;
  8897. })(BABYLON || (BABYLON = {}));
  8898. //# sourceMappingURL=babylon.observable.js.map
  8899. var BABYLON;
  8900. (function (BABYLON) {
  8901. /**
  8902. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8903. */
  8904. var SmartArray = /** @class */ (function () {
  8905. /**
  8906. * Instantiates a Smart Array.
  8907. * @param capacity defines the default capacity of the array.
  8908. */
  8909. function SmartArray(capacity) {
  8910. /**
  8911. * The active length of the array.
  8912. */
  8913. this.length = 0;
  8914. this.data = new Array(capacity);
  8915. this._id = SmartArray._GlobalId++;
  8916. }
  8917. /**
  8918. * Pushes a value at the end of the active data.
  8919. * @param value defines the object to push in the array.
  8920. */
  8921. SmartArray.prototype.push = function (value) {
  8922. this.data[this.length++] = value;
  8923. if (this.length > this.data.length) {
  8924. this.data.length *= 2;
  8925. }
  8926. };
  8927. /**
  8928. * Iterates over the active data and apply the lambda to them.
  8929. * @param func defines the action to apply on each value.
  8930. */
  8931. SmartArray.prototype.forEach = function (func) {
  8932. for (var index = 0; index < this.length; index++) {
  8933. func(this.data[index]);
  8934. }
  8935. };
  8936. /**
  8937. * Sorts the full sets of data.
  8938. * @param compareFn defines the comparison function to apply.
  8939. */
  8940. SmartArray.prototype.sort = function (compareFn) {
  8941. this.data.sort(compareFn);
  8942. };
  8943. /**
  8944. * Resets the active data to an empty array.
  8945. */
  8946. SmartArray.prototype.reset = function () {
  8947. this.length = 0;
  8948. };
  8949. /**
  8950. * Releases all the data from the array as well as the array.
  8951. */
  8952. SmartArray.prototype.dispose = function () {
  8953. this.reset();
  8954. if (this.data) {
  8955. this.data.length = 0;
  8956. this.data = [];
  8957. }
  8958. };
  8959. /**
  8960. * Concats the active data with a given array.
  8961. * @param array defines the data to concatenate with.
  8962. */
  8963. SmartArray.prototype.concat = function (array) {
  8964. if (array.length === 0) {
  8965. return;
  8966. }
  8967. if (this.length + array.length > this.data.length) {
  8968. this.data.length = (this.length + array.length) * 2;
  8969. }
  8970. for (var index = 0; index < array.length; index++) {
  8971. this.data[this.length++] = (array.data || array)[index];
  8972. }
  8973. };
  8974. /**
  8975. * Returns the position of a value in the active data.
  8976. * @param value defines the value to find the index for
  8977. * @returns the index if found in the active data otherwise -1
  8978. */
  8979. SmartArray.prototype.indexOf = function (value) {
  8980. var position = this.data.indexOf(value);
  8981. if (position >= this.length) {
  8982. return -1;
  8983. }
  8984. return position;
  8985. };
  8986. /**
  8987. * Returns whether an element is part of the active data.
  8988. * @param value defines the value to look for
  8989. * @returns true if found in the active data otherwise false
  8990. */
  8991. SmartArray.prototype.contains = function (value) {
  8992. return this.indexOf(value) !== -1;
  8993. };
  8994. // Statics
  8995. SmartArray._GlobalId = 0;
  8996. return SmartArray;
  8997. }());
  8998. BABYLON.SmartArray = SmartArray;
  8999. /**
  9000. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9001. * The data in this array can only be present once
  9002. */
  9003. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9004. __extends(SmartArrayNoDuplicate, _super);
  9005. function SmartArrayNoDuplicate() {
  9006. var _this = _super !== null && _super.apply(this, arguments) || this;
  9007. _this._duplicateId = 0;
  9008. return _this;
  9009. }
  9010. /**
  9011. * Pushes a value at the end of the active data.
  9012. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9013. * @param value defines the object to push in the array.
  9014. */
  9015. SmartArrayNoDuplicate.prototype.push = function (value) {
  9016. _super.prototype.push.call(this, value);
  9017. if (!value.__smartArrayFlags) {
  9018. value.__smartArrayFlags = {};
  9019. }
  9020. value.__smartArrayFlags[this._id] = this._duplicateId;
  9021. };
  9022. /**
  9023. * Pushes a value at the end of the active data.
  9024. * If the data is already present, it won t be added again
  9025. * @param value defines the object to push in the array.
  9026. * @returns true if added false if it was already present
  9027. */
  9028. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9029. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9030. return false;
  9031. }
  9032. this.push(value);
  9033. return true;
  9034. };
  9035. /**
  9036. * Resets the active data to an empty array.
  9037. */
  9038. SmartArrayNoDuplicate.prototype.reset = function () {
  9039. _super.prototype.reset.call(this);
  9040. this._duplicateId++;
  9041. };
  9042. /**
  9043. * Concats the active data with a given array.
  9044. * This ensures no dupplicate will be present in the result.
  9045. * @param array defines the data to concatenate with.
  9046. */
  9047. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9048. if (array.length === 0) {
  9049. return;
  9050. }
  9051. if (this.length + array.length > this.data.length) {
  9052. this.data.length = (this.length + array.length) * 2;
  9053. }
  9054. for (var index = 0; index < array.length; index++) {
  9055. var item = (array.data || array)[index];
  9056. this.pushNoDuplicate(item);
  9057. }
  9058. };
  9059. return SmartArrayNoDuplicate;
  9060. }(SmartArray));
  9061. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9062. })(BABYLON || (BABYLON = {}));
  9063. //# sourceMappingURL=babylon.smartArray.js.map
  9064. var BABYLON;
  9065. (function (BABYLON) {
  9066. /** Class used to store color4 gradient */
  9067. var ColorGradient = /** @class */ (function () {
  9068. function ColorGradient() {
  9069. }
  9070. /**
  9071. * Will get a color picked randomly between color1 and color2.
  9072. * If color2 is undefined then color1 will be used
  9073. * @param result defines the target Color4 to store the result in
  9074. */
  9075. ColorGradient.prototype.getColorToRef = function (result) {
  9076. if (!this.color2) {
  9077. result.copyFrom(this.color1);
  9078. return;
  9079. }
  9080. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9081. };
  9082. return ColorGradient;
  9083. }());
  9084. BABYLON.ColorGradient = ColorGradient;
  9085. /** Class used to store color 3 gradient */
  9086. var Color3Gradient = /** @class */ (function () {
  9087. function Color3Gradient() {
  9088. }
  9089. return Color3Gradient;
  9090. }());
  9091. BABYLON.Color3Gradient = Color3Gradient;
  9092. /** Class used to store factor gradient */
  9093. var FactorGradient = /** @class */ (function () {
  9094. function FactorGradient() {
  9095. }
  9096. /**
  9097. * Will get a number picked randomly between factor1 and factor2.
  9098. * If factor2 is undefined then factor1 will be used
  9099. * @returns the picked number
  9100. */
  9101. FactorGradient.prototype.getFactor = function () {
  9102. if (this.factor2 === undefined) {
  9103. return this.factor1;
  9104. }
  9105. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9106. };
  9107. return FactorGradient;
  9108. }());
  9109. BABYLON.FactorGradient = FactorGradient;
  9110. /**
  9111. * Application error to support additional information when loading a file
  9112. */
  9113. var LoadFileError = /** @class */ (function (_super) {
  9114. __extends(LoadFileError, _super);
  9115. /**
  9116. * Creates a new LoadFileError
  9117. * @param message defines the message of the error
  9118. * @param request defines the optional XHR request
  9119. */
  9120. function LoadFileError(message, request) {
  9121. var _this = _super.call(this, message) || this;
  9122. _this.request = request;
  9123. _this.name = "LoadFileError";
  9124. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9125. return _this;
  9126. }
  9127. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9128. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9129. // Polyfill for Object.setPrototypeOf if necessary.
  9130. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9131. return LoadFileError;
  9132. }(Error));
  9133. BABYLON.LoadFileError = LoadFileError;
  9134. /**
  9135. * Class used to define a retry strategy when error happens while loading assets
  9136. */
  9137. var RetryStrategy = /** @class */ (function () {
  9138. function RetryStrategy() {
  9139. }
  9140. /**
  9141. * Function used to defines an exponential back off strategy
  9142. * @param maxRetries defines the maximum number of retries (3 by default)
  9143. * @param baseInterval defines the interval between retries
  9144. * @returns the strategy function to use
  9145. */
  9146. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9147. if (maxRetries === void 0) { maxRetries = 3; }
  9148. if (baseInterval === void 0) { baseInterval = 500; }
  9149. return function (url, request, retryIndex) {
  9150. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9151. return -1;
  9152. }
  9153. return Math.pow(2, retryIndex) * baseInterval;
  9154. };
  9155. };
  9156. return RetryStrategy;
  9157. }());
  9158. BABYLON.RetryStrategy = RetryStrategy;
  9159. // Screenshots
  9160. var screenshotCanvas;
  9161. var cloneValue = function (source, destinationObject) {
  9162. if (!source)
  9163. return null;
  9164. if (source instanceof BABYLON.Mesh) {
  9165. return null;
  9166. }
  9167. if (source instanceof BABYLON.SubMesh) {
  9168. return source.clone(destinationObject);
  9169. }
  9170. else if (source.clone) {
  9171. return source.clone();
  9172. }
  9173. return null;
  9174. };
  9175. /**
  9176. * Class containing a set of static utilities functions
  9177. */
  9178. var Tools = /** @class */ (function () {
  9179. function Tools() {
  9180. }
  9181. /**
  9182. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9183. * @param u defines the coordinate on X axis
  9184. * @param v defines the coordinate on Y axis
  9185. * @param width defines the width of the source data
  9186. * @param height defines the height of the source data
  9187. * @param pixels defines the source byte array
  9188. * @param color defines the output color
  9189. */
  9190. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9191. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9192. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9193. var position = (wrappedU + wrappedV * width) * 4;
  9194. color.r = pixels[position] / 255;
  9195. color.g = pixels[position + 1] / 255;
  9196. color.b = pixels[position + 2] / 255;
  9197. color.a = pixels[position + 3] / 255;
  9198. };
  9199. /**
  9200. * Interpolates between a and b via alpha
  9201. * @param a The lower value (returned when alpha = 0)
  9202. * @param b The upper value (returned when alpha = 1)
  9203. * @param alpha The interpolation-factor
  9204. * @return The mixed value
  9205. */
  9206. Tools.Mix = function (a, b, alpha) {
  9207. return a * (1 - alpha) + b * alpha;
  9208. };
  9209. /**
  9210. * Tries to instantiate a new object from a given class name
  9211. * @param className defines the class name to instantiate
  9212. * @returns the new object or null if the system was not able to do the instantiation
  9213. */
  9214. Tools.Instantiate = function (className) {
  9215. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9216. return Tools.RegisteredExternalClasses[className];
  9217. }
  9218. var arr = className.split(".");
  9219. var fn = (window || this);
  9220. for (var i = 0, len = arr.length; i < len; i++) {
  9221. fn = fn[arr[i]];
  9222. }
  9223. if (typeof fn !== "function") {
  9224. return null;
  9225. }
  9226. return fn;
  9227. };
  9228. /**
  9229. * Provides a slice function that will work even on IE
  9230. * @param data defines the array to slice
  9231. * @param start defines the start of the data (optional)
  9232. * @param end defines the end of the data (optional)
  9233. * @returns the new sliced array
  9234. */
  9235. Tools.Slice = function (data, start, end) {
  9236. if (data.slice) {
  9237. return data.slice(start, end);
  9238. }
  9239. return Array.prototype.slice.call(data, start, end);
  9240. };
  9241. /**
  9242. * Polyfill for setImmediate
  9243. * @param action defines the action to execute after the current execution block
  9244. */
  9245. Tools.SetImmediate = function (action) {
  9246. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9247. window.setImmediate(action);
  9248. }
  9249. else {
  9250. setTimeout(action, 1);
  9251. }
  9252. };
  9253. /**
  9254. * Function indicating if a number is an exponent of 2
  9255. * @param value defines the value to test
  9256. * @returns true if the value is an exponent of 2
  9257. */
  9258. Tools.IsExponentOfTwo = function (value) {
  9259. var count = 1;
  9260. do {
  9261. count *= 2;
  9262. } while (count < value);
  9263. return count === value;
  9264. };
  9265. /**
  9266. * Returns the nearest 32-bit single precision float representation of a Number
  9267. * @param value A Number. If the parameter is of a different type, it will get converted
  9268. * to a number or to NaN if it cannot be converted
  9269. * @returns number
  9270. */
  9271. Tools.FloatRound = function (value) {
  9272. if (Math.fround) {
  9273. return Math.fround(value);
  9274. }
  9275. return (Tools._tmpFloatArray[0] = value);
  9276. };
  9277. /**
  9278. * Find the next highest power of two.
  9279. * @param x Number to start search from.
  9280. * @return Next highest power of two.
  9281. */
  9282. Tools.CeilingPOT = function (x) {
  9283. x--;
  9284. x |= x >> 1;
  9285. x |= x >> 2;
  9286. x |= x >> 4;
  9287. x |= x >> 8;
  9288. x |= x >> 16;
  9289. x++;
  9290. return x;
  9291. };
  9292. /**
  9293. * Find the next lowest power of two.
  9294. * @param x Number to start search from.
  9295. * @return Next lowest power of two.
  9296. */
  9297. Tools.FloorPOT = function (x) {
  9298. x = x | (x >> 1);
  9299. x = x | (x >> 2);
  9300. x = x | (x >> 4);
  9301. x = x | (x >> 8);
  9302. x = x | (x >> 16);
  9303. return x - (x >> 1);
  9304. };
  9305. /**
  9306. * Find the nearest power of two.
  9307. * @param x Number to start search from.
  9308. * @return Next nearest power of two.
  9309. */
  9310. Tools.NearestPOT = function (x) {
  9311. var c = Tools.CeilingPOT(x);
  9312. var f = Tools.FloorPOT(x);
  9313. return (c - x) > (x - f) ? f : c;
  9314. };
  9315. /**
  9316. * Get the closest exponent of two
  9317. * @param value defines the value to approximate
  9318. * @param max defines the maximum value to return
  9319. * @param mode defines how to define the closest value
  9320. * @returns closest exponent of two of the given value
  9321. */
  9322. Tools.GetExponentOfTwo = function (value, max, mode) {
  9323. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9324. var pot;
  9325. switch (mode) {
  9326. case BABYLON.Engine.SCALEMODE_FLOOR:
  9327. pot = Tools.FloorPOT(value);
  9328. break;
  9329. case BABYLON.Engine.SCALEMODE_NEAREST:
  9330. pot = Tools.NearestPOT(value);
  9331. break;
  9332. case BABYLON.Engine.SCALEMODE_CEILING:
  9333. default:
  9334. pot = Tools.CeilingPOT(value);
  9335. break;
  9336. }
  9337. return Math.min(pot, max);
  9338. };
  9339. /**
  9340. * Extracts the filename from a path
  9341. * @param path defines the path to use
  9342. * @returns the filename
  9343. */
  9344. Tools.GetFilename = function (path) {
  9345. var index = path.lastIndexOf("/");
  9346. if (index < 0)
  9347. return path;
  9348. return path.substring(index + 1);
  9349. };
  9350. /**
  9351. * Extracts the "folder" part of a path (everything before the filename).
  9352. * @param uri The URI to extract the info from
  9353. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9354. * @returns The "folder" part of the path
  9355. */
  9356. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9357. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9358. var index = uri.lastIndexOf("/");
  9359. if (index < 0) {
  9360. if (returnUnchangedIfNoSlash) {
  9361. return uri;
  9362. }
  9363. return "";
  9364. }
  9365. return uri.substring(0, index + 1);
  9366. };
  9367. /**
  9368. * Extracts text content from a DOM element hierarchy
  9369. * @param element defines the root element
  9370. * @returns a string
  9371. */
  9372. Tools.GetDOMTextContent = function (element) {
  9373. var result = "";
  9374. var child = element.firstChild;
  9375. while (child) {
  9376. if (child.nodeType === 3) {
  9377. result += child.textContent;
  9378. }
  9379. child = child.nextSibling;
  9380. }
  9381. return result;
  9382. };
  9383. /**
  9384. * Convert an angle in radians to degrees
  9385. * @param angle defines the angle to convert
  9386. * @returns the angle in degrees
  9387. */
  9388. Tools.ToDegrees = function (angle) {
  9389. return angle * 180 / Math.PI;
  9390. };
  9391. /**
  9392. * Convert an angle in degrees to radians
  9393. * @param angle defines the angle to convert
  9394. * @returns the angle in radians
  9395. */
  9396. Tools.ToRadians = function (angle) {
  9397. return angle * Math.PI / 180;
  9398. };
  9399. /**
  9400. * Encode a buffer to a base64 string
  9401. * @param buffer defines the buffer to encode
  9402. * @returns the encoded string
  9403. */
  9404. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9405. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9406. var output = "";
  9407. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9408. var i = 0;
  9409. var bytes = new Uint8Array(buffer);
  9410. while (i < bytes.length) {
  9411. chr1 = bytes[i++];
  9412. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9413. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9414. enc1 = chr1 >> 2;
  9415. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9416. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9417. enc4 = chr3 & 63;
  9418. if (isNaN(chr2)) {
  9419. enc3 = enc4 = 64;
  9420. }
  9421. else if (isNaN(chr3)) {
  9422. enc4 = 64;
  9423. }
  9424. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9425. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9426. }
  9427. return "data:image/png;base64," + output;
  9428. };
  9429. /**
  9430. * Extracts minimum and maximum values from a list of indexed positions
  9431. * @param positions defines the positions to use
  9432. * @param indices defines the indices to the positions
  9433. * @param indexStart defines the start index
  9434. * @param indexCount defines the end index
  9435. * @param bias defines bias value to add to the result
  9436. * @return minimum and maximum values
  9437. */
  9438. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9439. if (bias === void 0) { bias = null; }
  9440. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9441. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9442. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9443. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9444. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9445. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9446. }
  9447. if (bias) {
  9448. minimum.x -= minimum.x * bias.x + bias.y;
  9449. minimum.y -= minimum.y * bias.x + bias.y;
  9450. minimum.z -= minimum.z * bias.x + bias.y;
  9451. maximum.x += maximum.x * bias.x + bias.y;
  9452. maximum.y += maximum.y * bias.x + bias.y;
  9453. maximum.z += maximum.z * bias.x + bias.y;
  9454. }
  9455. return {
  9456. minimum: minimum,
  9457. maximum: maximum
  9458. };
  9459. };
  9460. /**
  9461. * Extracts minimum and maximum values from a list of positions
  9462. * @param positions defines the positions to use
  9463. * @param start defines the start index in the positions array
  9464. * @param count defines the number of positions to handle
  9465. * @param bias defines bias value to add to the result
  9466. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9467. * @return minimum and maximum values
  9468. */
  9469. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9470. if (bias === void 0) { bias = null; }
  9471. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9472. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9473. if (!stride) {
  9474. stride = 3;
  9475. }
  9476. for (var index = start; index < start + count; index++) {
  9477. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9478. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9479. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9480. }
  9481. if (bias) {
  9482. minimum.x -= minimum.x * bias.x + bias.y;
  9483. minimum.y -= minimum.y * bias.x + bias.y;
  9484. minimum.z -= minimum.z * bias.x + bias.y;
  9485. maximum.x += maximum.x * bias.x + bias.y;
  9486. maximum.y += maximum.y * bias.x + bias.y;
  9487. maximum.z += maximum.z * bias.x + bias.y;
  9488. }
  9489. return {
  9490. minimum: minimum,
  9491. maximum: maximum
  9492. };
  9493. };
  9494. /**
  9495. * Returns an array if obj is not an array
  9496. * @param obj defines the object to evaluate as an array
  9497. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9498. * @returns either obj directly if obj is an array or a new array containing obj
  9499. */
  9500. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9501. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9502. return null;
  9503. return Array.isArray(obj) ? obj : [obj];
  9504. };
  9505. /**
  9506. * Gets the pointer prefix to use
  9507. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9508. */
  9509. Tools.GetPointerPrefix = function () {
  9510. var eventPrefix = "pointer";
  9511. // Check if pointer events are supported
  9512. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9513. eventPrefix = "mouse";
  9514. }
  9515. return eventPrefix;
  9516. };
  9517. /**
  9518. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9519. * @param func - the function to be called
  9520. * @param requester - the object that will request the next frame. Falls back to window.
  9521. * @returns frame number
  9522. */
  9523. Tools.QueueNewFrame = function (func, requester) {
  9524. if (!Tools.IsWindowObjectExist()) {
  9525. return setTimeout(func, 16);
  9526. }
  9527. if (!requester) {
  9528. requester = window;
  9529. }
  9530. if (requester.requestAnimationFrame) {
  9531. return requester.requestAnimationFrame(func);
  9532. }
  9533. else if (requester.msRequestAnimationFrame) {
  9534. return requester.msRequestAnimationFrame(func);
  9535. }
  9536. else if (requester.webkitRequestAnimationFrame) {
  9537. return requester.webkitRequestAnimationFrame(func);
  9538. }
  9539. else if (requester.mozRequestAnimationFrame) {
  9540. return requester.mozRequestAnimationFrame(func);
  9541. }
  9542. else if (requester.oRequestAnimationFrame) {
  9543. return requester.oRequestAnimationFrame(func);
  9544. }
  9545. else {
  9546. return window.setTimeout(func, 16);
  9547. }
  9548. };
  9549. /**
  9550. * Ask the browser to promote the current element to fullscreen rendering mode
  9551. * @param element defines the DOM element to promote
  9552. */
  9553. Tools.RequestFullscreen = function (element) {
  9554. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9555. if (!requestFunction)
  9556. return;
  9557. requestFunction.call(element);
  9558. };
  9559. /**
  9560. * Asks the browser to exit fullscreen mode
  9561. */
  9562. Tools.ExitFullscreen = function () {
  9563. if (document.exitFullscreen) {
  9564. document.exitFullscreen();
  9565. }
  9566. else if (document.mozCancelFullScreen) {
  9567. document.mozCancelFullScreen();
  9568. }
  9569. else if (document.webkitCancelFullScreen) {
  9570. document.webkitCancelFullScreen();
  9571. }
  9572. else if (document.msCancelFullScreen) {
  9573. document.msCancelFullScreen();
  9574. }
  9575. };
  9576. /**
  9577. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9578. * @param url define the url we are trying
  9579. * @param element define the dom element where to configure the cors policy
  9580. */
  9581. Tools.SetCorsBehavior = function (url, element) {
  9582. if (url && url.indexOf("data:") === 0) {
  9583. return;
  9584. }
  9585. if (Tools.CorsBehavior) {
  9586. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9587. element.crossOrigin = Tools.CorsBehavior;
  9588. }
  9589. else {
  9590. var result = Tools.CorsBehavior(url);
  9591. if (result) {
  9592. element.crossOrigin = result;
  9593. }
  9594. }
  9595. }
  9596. };
  9597. // External files
  9598. /**
  9599. * Removes unwanted characters from an url
  9600. * @param url defines the url to clean
  9601. * @returns the cleaned url
  9602. */
  9603. Tools.CleanUrl = function (url) {
  9604. url = url.replace(/#/mg, "%23");
  9605. return url;
  9606. };
  9607. /**
  9608. * Loads an image as an HTMLImageElement.
  9609. * @param input url string, ArrayBuffer, or Blob to load
  9610. * @param onLoad callback called when the image successfully loads
  9611. * @param onError callback called when the image fails to load
  9612. * @param database database for caching
  9613. * @returns the HTMLImageElement of the loaded image
  9614. */
  9615. Tools.LoadImage = function (input, onLoad, onError, database) {
  9616. var url;
  9617. var usingObjectURL = false;
  9618. if (input instanceof ArrayBuffer) {
  9619. url = URL.createObjectURL(new Blob([input]));
  9620. usingObjectURL = true;
  9621. }
  9622. else if (input instanceof Blob) {
  9623. url = URL.createObjectURL(input);
  9624. usingObjectURL = true;
  9625. }
  9626. else {
  9627. url = Tools.CleanUrl(input);
  9628. url = Tools.PreprocessUrl(input);
  9629. }
  9630. var img = new Image();
  9631. Tools.SetCorsBehavior(url, img);
  9632. var loadHandler = function () {
  9633. if (usingObjectURL && img.src) {
  9634. URL.revokeObjectURL(img.src);
  9635. }
  9636. img.removeEventListener("load", loadHandler);
  9637. img.removeEventListener("error", errorHandler);
  9638. onLoad(img);
  9639. };
  9640. var errorHandler = function (err) {
  9641. if (usingObjectURL && img.src) {
  9642. URL.revokeObjectURL(img.src);
  9643. }
  9644. img.removeEventListener("load", loadHandler);
  9645. img.removeEventListener("error", errorHandler);
  9646. Tools.Error("Error while trying to load image: " + input);
  9647. if (onError) {
  9648. onError("Error while trying to load image: " + input, err);
  9649. }
  9650. };
  9651. img.addEventListener("load", loadHandler);
  9652. img.addEventListener("error", errorHandler);
  9653. var noIndexedDB = function () {
  9654. img.src = url;
  9655. };
  9656. var loadFromIndexedDB = function () {
  9657. if (database) {
  9658. database.loadImageFromDB(url, img);
  9659. }
  9660. };
  9661. //ANY database to do!
  9662. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9663. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9664. }
  9665. else {
  9666. if (url.indexOf("file:") !== -1) {
  9667. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9668. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9669. try {
  9670. var blobURL;
  9671. try {
  9672. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9673. }
  9674. catch (ex) {
  9675. // Chrome doesn't support oneTimeOnly parameter
  9676. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9677. }
  9678. img.src = blobURL;
  9679. usingObjectURL = true;
  9680. }
  9681. catch (e) {
  9682. img.src = "";
  9683. }
  9684. return img;
  9685. }
  9686. }
  9687. noIndexedDB();
  9688. }
  9689. return img;
  9690. };
  9691. /**
  9692. * Loads a file
  9693. * @param url url string, ArrayBuffer, or Blob to load
  9694. * @param onSuccess callback called when the file successfully loads
  9695. * @param onProgress callback called while file is loading (if the server supports this mode)
  9696. * @param database database for caching
  9697. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9698. * @param onError callback called when the file fails to load
  9699. * @returns a file request object
  9700. */
  9701. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9702. url = Tools.CleanUrl(url);
  9703. url = Tools.PreprocessUrl(url);
  9704. // If file and file input are set
  9705. if (url.indexOf("file:") !== -1) {
  9706. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9707. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9708. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9709. }
  9710. }
  9711. var loadUrl = Tools.BaseUrl + url;
  9712. var aborted = false;
  9713. var fileRequest = {
  9714. onCompleteObservable: new BABYLON.Observable(),
  9715. abort: function () { return aborted = true; },
  9716. };
  9717. var requestFile = function () {
  9718. var request = new XMLHttpRequest();
  9719. var retryHandle = null;
  9720. fileRequest.abort = function () {
  9721. aborted = true;
  9722. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9723. request.abort();
  9724. }
  9725. if (retryHandle !== null) {
  9726. clearTimeout(retryHandle);
  9727. retryHandle = null;
  9728. }
  9729. };
  9730. var retryLoop = function (retryIndex) {
  9731. request.open('GET', loadUrl, true);
  9732. if (useArrayBuffer) {
  9733. request.responseType = "arraybuffer";
  9734. }
  9735. if (onProgress) {
  9736. request.addEventListener("progress", onProgress);
  9737. }
  9738. var onLoadEnd = function () {
  9739. request.removeEventListener("loadend", onLoadEnd);
  9740. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9741. fileRequest.onCompleteObservable.clear();
  9742. };
  9743. request.addEventListener("loadend", onLoadEnd);
  9744. var onReadyStateChange = function () {
  9745. if (aborted) {
  9746. return;
  9747. }
  9748. // In case of undefined state in some browsers.
  9749. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9750. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9751. request.removeEventListener("readystatechange", onReadyStateChange);
  9752. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9753. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9754. return;
  9755. }
  9756. var retryStrategy = Tools.DefaultRetryStrategy;
  9757. if (retryStrategy) {
  9758. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9759. if (waitTime !== -1) {
  9760. // Prevent the request from completing for retry.
  9761. request.removeEventListener("loadend", onLoadEnd);
  9762. request = new XMLHttpRequest();
  9763. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9764. return;
  9765. }
  9766. }
  9767. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9768. if (onError) {
  9769. onError(request, e);
  9770. }
  9771. else {
  9772. throw e;
  9773. }
  9774. }
  9775. };
  9776. request.addEventListener("readystatechange", onReadyStateChange);
  9777. request.send();
  9778. };
  9779. retryLoop(0);
  9780. };
  9781. // Caching all files
  9782. if (database && database.enableSceneOffline) {
  9783. var noIndexedDB_1 = function (request) {
  9784. if (request && request.status > 400) {
  9785. if (onError) {
  9786. onError(request);
  9787. }
  9788. }
  9789. else {
  9790. if (!aborted) {
  9791. requestFile();
  9792. }
  9793. }
  9794. };
  9795. var loadFromIndexedDB = function () {
  9796. // TODO: database needs to support aborting and should return a IFileRequest
  9797. if (aborted) {
  9798. return;
  9799. }
  9800. if (database) {
  9801. database.loadFileFromDB(url, function (data) {
  9802. if (!aborted) {
  9803. onSuccess(data);
  9804. }
  9805. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9806. }, onProgress ? function (event) {
  9807. if (!aborted) {
  9808. onProgress(event);
  9809. }
  9810. } : undefined, noIndexedDB_1, useArrayBuffer);
  9811. }
  9812. };
  9813. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9814. }
  9815. else {
  9816. requestFile();
  9817. }
  9818. return fileRequest;
  9819. };
  9820. /**
  9821. * Load a script (identified by an url). When the url returns, the
  9822. * content of this file is added into a new script element, attached to the DOM (body element)
  9823. * @param scriptUrl defines the url of the script to laod
  9824. * @param onSuccess defines the callback called when the script is loaded
  9825. * @param onError defines the callback to call if an error occurs
  9826. */
  9827. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9828. if (!Tools.IsWindowObjectExist()) {
  9829. return;
  9830. }
  9831. var head = document.getElementsByTagName('head')[0];
  9832. var script = document.createElement('script');
  9833. script.type = 'text/javascript';
  9834. script.src = scriptUrl;
  9835. script.onload = function () {
  9836. if (onSuccess) {
  9837. onSuccess();
  9838. }
  9839. };
  9840. script.onerror = function (e) {
  9841. if (onError) {
  9842. onError("Unable to load script '" + scriptUrl + "'", e);
  9843. }
  9844. };
  9845. head.appendChild(script);
  9846. };
  9847. /**
  9848. * Loads a file from a blob
  9849. * @param fileToLoad defines the blob to use
  9850. * @param callback defines the callback to call when data is loaded
  9851. * @param progressCallback defines the callback to call during loading process
  9852. * @returns a file request object
  9853. */
  9854. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9855. var reader = new FileReader();
  9856. var request = {
  9857. onCompleteObservable: new BABYLON.Observable(),
  9858. abort: function () { return reader.abort(); },
  9859. };
  9860. reader.onloadend = function (e) {
  9861. request.onCompleteObservable.notifyObservers(request);
  9862. };
  9863. reader.onload = function (e) {
  9864. //target doesn't have result from ts 1.3
  9865. callback(e.target['result']);
  9866. };
  9867. reader.onprogress = progressCallback;
  9868. reader.readAsDataURL(fileToLoad);
  9869. return request;
  9870. };
  9871. /**
  9872. * Loads a file
  9873. * @param fileToLoad defines the file to load
  9874. * @param callback defines the callback to call when data is loaded
  9875. * @param progressCallBack defines the callback to call during loading process
  9876. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9877. * @returns a file request object
  9878. */
  9879. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9880. var reader = new FileReader();
  9881. var request = {
  9882. onCompleteObservable: new BABYLON.Observable(),
  9883. abort: function () { return reader.abort(); },
  9884. };
  9885. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9886. reader.onerror = function (e) {
  9887. Tools.Log("Error while reading file: " + fileToLoad.name);
  9888. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9889. };
  9890. reader.onload = function (e) {
  9891. //target doesn't have result from ts 1.3
  9892. callback(e.target['result']);
  9893. };
  9894. if (progressCallBack) {
  9895. reader.onprogress = progressCallBack;
  9896. }
  9897. if (!useArrayBuffer) {
  9898. // Asynchronous read
  9899. reader.readAsText(fileToLoad);
  9900. }
  9901. else {
  9902. reader.readAsArrayBuffer(fileToLoad);
  9903. }
  9904. return request;
  9905. };
  9906. /**
  9907. * Creates a data url from a given string content
  9908. * @param content defines the content to convert
  9909. * @returns the new data url link
  9910. */
  9911. Tools.FileAsURL = function (content) {
  9912. var fileBlob = new Blob([content]);
  9913. var url = window.URL || window.webkitURL;
  9914. var link = url.createObjectURL(fileBlob);
  9915. return link;
  9916. };
  9917. /**
  9918. * Format the given number to a specific decimal format
  9919. * @param value defines the number to format
  9920. * @param decimals defines the number of decimals to use
  9921. * @returns the formatted string
  9922. */
  9923. Tools.Format = function (value, decimals) {
  9924. if (decimals === void 0) { decimals = 2; }
  9925. return value.toFixed(decimals);
  9926. };
  9927. /**
  9928. * Checks if a given vector is inside a specific range
  9929. * @param v defines the vector to test
  9930. * @param min defines the minimum range
  9931. * @param max defines the maximum range
  9932. */
  9933. Tools.CheckExtends = function (v, min, max) {
  9934. if (v.x < min.x)
  9935. min.x = v.x;
  9936. if (v.y < min.y)
  9937. min.y = v.y;
  9938. if (v.z < min.z)
  9939. min.z = v.z;
  9940. if (v.x > max.x)
  9941. max.x = v.x;
  9942. if (v.y > max.y)
  9943. max.y = v.y;
  9944. if (v.z > max.z)
  9945. max.z = v.z;
  9946. };
  9947. /**
  9948. * Tries to copy an object by duplicating every property
  9949. * @param source defines the source object
  9950. * @param destination defines the target object
  9951. * @param doNotCopyList defines a list of properties to avoid
  9952. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9953. */
  9954. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9955. for (var prop in source) {
  9956. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9957. continue;
  9958. }
  9959. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9960. continue;
  9961. }
  9962. var sourceValue = source[prop];
  9963. var typeOfSourceValue = typeof sourceValue;
  9964. if (typeOfSourceValue === "function") {
  9965. continue;
  9966. }
  9967. try {
  9968. if (typeOfSourceValue === "object") {
  9969. if (sourceValue instanceof Array) {
  9970. destination[prop] = [];
  9971. if (sourceValue.length > 0) {
  9972. if (typeof sourceValue[0] == "object") {
  9973. for (var index = 0; index < sourceValue.length; index++) {
  9974. var clonedValue = cloneValue(sourceValue[index], destination);
  9975. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9976. destination[prop].push(clonedValue);
  9977. }
  9978. }
  9979. }
  9980. else {
  9981. destination[prop] = sourceValue.slice(0);
  9982. }
  9983. }
  9984. }
  9985. else {
  9986. destination[prop] = cloneValue(sourceValue, destination);
  9987. }
  9988. }
  9989. else {
  9990. destination[prop] = sourceValue;
  9991. }
  9992. }
  9993. catch (e) {
  9994. // Just ignore error (it could be because of a read-only property)
  9995. }
  9996. }
  9997. };
  9998. /**
  9999. * Gets a boolean indicating if the given object has no own property
  10000. * @param obj defines the object to test
  10001. * @returns true if object has no own property
  10002. */
  10003. Tools.IsEmpty = function (obj) {
  10004. for (var i in obj) {
  10005. if (obj.hasOwnProperty(i)) {
  10006. return false;
  10007. }
  10008. }
  10009. return true;
  10010. };
  10011. /**
  10012. * Function used to register events at window level
  10013. * @param events defines the events to register
  10014. */
  10015. Tools.RegisterTopRootEvents = function (events) {
  10016. for (var index = 0; index < events.length; index++) {
  10017. var event = events[index];
  10018. window.addEventListener(event.name, event.handler, false);
  10019. try {
  10020. if (window.parent) {
  10021. window.parent.addEventListener(event.name, event.handler, false);
  10022. }
  10023. }
  10024. catch (e) {
  10025. // Silently fails...
  10026. }
  10027. }
  10028. };
  10029. /**
  10030. * Function used to unregister events from window level
  10031. * @param events defines the events to unregister
  10032. */
  10033. Tools.UnregisterTopRootEvents = function (events) {
  10034. for (var index = 0; index < events.length; index++) {
  10035. var event = events[index];
  10036. window.removeEventListener(event.name, event.handler);
  10037. try {
  10038. if (window.parent) {
  10039. window.parent.removeEventListener(event.name, event.handler);
  10040. }
  10041. }
  10042. catch (e) {
  10043. // Silently fails...
  10044. }
  10045. }
  10046. };
  10047. /**
  10048. * Dumps the current bound framebuffer
  10049. * @param width defines the rendering width
  10050. * @param height defines the rendering height
  10051. * @param engine defines the hosting engine
  10052. * @param successCallback defines the callback triggered once the data are available
  10053. * @param mimeType defines the mime type of the result
  10054. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10055. */
  10056. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10057. if (mimeType === void 0) { mimeType = "image/png"; }
  10058. // Read the contents of the framebuffer
  10059. var numberOfChannelsByLine = width * 4;
  10060. var halfHeight = height / 2;
  10061. //Reading datas from WebGL
  10062. var data = engine.readPixels(0, 0, width, height);
  10063. //To flip image on Y axis.
  10064. for (var i = 0; i < halfHeight; i++) {
  10065. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10066. var currentCell = j + i * numberOfChannelsByLine;
  10067. var targetLine = height - i - 1;
  10068. var targetCell = j + targetLine * numberOfChannelsByLine;
  10069. var temp = data[currentCell];
  10070. data[currentCell] = data[targetCell];
  10071. data[targetCell] = temp;
  10072. }
  10073. }
  10074. // Create a 2D canvas to store the result
  10075. if (!screenshotCanvas) {
  10076. screenshotCanvas = document.createElement('canvas');
  10077. }
  10078. screenshotCanvas.width = width;
  10079. screenshotCanvas.height = height;
  10080. var context = screenshotCanvas.getContext('2d');
  10081. if (context) {
  10082. // Copy the pixels to a 2D canvas
  10083. var imageData = context.createImageData(width, height);
  10084. var castData = (imageData.data);
  10085. castData.set(data);
  10086. context.putImageData(imageData, 0, 0);
  10087. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10088. }
  10089. };
  10090. /**
  10091. * Converts the canvas data to blob.
  10092. * This acts as a polyfill for browsers not supporting the to blob function.
  10093. * @param canvas Defines the canvas to extract the data from
  10094. * @param successCallback Defines the callback triggered once the data are available
  10095. * @param mimeType Defines the mime type of the result
  10096. */
  10097. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10098. if (mimeType === void 0) { mimeType = "image/png"; }
  10099. // We need HTMLCanvasElement.toBlob for HD screenshots
  10100. if (!canvas.toBlob) {
  10101. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10102. canvas.toBlob = function (callback, type, quality) {
  10103. var _this = this;
  10104. setTimeout(function () {
  10105. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10106. for (var i = 0; i < len; i++) {
  10107. arr[i] = binStr.charCodeAt(i);
  10108. }
  10109. callback(new Blob([arr]));
  10110. });
  10111. };
  10112. }
  10113. canvas.toBlob(function (blob) {
  10114. successCallback(blob);
  10115. }, mimeType);
  10116. };
  10117. /**
  10118. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10119. * @param successCallback defines the callback triggered once the data are available
  10120. * @param mimeType defines the mime type of the result
  10121. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10122. */
  10123. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10124. if (mimeType === void 0) { mimeType = "image/png"; }
  10125. if (successCallback) {
  10126. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10127. successCallback(base64Image);
  10128. }
  10129. else {
  10130. this.ToBlob(screenshotCanvas, function (blob) {
  10131. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10132. if (("download" in document.createElement("a"))) {
  10133. if (!fileName) {
  10134. var date = new Date();
  10135. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10136. fileName = "screenshot_" + stringDate + ".png";
  10137. }
  10138. Tools.Download(blob, fileName);
  10139. }
  10140. else {
  10141. var url = URL.createObjectURL(blob);
  10142. var newWindow = window.open("");
  10143. if (!newWindow)
  10144. return;
  10145. var img = newWindow.document.createElement("img");
  10146. img.onload = function () {
  10147. // no longer need to read the blob so it's revoked
  10148. URL.revokeObjectURL(url);
  10149. };
  10150. img.src = url;
  10151. newWindow.document.body.appendChild(img);
  10152. }
  10153. }, mimeType);
  10154. }
  10155. };
  10156. /**
  10157. * Downloads a blob in the browser
  10158. * @param blob defines the blob to download
  10159. * @param fileName defines the name of the downloaded file
  10160. */
  10161. Tools.Download = function (blob, fileName) {
  10162. if (navigator && navigator.msSaveBlob) {
  10163. navigator.msSaveBlob(blob, fileName);
  10164. return;
  10165. }
  10166. var url = window.URL.createObjectURL(blob);
  10167. var a = document.createElement("a");
  10168. document.body.appendChild(a);
  10169. a.style.display = "none";
  10170. a.href = url;
  10171. a.download = fileName;
  10172. a.addEventListener("click", function () {
  10173. if (a.parentElement) {
  10174. a.parentElement.removeChild(a);
  10175. }
  10176. });
  10177. a.click();
  10178. window.URL.revokeObjectURL(url);
  10179. };
  10180. /**
  10181. * Captures a screenshot of the current rendering
  10182. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10183. * @param engine defines the rendering engine
  10184. * @param camera defines the source camera
  10185. * @param size This parameter can be set to a single number or to an object with the
  10186. * following (optional) properties: precision, width, height. If a single number is passed,
  10187. * it will be used for both width and height. If an object is passed, the screenshot size
  10188. * will be derived from the parameters. The precision property is a multiplier allowing
  10189. * rendering at a higher or lower resolution
  10190. * @param successCallback defines the callback receives a single parameter which contains the
  10191. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10192. * src parameter of an <img> to display it
  10193. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10194. * Check your browser for supported MIME types
  10195. */
  10196. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10197. if (mimeType === void 0) { mimeType = "image/png"; }
  10198. var width;
  10199. var height;
  10200. // If a precision value is specified
  10201. if (size.precision) {
  10202. width = Math.round(engine.getRenderWidth() * size.precision);
  10203. height = Math.round(width / engine.getAspectRatio(camera));
  10204. }
  10205. else if (size.width && size.height) {
  10206. width = size.width;
  10207. height = size.height;
  10208. }
  10209. //If passing only width, computing height to keep display canvas ratio.
  10210. else if (size.width && !size.height) {
  10211. width = size.width;
  10212. height = Math.round(width / engine.getAspectRatio(camera));
  10213. }
  10214. //If passing only height, computing width to keep display canvas ratio.
  10215. else if (size.height && !size.width) {
  10216. height = size.height;
  10217. width = Math.round(height * engine.getAspectRatio(camera));
  10218. }
  10219. //Assuming here that "size" parameter is a number
  10220. else if (!isNaN(size)) {
  10221. height = size;
  10222. width = size;
  10223. }
  10224. else {
  10225. Tools.Error("Invalid 'size' parameter !");
  10226. return;
  10227. }
  10228. if (!screenshotCanvas) {
  10229. screenshotCanvas = document.createElement('canvas');
  10230. }
  10231. screenshotCanvas.width = width;
  10232. screenshotCanvas.height = height;
  10233. var renderContext = screenshotCanvas.getContext("2d");
  10234. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10235. var newWidth = width;
  10236. var newHeight = newWidth / ratio;
  10237. if (newHeight > height) {
  10238. newHeight = height;
  10239. newWidth = newHeight * ratio;
  10240. }
  10241. var offsetX = Math.max(0, width - newWidth) / 2;
  10242. var offsetY = Math.max(0, height - newHeight) / 2;
  10243. var renderingCanvas = engine.getRenderingCanvas();
  10244. if (renderContext && renderingCanvas) {
  10245. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10246. }
  10247. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10248. };
  10249. /**
  10250. * Generates an image screenshot from the specified camera.
  10251. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10252. * @param engine The engine to use for rendering
  10253. * @param camera The camera to use for rendering
  10254. * @param size This parameter can be set to a single number or to an object with the
  10255. * following (optional) properties: precision, width, height. If a single number is passed,
  10256. * it will be used for both width and height. If an object is passed, the screenshot size
  10257. * will be derived from the parameters. The precision property is a multiplier allowing
  10258. * rendering at a higher or lower resolution
  10259. * @param successCallback The callback receives a single parameter which contains the
  10260. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10261. * src parameter of an <img> to display it
  10262. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10263. * Check your browser for supported MIME types
  10264. * @param samples Texture samples (default: 1)
  10265. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10266. * @param fileName A name for for the downloaded file.
  10267. */
  10268. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10269. if (mimeType === void 0) { mimeType = "image/png"; }
  10270. if (samples === void 0) { samples = 1; }
  10271. if (antialiasing === void 0) { antialiasing = false; }
  10272. var width;
  10273. var height;
  10274. //If a precision value is specified
  10275. if (size.precision) {
  10276. width = Math.round(engine.getRenderWidth() * size.precision);
  10277. height = Math.round(width / engine.getAspectRatio(camera));
  10278. size = { width: width, height: height };
  10279. }
  10280. else if (size.width && size.height) {
  10281. width = size.width;
  10282. height = size.height;
  10283. }
  10284. //If passing only width, computing height to keep display canvas ratio.
  10285. else if (size.width && !size.height) {
  10286. width = size.width;
  10287. height = Math.round(width / engine.getAspectRatio(camera));
  10288. size = { width: width, height: height };
  10289. }
  10290. //If passing only height, computing width to keep display canvas ratio.
  10291. else if (size.height && !size.width) {
  10292. height = size.height;
  10293. width = Math.round(height * engine.getAspectRatio(camera));
  10294. size = { width: width, height: height };
  10295. }
  10296. //Assuming here that "size" parameter is a number
  10297. else if (!isNaN(size)) {
  10298. height = size;
  10299. width = size;
  10300. }
  10301. else {
  10302. Tools.Error("Invalid 'size' parameter !");
  10303. return;
  10304. }
  10305. var scene = camera.getScene();
  10306. var previousCamera = null;
  10307. if (scene.activeCamera !== camera) {
  10308. previousCamera = scene.activeCamera;
  10309. scene.activeCamera = camera;
  10310. }
  10311. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10312. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10313. texture.renderList = null;
  10314. texture.samples = samples;
  10315. if (antialiasing) {
  10316. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10317. }
  10318. texture.onAfterRenderObservable.add(function () {
  10319. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10320. });
  10321. scene.incrementRenderId();
  10322. scene.resetCachedMaterial();
  10323. texture.render(true);
  10324. texture.dispose();
  10325. if (previousCamera) {
  10326. scene.activeCamera = previousCamera;
  10327. }
  10328. camera.getProjectionMatrix(true); // Force cache refresh;
  10329. };
  10330. /**
  10331. * Validates if xhr data is correct
  10332. * @param xhr defines the request to validate
  10333. * @param dataType defines the expected data type
  10334. * @returns true if data is correct
  10335. */
  10336. Tools.ValidateXHRData = function (xhr, dataType) {
  10337. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10338. if (dataType === void 0) { dataType = 7; }
  10339. try {
  10340. if (dataType & 1) {
  10341. if (xhr.responseText && xhr.responseText.length > 0) {
  10342. return true;
  10343. }
  10344. else if (dataType === 1) {
  10345. return false;
  10346. }
  10347. }
  10348. if (dataType & 2) {
  10349. // Check header width and height since there is no "TGA" magic number
  10350. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10351. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10352. return true;
  10353. }
  10354. else if (dataType === 2) {
  10355. return false;
  10356. }
  10357. }
  10358. if (dataType & 4) {
  10359. // Check for the "DDS" magic number
  10360. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10361. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10362. return true;
  10363. }
  10364. else {
  10365. return false;
  10366. }
  10367. }
  10368. }
  10369. catch (e) {
  10370. // Global protection
  10371. }
  10372. return false;
  10373. };
  10374. /**
  10375. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10376. * Be aware Math.random() could cause collisions, but:
  10377. * "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"
  10378. * @returns a pseudo random id
  10379. */
  10380. Tools.RandomId = function () {
  10381. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10382. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10383. return v.toString(16);
  10384. });
  10385. };
  10386. /**
  10387. * Test if the given uri is a base64 string
  10388. * @param uri The uri to test
  10389. * @return True if the uri is a base64 string or false otherwise
  10390. */
  10391. Tools.IsBase64 = function (uri) {
  10392. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10393. };
  10394. /**
  10395. * Decode the given base64 uri.
  10396. * @param uri The uri to decode
  10397. * @return The decoded base64 data.
  10398. */
  10399. Tools.DecodeBase64 = function (uri) {
  10400. var decodedString = atob(uri.split(",")[1]);
  10401. var bufferLength = decodedString.length;
  10402. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10403. for (var i = 0; i < bufferLength; i++) {
  10404. bufferView[i] = decodedString.charCodeAt(i);
  10405. }
  10406. return bufferView.buffer;
  10407. };
  10408. Tools._AddLogEntry = function (entry) {
  10409. Tools._LogCache = entry + Tools._LogCache;
  10410. if (Tools.OnNewCacheEntry) {
  10411. Tools.OnNewCacheEntry(entry);
  10412. }
  10413. };
  10414. Tools._FormatMessage = function (message) {
  10415. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10416. var date = new Date();
  10417. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10418. };
  10419. Tools._LogDisabled = function (message) {
  10420. // nothing to do
  10421. };
  10422. Tools._LogEnabled = function (message) {
  10423. var formattedMessage = Tools._FormatMessage(message);
  10424. console.log("BJS - " + formattedMessage);
  10425. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10426. Tools._AddLogEntry(entry);
  10427. };
  10428. Tools._WarnDisabled = function (message) {
  10429. // nothing to do
  10430. };
  10431. Tools._WarnEnabled = function (message) {
  10432. var formattedMessage = Tools._FormatMessage(message);
  10433. console.warn("BJS - " + formattedMessage);
  10434. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10435. Tools._AddLogEntry(entry);
  10436. };
  10437. Tools._ErrorDisabled = function (message) {
  10438. // nothing to do
  10439. };
  10440. Tools._ErrorEnabled = function (message) {
  10441. Tools.errorsCount++;
  10442. var formattedMessage = Tools._FormatMessage(message);
  10443. console.error("BJS - " + formattedMessage);
  10444. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10445. Tools._AddLogEntry(entry);
  10446. };
  10447. Object.defineProperty(Tools, "LogCache", {
  10448. /**
  10449. * Gets current log cache (list of logs)
  10450. */
  10451. get: function () {
  10452. return Tools._LogCache;
  10453. },
  10454. enumerable: true,
  10455. configurable: true
  10456. });
  10457. /**
  10458. * Clears the log cache
  10459. */
  10460. Tools.ClearLogCache = function () {
  10461. Tools._LogCache = "";
  10462. Tools.errorsCount = 0;
  10463. };
  10464. Object.defineProperty(Tools, "LogLevels", {
  10465. /**
  10466. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10467. */
  10468. set: function (level) {
  10469. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10470. Tools.Log = Tools._LogEnabled;
  10471. }
  10472. else {
  10473. Tools.Log = Tools._LogDisabled;
  10474. }
  10475. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10476. Tools.Warn = Tools._WarnEnabled;
  10477. }
  10478. else {
  10479. Tools.Warn = Tools._WarnDisabled;
  10480. }
  10481. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10482. Tools.Error = Tools._ErrorEnabled;
  10483. }
  10484. else {
  10485. Tools.Error = Tools._ErrorDisabled;
  10486. }
  10487. },
  10488. enumerable: true,
  10489. configurable: true
  10490. });
  10491. /**
  10492. * Checks if the loaded document was accessed via `file:`-Protocol.
  10493. * @returns boolean
  10494. */
  10495. Tools.IsFileURL = function () {
  10496. return location.protocol === "file:";
  10497. };
  10498. /**
  10499. * Checks if the window object exists
  10500. * @returns true if the window object exists
  10501. */
  10502. Tools.IsWindowObjectExist = function () {
  10503. return (typeof window) !== "undefined";
  10504. };
  10505. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10506. /**
  10507. * Sets the current performance log level
  10508. */
  10509. set: function (level) {
  10510. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10511. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10512. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10513. return;
  10514. }
  10515. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10516. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10517. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10518. return;
  10519. }
  10520. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10521. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10522. },
  10523. enumerable: true,
  10524. configurable: true
  10525. });
  10526. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10527. };
  10528. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10529. };
  10530. Tools._StartUserMark = function (counterName, condition) {
  10531. if (condition === void 0) { condition = true; }
  10532. if (!Tools._performance) {
  10533. if (!Tools.IsWindowObjectExist()) {
  10534. return;
  10535. }
  10536. Tools._performance = window.performance;
  10537. }
  10538. if (!condition || !Tools._performance.mark) {
  10539. return;
  10540. }
  10541. Tools._performance.mark(counterName + "-Begin");
  10542. };
  10543. Tools._EndUserMark = function (counterName, condition) {
  10544. if (condition === void 0) { condition = true; }
  10545. if (!condition || !Tools._performance.mark) {
  10546. return;
  10547. }
  10548. Tools._performance.mark(counterName + "-End");
  10549. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10550. };
  10551. Tools._StartPerformanceConsole = function (counterName, condition) {
  10552. if (condition === void 0) { condition = true; }
  10553. if (!condition) {
  10554. return;
  10555. }
  10556. Tools._StartUserMark(counterName, condition);
  10557. if (console.time) {
  10558. console.time(counterName);
  10559. }
  10560. };
  10561. Tools._EndPerformanceConsole = function (counterName, condition) {
  10562. if (condition === void 0) { condition = true; }
  10563. if (!condition) {
  10564. return;
  10565. }
  10566. Tools._EndUserMark(counterName, condition);
  10567. if (console.time) {
  10568. console.timeEnd(counterName);
  10569. }
  10570. };
  10571. Object.defineProperty(Tools, "Now", {
  10572. /**
  10573. * Gets either window.performance.now() if supported or Date.now() else
  10574. */
  10575. get: function () {
  10576. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10577. return window.performance.now();
  10578. }
  10579. return Date.now();
  10580. },
  10581. enumerable: true,
  10582. configurable: true
  10583. });
  10584. /**
  10585. * This method will return the name of the class used to create the instance of the given object.
  10586. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10587. * @param object the object to get the class name from
  10588. * @param isType defines if the object is actually a type
  10589. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10590. */
  10591. Tools.GetClassName = function (object, isType) {
  10592. if (isType === void 0) { isType = false; }
  10593. var name = null;
  10594. if (!isType && object.getClassName) {
  10595. name = object.getClassName();
  10596. }
  10597. else {
  10598. if (object instanceof Object) {
  10599. var classObj = isType ? object : Object.getPrototypeOf(object);
  10600. name = classObj.constructor["__bjsclassName__"];
  10601. }
  10602. if (!name) {
  10603. name = typeof object;
  10604. }
  10605. }
  10606. return name;
  10607. };
  10608. /**
  10609. * Gets the first element of an array satisfying a given predicate
  10610. * @param array defines the array to browse
  10611. * @param predicate defines the predicate to use
  10612. * @returns null if not found or the element
  10613. */
  10614. Tools.First = function (array, predicate) {
  10615. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10616. var el = array_1[_i];
  10617. if (predicate(el)) {
  10618. return el;
  10619. }
  10620. }
  10621. return null;
  10622. };
  10623. /**
  10624. * This method will return the name of the full name of the class, including its owning module (if any).
  10625. * 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).
  10626. * @param object the object to get the class name from
  10627. * @param isType defines if the object is actually a type
  10628. * @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.
  10629. * @ignorenaming
  10630. */
  10631. Tools.getFullClassName = function (object, isType) {
  10632. if (isType === void 0) { isType = false; }
  10633. var className = null;
  10634. var moduleName = null;
  10635. if (!isType && object.getClassName) {
  10636. className = object.getClassName();
  10637. }
  10638. else {
  10639. if (object instanceof Object) {
  10640. var classObj = isType ? object : Object.getPrototypeOf(object);
  10641. className = classObj.constructor["__bjsclassName__"];
  10642. moduleName = classObj.constructor["__bjsmoduleName__"];
  10643. }
  10644. if (!className) {
  10645. className = typeof object;
  10646. }
  10647. }
  10648. if (!className) {
  10649. return null;
  10650. }
  10651. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10652. };
  10653. /**
  10654. * Returns a promise that resolves after the given amount of time.
  10655. * @param delay Number of milliseconds to delay
  10656. * @returns Promise that resolves after the given amount of time
  10657. */
  10658. Tools.DelayAsync = function (delay) {
  10659. return new Promise(function (resolve) {
  10660. setTimeout(function () {
  10661. resolve();
  10662. }, delay);
  10663. });
  10664. };
  10665. /**
  10666. * Gets the current gradient from an array of IValueGradient
  10667. * @param ratio defines the current ratio to get
  10668. * @param gradients defines the array of IValueGradient
  10669. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10670. */
  10671. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10672. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10673. var currentGradient = gradients[gradientIndex];
  10674. var nextGradient = gradients[gradientIndex + 1];
  10675. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10676. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10677. updateFunc(currentGradient, nextGradient, scale);
  10678. return;
  10679. }
  10680. }
  10681. // Use last index if over
  10682. var lastIndex = gradients.length - 1;
  10683. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10684. };
  10685. /**
  10686. * Gets or sets the base URL to use to load assets
  10687. */
  10688. Tools.BaseUrl = "";
  10689. /**
  10690. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10691. */
  10692. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10693. /**
  10694. * Default behaviour for cors in the application.
  10695. * It can be a string if the expected behavior is identical in the entire app.
  10696. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10697. */
  10698. Tools.CorsBehavior = "anonymous";
  10699. /**
  10700. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10701. * @ignorenaming
  10702. */
  10703. Tools.UseFallbackTexture = true;
  10704. /**
  10705. * Use this object to register external classes like custom textures or material
  10706. * to allow the laoders to instantiate them
  10707. */
  10708. Tools.RegisteredExternalClasses = {};
  10709. /**
  10710. * Texture content used if a texture cannot loaded
  10711. * @ignorenaming
  10712. */
  10713. 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";
  10714. Tools._tmpFloatArray = new Float32Array(1);
  10715. /**
  10716. * Gets or sets a function used to pre-process url before using them to load assets
  10717. */
  10718. Tools.PreprocessUrl = function (url) {
  10719. return url;
  10720. };
  10721. // Logs
  10722. /**
  10723. * No log
  10724. */
  10725. Tools.NoneLogLevel = 0;
  10726. /**
  10727. * Only message logs
  10728. */
  10729. Tools.MessageLogLevel = 1;
  10730. /**
  10731. * Only warning logs
  10732. */
  10733. Tools.WarningLogLevel = 2;
  10734. /**
  10735. * Only error logs
  10736. */
  10737. Tools.ErrorLogLevel = 4;
  10738. /**
  10739. * All logs
  10740. */
  10741. Tools.AllLogLevel = 7;
  10742. Tools._LogCache = "";
  10743. /**
  10744. * Gets a value indicating the number of loading errors
  10745. * @ignorenaming
  10746. */
  10747. Tools.errorsCount = 0;
  10748. /**
  10749. * Log a message to the console
  10750. */
  10751. Tools.Log = Tools._LogEnabled;
  10752. /**
  10753. * Write a warning message to the console
  10754. */
  10755. Tools.Warn = Tools._WarnEnabled;
  10756. /**
  10757. * Write an error message to the console
  10758. */
  10759. Tools.Error = Tools._ErrorEnabled;
  10760. // Performances
  10761. /**
  10762. * No performance log
  10763. */
  10764. Tools.PerformanceNoneLogLevel = 0;
  10765. /**
  10766. * Use user marks to log performance
  10767. */
  10768. Tools.PerformanceUserMarkLogLevel = 1;
  10769. /**
  10770. * Log performance to the console
  10771. */
  10772. Tools.PerformanceConsoleLogLevel = 2;
  10773. /**
  10774. * Starts a performance counter
  10775. */
  10776. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10777. /**
  10778. * Ends a specific performance coutner
  10779. */
  10780. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10781. return Tools;
  10782. }());
  10783. BABYLON.Tools = Tools;
  10784. /**
  10785. * This class is used to track a performance counter which is number based.
  10786. * The user has access to many properties which give statistics of different nature.
  10787. *
  10788. * The implementer can track two kinds of Performance Counter: time and count.
  10789. * 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.
  10790. * 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.
  10791. */
  10792. var PerfCounter = /** @class */ (function () {
  10793. /**
  10794. * Creates a new counter
  10795. */
  10796. function PerfCounter() {
  10797. this._startMonitoringTime = 0;
  10798. this._min = 0;
  10799. this._max = 0;
  10800. this._average = 0;
  10801. this._lastSecAverage = 0;
  10802. this._current = 0;
  10803. this._totalValueCount = 0;
  10804. this._totalAccumulated = 0;
  10805. this._lastSecAccumulated = 0;
  10806. this._lastSecTime = 0;
  10807. this._lastSecValueCount = 0;
  10808. }
  10809. Object.defineProperty(PerfCounter.prototype, "min", {
  10810. /**
  10811. * Returns the smallest value ever
  10812. */
  10813. get: function () {
  10814. return this._min;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(PerfCounter.prototype, "max", {
  10820. /**
  10821. * Returns the biggest value ever
  10822. */
  10823. get: function () {
  10824. return this._max;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(PerfCounter.prototype, "average", {
  10830. /**
  10831. * Returns the average value since the performance counter is running
  10832. */
  10833. get: function () {
  10834. return this._average;
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10840. /**
  10841. * Returns the average value of the last second the counter was monitored
  10842. */
  10843. get: function () {
  10844. return this._lastSecAverage;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(PerfCounter.prototype, "current", {
  10850. /**
  10851. * Returns the current value
  10852. */
  10853. get: function () {
  10854. return this._current;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(PerfCounter.prototype, "total", {
  10860. /**
  10861. * Gets the accumulated total
  10862. */
  10863. get: function () {
  10864. return this._totalAccumulated;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(PerfCounter.prototype, "count", {
  10870. /**
  10871. * Gets the total value count
  10872. */
  10873. get: function () {
  10874. return this._totalValueCount;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. /**
  10880. * Call this method to start monitoring a new frame.
  10881. * 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.
  10882. */
  10883. PerfCounter.prototype.fetchNewFrame = function () {
  10884. this._totalValueCount++;
  10885. this._current = 0;
  10886. this._lastSecValueCount++;
  10887. };
  10888. /**
  10889. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10890. * @param newCount the count value to add to the monitored count
  10891. * @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.
  10892. */
  10893. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10894. if (!PerfCounter.Enabled) {
  10895. return;
  10896. }
  10897. this._current += newCount;
  10898. if (fetchResult) {
  10899. this._fetchResult();
  10900. }
  10901. };
  10902. /**
  10903. * Start monitoring this performance counter
  10904. */
  10905. PerfCounter.prototype.beginMonitoring = function () {
  10906. if (!PerfCounter.Enabled) {
  10907. return;
  10908. }
  10909. this._startMonitoringTime = Tools.Now;
  10910. };
  10911. /**
  10912. * Compute the time lapsed since the previous beginMonitoring() call.
  10913. * @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
  10914. */
  10915. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10916. if (newFrame === void 0) { newFrame = true; }
  10917. if (!PerfCounter.Enabled) {
  10918. return;
  10919. }
  10920. if (newFrame) {
  10921. this.fetchNewFrame();
  10922. }
  10923. var currentTime = Tools.Now;
  10924. this._current = currentTime - this._startMonitoringTime;
  10925. if (newFrame) {
  10926. this._fetchResult();
  10927. }
  10928. };
  10929. PerfCounter.prototype._fetchResult = function () {
  10930. this._totalAccumulated += this._current;
  10931. this._lastSecAccumulated += this._current;
  10932. // Min/Max update
  10933. this._min = Math.min(this._min, this._current);
  10934. this._max = Math.max(this._max, this._current);
  10935. this._average = this._totalAccumulated / this._totalValueCount;
  10936. // Reset last sec?
  10937. var now = Tools.Now;
  10938. if ((now - this._lastSecTime) > 1000) {
  10939. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10940. this._lastSecTime = now;
  10941. this._lastSecAccumulated = 0;
  10942. this._lastSecValueCount = 0;
  10943. }
  10944. };
  10945. /**
  10946. * Gets or sets a global boolean to turn on and off all the counters
  10947. */
  10948. PerfCounter.Enabled = true;
  10949. return PerfCounter;
  10950. }());
  10951. BABYLON.PerfCounter = PerfCounter;
  10952. /**
  10953. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10954. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10955. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10956. * @param name The name of the class, case should be preserved
  10957. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10958. */
  10959. function className(name, module) {
  10960. return function (target) {
  10961. target["__bjsclassName__"] = name;
  10962. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10963. };
  10964. }
  10965. BABYLON.className = className;
  10966. /**
  10967. * An implementation of a loop for asynchronous functions.
  10968. */
  10969. var AsyncLoop = /** @class */ (function () {
  10970. /**
  10971. * Constructor.
  10972. * @param iterations the number of iterations.
  10973. * @param func the function to run each iteration
  10974. * @param successCallback the callback that will be called upon succesful execution
  10975. * @param offset starting offset.
  10976. */
  10977. function AsyncLoop(
  10978. /**
  10979. * Defines the number of iterations for the loop
  10980. */
  10981. iterations, func, successCallback, offset) {
  10982. if (offset === void 0) { offset = 0; }
  10983. this.iterations = iterations;
  10984. this.index = offset - 1;
  10985. this._done = false;
  10986. this._fn = func;
  10987. this._successCallback = successCallback;
  10988. }
  10989. /**
  10990. * Execute the next iteration. Must be called after the last iteration was finished.
  10991. */
  10992. AsyncLoop.prototype.executeNext = function () {
  10993. if (!this._done) {
  10994. if (this.index + 1 < this.iterations) {
  10995. ++this.index;
  10996. this._fn(this);
  10997. }
  10998. else {
  10999. this.breakLoop();
  11000. }
  11001. }
  11002. };
  11003. /**
  11004. * Break the loop and run the success callback.
  11005. */
  11006. AsyncLoop.prototype.breakLoop = function () {
  11007. this._done = true;
  11008. this._successCallback();
  11009. };
  11010. /**
  11011. * Create and run an async loop.
  11012. * @param iterations the number of iterations.
  11013. * @param fn the function to run each iteration
  11014. * @param successCallback the callback that will be called upon succesful execution
  11015. * @param offset starting offset.
  11016. * @returns the created async loop object
  11017. */
  11018. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11019. if (offset === void 0) { offset = 0; }
  11020. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11021. loop.executeNext();
  11022. return loop;
  11023. };
  11024. /**
  11025. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11026. * @param iterations total number of iterations
  11027. * @param syncedIterations number of synchronous iterations in each async iteration.
  11028. * @param fn the function to call each iteration.
  11029. * @param callback a success call back that will be called when iterating stops.
  11030. * @param breakFunction a break condition (optional)
  11031. * @param timeout timeout settings for the setTimeout function. default - 0.
  11032. * @returns the created async loop object
  11033. */
  11034. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11035. if (timeout === void 0) { timeout = 0; }
  11036. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11037. if (breakFunction && breakFunction())
  11038. loop.breakLoop();
  11039. else {
  11040. setTimeout(function () {
  11041. for (var i = 0; i < syncedIterations; ++i) {
  11042. var iteration = (loop.index * syncedIterations) + i;
  11043. if (iteration >= iterations)
  11044. break;
  11045. fn(iteration);
  11046. if (breakFunction && breakFunction()) {
  11047. loop.breakLoop();
  11048. break;
  11049. }
  11050. }
  11051. loop.executeNext();
  11052. }, timeout);
  11053. }
  11054. }, callback);
  11055. };
  11056. return AsyncLoop;
  11057. }());
  11058. BABYLON.AsyncLoop = AsyncLoop;
  11059. })(BABYLON || (BABYLON = {}));
  11060. //# sourceMappingURL=babylon.tools.js.map
  11061. var BABYLON;
  11062. (function (BABYLON) {
  11063. var PromiseStates;
  11064. (function (PromiseStates) {
  11065. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11066. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11067. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11068. })(PromiseStates || (PromiseStates = {}));
  11069. var FulFillmentAgregator = /** @class */ (function () {
  11070. function FulFillmentAgregator() {
  11071. this.count = 0;
  11072. this.target = 0;
  11073. this.results = [];
  11074. }
  11075. return FulFillmentAgregator;
  11076. }());
  11077. var InternalPromise = /** @class */ (function () {
  11078. function InternalPromise(resolver) {
  11079. var _this = this;
  11080. this._state = PromiseStates.Pending;
  11081. this._children = new Array();
  11082. this._rejectWasConsumed = false;
  11083. if (!resolver) {
  11084. return;
  11085. }
  11086. try {
  11087. resolver(function (value) {
  11088. _this._resolve(value);
  11089. }, function (reason) {
  11090. _this._reject(reason);
  11091. });
  11092. }
  11093. catch (e) {
  11094. this._reject(e);
  11095. }
  11096. }
  11097. Object.defineProperty(InternalPromise.prototype, "_result", {
  11098. get: function () {
  11099. return this._resultValue;
  11100. },
  11101. set: function (value) {
  11102. this._resultValue = value;
  11103. if (this._parent && this._parent._result === undefined) {
  11104. this._parent._result = value;
  11105. }
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. InternalPromise.prototype.catch = function (onRejected) {
  11111. return this.then(undefined, onRejected);
  11112. };
  11113. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11114. var _this = this;
  11115. var newPromise = new InternalPromise();
  11116. newPromise._onFulfilled = onFulfilled;
  11117. newPromise._onRejected = onRejected;
  11118. // Composition
  11119. this._children.push(newPromise);
  11120. newPromise._parent = this;
  11121. if (this._state !== PromiseStates.Pending) {
  11122. BABYLON.Tools.SetImmediate(function () {
  11123. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11124. var returnedValue = newPromise._resolve(_this._result);
  11125. if (returnedValue !== undefined && returnedValue !== null) {
  11126. if (returnedValue._state !== undefined) {
  11127. var returnedPromise = returnedValue;
  11128. newPromise._children.push(returnedPromise);
  11129. returnedPromise._parent = newPromise;
  11130. newPromise = returnedPromise;
  11131. }
  11132. else {
  11133. newPromise._result = returnedValue;
  11134. }
  11135. }
  11136. }
  11137. else {
  11138. newPromise._reject(_this._reason);
  11139. }
  11140. });
  11141. }
  11142. return newPromise;
  11143. };
  11144. InternalPromise.prototype._moveChildren = function (children) {
  11145. var _this = this;
  11146. var _a;
  11147. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11148. this._children.forEach(function (child) {
  11149. child._parent = _this;
  11150. });
  11151. if (this._state === PromiseStates.Fulfilled) {
  11152. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11153. var child = _b[_i];
  11154. child._resolve(this._result);
  11155. }
  11156. }
  11157. else if (this._state === PromiseStates.Rejected) {
  11158. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11159. var child = _d[_c];
  11160. child._reject(this._reason);
  11161. }
  11162. }
  11163. };
  11164. InternalPromise.prototype._resolve = function (value) {
  11165. try {
  11166. this._state = PromiseStates.Fulfilled;
  11167. var returnedValue = null;
  11168. if (this._onFulfilled) {
  11169. returnedValue = this._onFulfilled(value);
  11170. }
  11171. if (returnedValue !== undefined && returnedValue !== null) {
  11172. if (returnedValue._state !== undefined) {
  11173. // Transmit children
  11174. var returnedPromise = returnedValue;
  11175. returnedPromise._parent = this;
  11176. returnedPromise._moveChildren(this._children);
  11177. value = returnedPromise._result;
  11178. }
  11179. else {
  11180. value = returnedValue;
  11181. }
  11182. }
  11183. this._result = value;
  11184. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11185. var child = _a[_i];
  11186. child._resolve(value);
  11187. }
  11188. this._children.length = 0;
  11189. delete this._onFulfilled;
  11190. delete this._onRejected;
  11191. }
  11192. catch (e) {
  11193. this._reject(e, true);
  11194. }
  11195. };
  11196. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11197. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11198. this._state = PromiseStates.Rejected;
  11199. this._reason = reason;
  11200. if (this._onRejected && !onLocalThrow) {
  11201. try {
  11202. this._onRejected(reason);
  11203. this._rejectWasConsumed = true;
  11204. }
  11205. catch (e) {
  11206. reason = e;
  11207. }
  11208. }
  11209. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11210. var child = _a[_i];
  11211. if (this._rejectWasConsumed) {
  11212. child._resolve(null);
  11213. }
  11214. else {
  11215. child._reject(reason);
  11216. }
  11217. }
  11218. this._children.length = 0;
  11219. delete this._onFulfilled;
  11220. delete this._onRejected;
  11221. };
  11222. InternalPromise.resolve = function (value) {
  11223. var newPromise = new InternalPromise();
  11224. newPromise._resolve(value);
  11225. return newPromise;
  11226. };
  11227. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11228. promise.then(function (value) {
  11229. agregator.results[index] = value;
  11230. agregator.count++;
  11231. if (agregator.count === agregator.target) {
  11232. agregator.rootPromise._resolve(agregator.results);
  11233. }
  11234. return null;
  11235. }, function (reason) {
  11236. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11237. agregator.rootPromise._reject(reason);
  11238. }
  11239. });
  11240. };
  11241. InternalPromise.all = function (promises) {
  11242. var newPromise = new InternalPromise();
  11243. var agregator = new FulFillmentAgregator();
  11244. agregator.target = promises.length;
  11245. agregator.rootPromise = newPromise;
  11246. if (promises.length) {
  11247. for (var index = 0; index < promises.length; index++) {
  11248. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11249. }
  11250. }
  11251. else {
  11252. newPromise._resolve([]);
  11253. }
  11254. return newPromise;
  11255. };
  11256. InternalPromise.race = function (promises) {
  11257. var newPromise = new InternalPromise();
  11258. if (promises.length) {
  11259. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11260. var promise = promises_1[_i];
  11261. promise.then(function (value) {
  11262. if (newPromise) {
  11263. newPromise._resolve(value);
  11264. newPromise = null;
  11265. }
  11266. return null;
  11267. }, function (reason) {
  11268. if (newPromise) {
  11269. newPromise._reject(reason);
  11270. newPromise = null;
  11271. }
  11272. });
  11273. }
  11274. }
  11275. return newPromise;
  11276. };
  11277. return InternalPromise;
  11278. }());
  11279. /**
  11280. * Helper class that provides a small promise polyfill
  11281. */
  11282. var PromisePolyfill = /** @class */ (function () {
  11283. function PromisePolyfill() {
  11284. }
  11285. /**
  11286. * Static function used to check if the polyfill is required
  11287. * If this is the case then the function will inject the polyfill to window.Promise
  11288. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11289. */
  11290. PromisePolyfill.Apply = function (force) {
  11291. if (force === void 0) { force = false; }
  11292. if (force || typeof Promise === 'undefined') {
  11293. var root = window;
  11294. root.Promise = InternalPromise;
  11295. }
  11296. };
  11297. return PromisePolyfill;
  11298. }());
  11299. BABYLON.PromisePolyfill = PromisePolyfill;
  11300. })(BABYLON || (BABYLON = {}));
  11301. //# sourceMappingURL=babylon.promise.js.map
  11302. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11303. var BABYLON;
  11304. (function (BABYLON) {
  11305. /**
  11306. * Helper class to push actions to a pool of workers.
  11307. */
  11308. var WorkerPool = /** @class */ (function () {
  11309. /**
  11310. * Constructor
  11311. * @param workers Array of workers to use for actions
  11312. */
  11313. function WorkerPool(workers) {
  11314. this._pendingActions = new Array();
  11315. this._workerInfos = workers.map(function (worker) { return ({
  11316. worker: worker,
  11317. active: false
  11318. }); });
  11319. }
  11320. /**
  11321. * Terminates all workers and clears any pending actions.
  11322. */
  11323. WorkerPool.prototype.dispose = function () {
  11324. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11325. var workerInfo = _a[_i];
  11326. workerInfo.worker.terminate();
  11327. }
  11328. delete this._workerInfos;
  11329. delete this._pendingActions;
  11330. };
  11331. /**
  11332. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11333. * pended until a worker has completed its action.
  11334. * @param action The action to perform. Call onComplete when the action is complete.
  11335. */
  11336. WorkerPool.prototype.push = function (action) {
  11337. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11338. var workerInfo = _a[_i];
  11339. if (!workerInfo.active) {
  11340. this._execute(workerInfo, action);
  11341. return;
  11342. }
  11343. }
  11344. this._pendingActions.push(action);
  11345. };
  11346. WorkerPool.prototype._execute = function (workerInfo, action) {
  11347. var _this = this;
  11348. workerInfo.active = true;
  11349. action(workerInfo.worker, function () {
  11350. workerInfo.active = false;
  11351. var nextAction = _this._pendingActions.shift();
  11352. if (nextAction) {
  11353. _this._execute(workerInfo, nextAction);
  11354. }
  11355. });
  11356. };
  11357. return WorkerPool;
  11358. }());
  11359. BABYLON.WorkerPool = WorkerPool;
  11360. })(BABYLON || (BABYLON = {}));
  11361. //# sourceMappingURL=babylon.workerPool.js.map
  11362. var BABYLON;
  11363. (function (BABYLON) {
  11364. /**
  11365. * @hidden
  11366. **/
  11367. var _AlphaState = /** @class */ (function () {
  11368. /**
  11369. * Initializes the state.
  11370. */
  11371. function _AlphaState() {
  11372. this._isAlphaBlendDirty = false;
  11373. this._isBlendFunctionParametersDirty = false;
  11374. this._isBlendEquationParametersDirty = false;
  11375. this._isBlendConstantsDirty = false;
  11376. this._alphaBlend = false;
  11377. this._blendFunctionParameters = new Array(4);
  11378. this._blendEquationParameters = new Array(2);
  11379. this._blendConstants = new Array(4);
  11380. this.reset();
  11381. }
  11382. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11383. get: function () {
  11384. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11390. get: function () {
  11391. return this._alphaBlend;
  11392. },
  11393. set: function (value) {
  11394. if (this._alphaBlend === value) {
  11395. return;
  11396. }
  11397. this._alphaBlend = value;
  11398. this._isAlphaBlendDirty = true;
  11399. },
  11400. enumerable: true,
  11401. configurable: true
  11402. });
  11403. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11404. if (this._blendConstants[0] === r &&
  11405. this._blendConstants[1] === g &&
  11406. this._blendConstants[2] === b &&
  11407. this._blendConstants[3] === a) {
  11408. return;
  11409. }
  11410. this._blendConstants[0] = r;
  11411. this._blendConstants[1] = g;
  11412. this._blendConstants[2] = b;
  11413. this._blendConstants[3] = a;
  11414. this._isBlendConstantsDirty = true;
  11415. };
  11416. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11417. if (this._blendFunctionParameters[0] === value0 &&
  11418. this._blendFunctionParameters[1] === value1 &&
  11419. this._blendFunctionParameters[2] === value2 &&
  11420. this._blendFunctionParameters[3] === value3) {
  11421. return;
  11422. }
  11423. this._blendFunctionParameters[0] = value0;
  11424. this._blendFunctionParameters[1] = value1;
  11425. this._blendFunctionParameters[2] = value2;
  11426. this._blendFunctionParameters[3] = value3;
  11427. this._isBlendFunctionParametersDirty = true;
  11428. };
  11429. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11430. if (this._blendEquationParameters[0] === rgb &&
  11431. this._blendEquationParameters[1] === alpha) {
  11432. return;
  11433. }
  11434. this._blendEquationParameters[0] = rgb;
  11435. this._blendEquationParameters[1] = alpha;
  11436. this._isBlendEquationParametersDirty = true;
  11437. };
  11438. _AlphaState.prototype.reset = function () {
  11439. this._alphaBlend = false;
  11440. this._blendFunctionParameters[0] = null;
  11441. this._blendFunctionParameters[1] = null;
  11442. this._blendFunctionParameters[2] = null;
  11443. this._blendFunctionParameters[3] = null;
  11444. this._blendEquationParameters[0] = null;
  11445. this._blendEquationParameters[1] = null;
  11446. this._blendConstants[0] = null;
  11447. this._blendConstants[1] = null;
  11448. this._blendConstants[2] = null;
  11449. this._blendConstants[3] = null;
  11450. this._isAlphaBlendDirty = true;
  11451. this._isBlendFunctionParametersDirty = false;
  11452. this._isBlendEquationParametersDirty = false;
  11453. this._isBlendConstantsDirty = false;
  11454. };
  11455. _AlphaState.prototype.apply = function (gl) {
  11456. if (!this.isDirty) {
  11457. return;
  11458. }
  11459. // Alpha blend
  11460. if (this._isAlphaBlendDirty) {
  11461. if (this._alphaBlend) {
  11462. gl.enable(gl.BLEND);
  11463. }
  11464. else {
  11465. gl.disable(gl.BLEND);
  11466. }
  11467. this._isAlphaBlendDirty = false;
  11468. }
  11469. // Alpha function
  11470. if (this._isBlendFunctionParametersDirty) {
  11471. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11472. this._isBlendFunctionParametersDirty = false;
  11473. }
  11474. // Alpha equation
  11475. if (this._isBlendEquationParametersDirty) {
  11476. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11477. this._isBlendEquationParametersDirty = false;
  11478. }
  11479. // Constants
  11480. if (this._isBlendConstantsDirty) {
  11481. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11482. this._isBlendConstantsDirty = false;
  11483. }
  11484. };
  11485. return _AlphaState;
  11486. }());
  11487. BABYLON._AlphaState = _AlphaState;
  11488. })(BABYLON || (BABYLON = {}));
  11489. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11490. var BABYLON;
  11491. (function (BABYLON) {
  11492. /**
  11493. * @hidden
  11494. **/
  11495. var _DepthCullingState = /** @class */ (function () {
  11496. /**
  11497. * Initializes the state.
  11498. */
  11499. function _DepthCullingState() {
  11500. this._isDepthTestDirty = false;
  11501. this._isDepthMaskDirty = false;
  11502. this._isDepthFuncDirty = false;
  11503. this._isCullFaceDirty = false;
  11504. this._isCullDirty = false;
  11505. this._isZOffsetDirty = false;
  11506. this._isFrontFaceDirty = false;
  11507. this.reset();
  11508. }
  11509. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11510. get: function () {
  11511. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11512. },
  11513. enumerable: true,
  11514. configurable: true
  11515. });
  11516. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11517. get: function () {
  11518. return this._zOffset;
  11519. },
  11520. set: function (value) {
  11521. if (this._zOffset === value) {
  11522. return;
  11523. }
  11524. this._zOffset = value;
  11525. this._isZOffsetDirty = true;
  11526. },
  11527. enumerable: true,
  11528. configurable: true
  11529. });
  11530. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11531. get: function () {
  11532. return this._cullFace;
  11533. },
  11534. set: function (value) {
  11535. if (this._cullFace === value) {
  11536. return;
  11537. }
  11538. this._cullFace = value;
  11539. this._isCullFaceDirty = true;
  11540. },
  11541. enumerable: true,
  11542. configurable: true
  11543. });
  11544. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11545. get: function () {
  11546. return this._cull;
  11547. },
  11548. set: function (value) {
  11549. if (this._cull === value) {
  11550. return;
  11551. }
  11552. this._cull = value;
  11553. this._isCullDirty = true;
  11554. },
  11555. enumerable: true,
  11556. configurable: true
  11557. });
  11558. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11559. get: function () {
  11560. return this._depthFunc;
  11561. },
  11562. set: function (value) {
  11563. if (this._depthFunc === value) {
  11564. return;
  11565. }
  11566. this._depthFunc = value;
  11567. this._isDepthFuncDirty = true;
  11568. },
  11569. enumerable: true,
  11570. configurable: true
  11571. });
  11572. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11573. get: function () {
  11574. return this._depthMask;
  11575. },
  11576. set: function (value) {
  11577. if (this._depthMask === value) {
  11578. return;
  11579. }
  11580. this._depthMask = value;
  11581. this._isDepthMaskDirty = true;
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11587. get: function () {
  11588. return this._depthTest;
  11589. },
  11590. set: function (value) {
  11591. if (this._depthTest === value) {
  11592. return;
  11593. }
  11594. this._depthTest = value;
  11595. this._isDepthTestDirty = true;
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11601. get: function () {
  11602. return this._frontFace;
  11603. },
  11604. set: function (value) {
  11605. if (this._frontFace === value) {
  11606. return;
  11607. }
  11608. this._frontFace = value;
  11609. this._isFrontFaceDirty = true;
  11610. },
  11611. enumerable: true,
  11612. configurable: true
  11613. });
  11614. _DepthCullingState.prototype.reset = function () {
  11615. this._depthMask = true;
  11616. this._depthTest = true;
  11617. this._depthFunc = null;
  11618. this._cullFace = null;
  11619. this._cull = null;
  11620. this._zOffset = 0;
  11621. this._frontFace = null;
  11622. this._isDepthTestDirty = true;
  11623. this._isDepthMaskDirty = true;
  11624. this._isDepthFuncDirty = false;
  11625. this._isCullFaceDirty = false;
  11626. this._isCullDirty = false;
  11627. this._isZOffsetDirty = false;
  11628. this._isFrontFaceDirty = false;
  11629. };
  11630. _DepthCullingState.prototype.apply = function (gl) {
  11631. if (!this.isDirty) {
  11632. return;
  11633. }
  11634. // Cull
  11635. if (this._isCullDirty) {
  11636. if (this.cull) {
  11637. gl.enable(gl.CULL_FACE);
  11638. }
  11639. else {
  11640. gl.disable(gl.CULL_FACE);
  11641. }
  11642. this._isCullDirty = false;
  11643. }
  11644. // Cull face
  11645. if (this._isCullFaceDirty) {
  11646. gl.cullFace(this.cullFace);
  11647. this._isCullFaceDirty = false;
  11648. }
  11649. // Depth mask
  11650. if (this._isDepthMaskDirty) {
  11651. gl.depthMask(this.depthMask);
  11652. this._isDepthMaskDirty = false;
  11653. }
  11654. // Depth test
  11655. if (this._isDepthTestDirty) {
  11656. if (this.depthTest) {
  11657. gl.enable(gl.DEPTH_TEST);
  11658. }
  11659. else {
  11660. gl.disable(gl.DEPTH_TEST);
  11661. }
  11662. this._isDepthTestDirty = false;
  11663. }
  11664. // Depth func
  11665. if (this._isDepthFuncDirty) {
  11666. gl.depthFunc(this.depthFunc);
  11667. this._isDepthFuncDirty = false;
  11668. }
  11669. // zOffset
  11670. if (this._isZOffsetDirty) {
  11671. if (this.zOffset) {
  11672. gl.enable(gl.POLYGON_OFFSET_FILL);
  11673. gl.polygonOffset(this.zOffset, 0);
  11674. }
  11675. else {
  11676. gl.disable(gl.POLYGON_OFFSET_FILL);
  11677. }
  11678. this._isZOffsetDirty = false;
  11679. }
  11680. // Front face
  11681. if (this._isFrontFaceDirty) {
  11682. gl.frontFace(this.frontFace);
  11683. this._isFrontFaceDirty = false;
  11684. }
  11685. };
  11686. return _DepthCullingState;
  11687. }());
  11688. BABYLON._DepthCullingState = _DepthCullingState;
  11689. })(BABYLON || (BABYLON = {}));
  11690. //# sourceMappingURL=babylon.depthCullingState.js.map
  11691. var BABYLON;
  11692. (function (BABYLON) {
  11693. /**
  11694. * @hidden
  11695. **/
  11696. var _StencilState = /** @class */ (function () {
  11697. function _StencilState() {
  11698. this._isStencilTestDirty = false;
  11699. this._isStencilMaskDirty = false;
  11700. this._isStencilFuncDirty = false;
  11701. this._isStencilOpDirty = false;
  11702. this.reset();
  11703. }
  11704. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11705. get: function () {
  11706. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11712. get: function () {
  11713. return this._stencilFunc;
  11714. },
  11715. set: function (value) {
  11716. if (this._stencilFunc === value) {
  11717. return;
  11718. }
  11719. this._stencilFunc = value;
  11720. this._isStencilFuncDirty = true;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11726. get: function () {
  11727. return this._stencilFuncRef;
  11728. },
  11729. set: function (value) {
  11730. if (this._stencilFuncRef === value) {
  11731. return;
  11732. }
  11733. this._stencilFuncRef = value;
  11734. this._isStencilFuncDirty = true;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11740. get: function () {
  11741. return this._stencilFuncMask;
  11742. },
  11743. set: function (value) {
  11744. if (this._stencilFuncMask === value) {
  11745. return;
  11746. }
  11747. this._stencilFuncMask = value;
  11748. this._isStencilFuncDirty = true;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11754. get: function () {
  11755. return this._stencilOpStencilFail;
  11756. },
  11757. set: function (value) {
  11758. if (this._stencilOpStencilFail === value) {
  11759. return;
  11760. }
  11761. this._stencilOpStencilFail = value;
  11762. this._isStencilOpDirty = true;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11768. get: function () {
  11769. return this._stencilOpDepthFail;
  11770. },
  11771. set: function (value) {
  11772. if (this._stencilOpDepthFail === value) {
  11773. return;
  11774. }
  11775. this._stencilOpDepthFail = value;
  11776. this._isStencilOpDirty = true;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11782. get: function () {
  11783. return this._stencilOpStencilDepthPass;
  11784. },
  11785. set: function (value) {
  11786. if (this._stencilOpStencilDepthPass === value) {
  11787. return;
  11788. }
  11789. this._stencilOpStencilDepthPass = value;
  11790. this._isStencilOpDirty = true;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11796. get: function () {
  11797. return this._stencilMask;
  11798. },
  11799. set: function (value) {
  11800. if (this._stencilMask === value) {
  11801. return;
  11802. }
  11803. this._stencilMask = value;
  11804. this._isStencilMaskDirty = true;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11810. get: function () {
  11811. return this._stencilTest;
  11812. },
  11813. set: function (value) {
  11814. if (this._stencilTest === value) {
  11815. return;
  11816. }
  11817. this._stencilTest = value;
  11818. this._isStencilTestDirty = true;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. _StencilState.prototype.reset = function () {
  11824. this._stencilTest = false;
  11825. this._stencilMask = 0xFF;
  11826. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11827. this._stencilFuncRef = 1;
  11828. this._stencilFuncMask = 0xFF;
  11829. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11830. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11831. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11832. this._isStencilTestDirty = true;
  11833. this._isStencilMaskDirty = true;
  11834. this._isStencilFuncDirty = true;
  11835. this._isStencilOpDirty = true;
  11836. };
  11837. _StencilState.prototype.apply = function (gl) {
  11838. if (!this.isDirty) {
  11839. return;
  11840. }
  11841. // Stencil test
  11842. if (this._isStencilTestDirty) {
  11843. if (this.stencilTest) {
  11844. gl.enable(gl.STENCIL_TEST);
  11845. }
  11846. else {
  11847. gl.disable(gl.STENCIL_TEST);
  11848. }
  11849. this._isStencilTestDirty = false;
  11850. }
  11851. // Stencil mask
  11852. if (this._isStencilMaskDirty) {
  11853. gl.stencilMask(this.stencilMask);
  11854. this._isStencilMaskDirty = false;
  11855. }
  11856. // Stencil func
  11857. if (this._isStencilFuncDirty) {
  11858. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11859. this._isStencilFuncDirty = false;
  11860. }
  11861. // Stencil op
  11862. if (this._isStencilOpDirty) {
  11863. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11864. this._isStencilOpDirty = false;
  11865. }
  11866. };
  11867. return _StencilState;
  11868. }());
  11869. BABYLON._StencilState = _StencilState;
  11870. })(BABYLON || (BABYLON = {}));
  11871. //# sourceMappingURL=babylon.stencilState.js.map
  11872. var __assign = (this && this.__assign) || function () {
  11873. __assign = Object.assign || function(t) {
  11874. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11875. s = arguments[i];
  11876. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11877. t[p] = s[p];
  11878. }
  11879. return t;
  11880. };
  11881. return __assign.apply(this, arguments);
  11882. };
  11883. var BABYLON;
  11884. (function (BABYLON) {
  11885. /**
  11886. * Keeps track of all the buffer info used in engine.
  11887. */
  11888. var BufferPointer = /** @class */ (function () {
  11889. function BufferPointer() {
  11890. }
  11891. return BufferPointer;
  11892. }());
  11893. /**
  11894. * Interface for attribute information associated with buffer instanciation
  11895. */
  11896. var InstancingAttributeInfo = /** @class */ (function () {
  11897. function InstancingAttributeInfo() {
  11898. }
  11899. return InstancingAttributeInfo;
  11900. }());
  11901. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11902. /**
  11903. * Define options used to create a render target texture
  11904. */
  11905. var RenderTargetCreationOptions = /** @class */ (function () {
  11906. function RenderTargetCreationOptions() {
  11907. }
  11908. return RenderTargetCreationOptions;
  11909. }());
  11910. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11911. /**
  11912. * Define options used to create a depth texture
  11913. */
  11914. var DepthTextureCreationOptions = /** @class */ (function () {
  11915. function DepthTextureCreationOptions() {
  11916. }
  11917. return DepthTextureCreationOptions;
  11918. }());
  11919. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11920. /**
  11921. * Class used to describe the capabilities of the engine relatively to the current browser
  11922. */
  11923. var EngineCapabilities = /** @class */ (function () {
  11924. function EngineCapabilities() {
  11925. }
  11926. return EngineCapabilities;
  11927. }());
  11928. BABYLON.EngineCapabilities = EngineCapabilities;
  11929. /**
  11930. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11931. */
  11932. var Engine = /** @class */ (function () {
  11933. /**
  11934. * Creates a new engine
  11935. * @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
  11936. * @param antialias defines enable antialiasing (default: false)
  11937. * @param options defines further options to be sent to the getContext() function
  11938. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11939. */
  11940. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11941. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11942. var _this = this;
  11943. // Public members
  11944. /**
  11945. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11946. */
  11947. this.forcePOTTextures = false;
  11948. /**
  11949. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11950. */
  11951. this.isFullscreen = false;
  11952. /**
  11953. * Gets a boolean indicating if the pointer is currently locked
  11954. */
  11955. this.isPointerLock = false;
  11956. /**
  11957. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11958. */
  11959. this.cullBackFaces = true;
  11960. /**
  11961. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11962. */
  11963. this.renderEvenInBackground = true;
  11964. /**
  11965. * Gets or sets a boolean indicating that cache can be kept between frames
  11966. */
  11967. this.preventCacheWipeBetweenFrames = false;
  11968. /**
  11969. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11970. **/
  11971. this.enableOfflineSupport = false;
  11972. /**
  11973. * 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)
  11974. **/
  11975. this.disableManifestCheck = false;
  11976. /**
  11977. * Gets the list of created scenes
  11978. */
  11979. this.scenes = new Array();
  11980. /**
  11981. * Gets the list of created postprocesses
  11982. */
  11983. this.postProcesses = new Array();
  11984. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11985. this.validateShaderPrograms = false;
  11986. // Observables
  11987. /**
  11988. * Observable event triggered each time the rendering canvas is resized
  11989. */
  11990. this.onResizeObservable = new BABYLON.Observable();
  11991. /**
  11992. * Observable event triggered each time the canvas loses focus
  11993. */
  11994. this.onCanvasBlurObservable = new BABYLON.Observable();
  11995. /**
  11996. * Observable event triggered each time the canvas gains focus
  11997. */
  11998. this.onCanvasFocusObservable = new BABYLON.Observable();
  11999. /**
  12000. * Observable event triggered each time the canvas receives pointerout event
  12001. */
  12002. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12003. /**
  12004. * Observable event triggered before each texture is initialized
  12005. */
  12006. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12007. //WebVR
  12008. this._vrDisplay = undefined;
  12009. this._vrSupported = false;
  12010. this._vrExclusivePointerMode = false;
  12011. // Uniform buffers list
  12012. /**
  12013. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12014. */
  12015. this.disableUniformBuffers = false;
  12016. /** @hidden */
  12017. this._uniformBuffers = new Array();
  12018. // Observables
  12019. /**
  12020. * Observable raised when the engine begins a new frame
  12021. */
  12022. this.onBeginFrameObservable = new BABYLON.Observable();
  12023. /**
  12024. * Observable raised when the engine ends the current frame
  12025. */
  12026. this.onEndFrameObservable = new BABYLON.Observable();
  12027. /**
  12028. * Observable raised when the engine is about to compile a shader
  12029. */
  12030. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12031. /**
  12032. * Observable raised when the engine has jsut compiled a shader
  12033. */
  12034. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12035. this._windowIsBackground = false;
  12036. this._webGLVersion = 1.0;
  12037. /** @hidden */
  12038. this._badOS = false;
  12039. /** @hidden */
  12040. this._badDesktopOS = false;
  12041. /**
  12042. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12043. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12044. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12045. */
  12046. this.disableTextureBindingOptimization = false;
  12047. /**
  12048. * Observable signaled when VR display mode changes
  12049. */
  12050. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12051. /**
  12052. * Observable signaled when VR request present is complete
  12053. */
  12054. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12055. /**
  12056. * Observable signaled when VR request present starts
  12057. */
  12058. this.onVRRequestPresentStart = new BABYLON.Observable();
  12059. this._colorWrite = true;
  12060. /** @hidden */
  12061. this._drawCalls = new BABYLON.PerfCounter();
  12062. /** @hidden */
  12063. this._textureCollisions = new BABYLON.PerfCounter();
  12064. this._renderingQueueLaunched = false;
  12065. this._activeRenderLoops = new Array();
  12066. // Deterministic lockstepMaxSteps
  12067. this._deterministicLockstep = false;
  12068. this._lockstepMaxSteps = 4;
  12069. // Lost context
  12070. /**
  12071. * Observable signaled when a context lost event is raised
  12072. */
  12073. this.onContextLostObservable = new BABYLON.Observable();
  12074. /**
  12075. * Observable signaled when a context restored event is raised
  12076. */
  12077. this.onContextRestoredObservable = new BABYLON.Observable();
  12078. this._contextWasLost = false;
  12079. this._doNotHandleContextLost = false;
  12080. // FPS
  12081. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12082. this._fps = 60;
  12083. this._deltaTime = 0;
  12084. /**
  12085. * Turn this value on if you want to pause FPS computation when in background
  12086. */
  12087. this.disablePerformanceMonitorInBackground = false;
  12088. // States
  12089. /** @hidden */
  12090. this._depthCullingState = new BABYLON._DepthCullingState();
  12091. /** @hidden */
  12092. this._stencilState = new BABYLON._StencilState();
  12093. /** @hidden */
  12094. this._alphaState = new BABYLON._AlphaState();
  12095. /** @hidden */
  12096. this._alphaMode = Engine.ALPHA_DISABLE;
  12097. // Cache
  12098. this._internalTexturesCache = new Array();
  12099. /** @hidden */
  12100. this._activeChannel = 0;
  12101. this._currentTextureChannel = -1;
  12102. /** @hidden */
  12103. this._boundTexturesCache = {};
  12104. this._compiledEffects = {};
  12105. this._vertexAttribArraysEnabled = [];
  12106. this._uintIndicesCurrentlySet = false;
  12107. this._currentBoundBuffer = new Array();
  12108. /** @hidden */
  12109. this._currentFramebuffer = null;
  12110. this._currentBufferPointers = new Array();
  12111. this._currentInstanceLocations = new Array();
  12112. this._currentInstanceBuffers = new Array();
  12113. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12114. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12115. this._vaoRecordInProgress = false;
  12116. this._mustWipeVertexAttributes = false;
  12117. this._nextFreeTextureSlots = new Array();
  12118. this._maxSimultaneousTextures = 0;
  12119. this._activeRequests = new Array();
  12120. // Hardware supported Compressed Textures
  12121. this._texturesSupported = new Array();
  12122. /**
  12123. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12124. */
  12125. this.premultipliedAlpha = true;
  12126. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12127. this._onVRFullScreenTriggered = function () {
  12128. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12129. //get the old size before we change
  12130. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12131. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12132. //get the width and height, change the render size
  12133. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12134. _this.setHardwareScalingLevel(1);
  12135. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12136. }
  12137. else {
  12138. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12139. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12140. }
  12141. };
  12142. this._unpackFlipYCached = null;
  12143. /**
  12144. * In case you are sharing the context with other applications, it might
  12145. * be interested to not cache the unpack flip y state to ensure a consistent
  12146. * value would be set.
  12147. */
  12148. this.enableUnpackFlipYCached = true;
  12149. this._boundUniforms = {};
  12150. // Register promises
  12151. BABYLON.PromisePolyfill.Apply();
  12152. var canvas = null;
  12153. Engine.Instances.push(this);
  12154. if (!canvasOrContext) {
  12155. return;
  12156. }
  12157. options = options || {};
  12158. if (canvasOrContext.getContext) {
  12159. canvas = canvasOrContext;
  12160. this._renderingCanvas = canvas;
  12161. if (antialias != null) {
  12162. options.antialias = antialias;
  12163. }
  12164. if (options.deterministicLockstep === undefined) {
  12165. options.deterministicLockstep = false;
  12166. }
  12167. if (options.lockstepMaxSteps === undefined) {
  12168. options.lockstepMaxSteps = 4;
  12169. }
  12170. if (options.preserveDrawingBuffer === undefined) {
  12171. options.preserveDrawingBuffer = false;
  12172. }
  12173. if (options.audioEngine === undefined) {
  12174. options.audioEngine = true;
  12175. }
  12176. if (options.stencil === undefined) {
  12177. options.stencil = true;
  12178. }
  12179. if (options.premultipliedAlpha === false) {
  12180. this.premultipliedAlpha = false;
  12181. }
  12182. this._deterministicLockstep = options.deterministicLockstep;
  12183. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12184. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12185. // Exceptions
  12186. if (navigator && navigator.userAgent) {
  12187. var ua = navigator.userAgent;
  12188. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12189. var exception = _a[_i];
  12190. var key = exception.key;
  12191. var targets = exception.targets;
  12192. if (ua.indexOf(key) > -1) {
  12193. if (exception.capture && exception.captureConstraint) {
  12194. var capture = exception.capture;
  12195. var constraint = exception.captureConstraint;
  12196. var regex = new RegExp(capture);
  12197. var matches = regex.exec(ua);
  12198. if (matches && matches.length > 0) {
  12199. var capturedValue = parseInt(matches[matches.length - 1]);
  12200. if (capturedValue >= constraint) {
  12201. continue;
  12202. }
  12203. }
  12204. }
  12205. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12206. var target = targets_1[_b];
  12207. switch (target) {
  12208. case "uniformBuffer":
  12209. this.disableUniformBuffers = true;
  12210. break;
  12211. case "textureBindingOptimization":
  12212. this.disableTextureBindingOptimization = true;
  12213. break;
  12214. }
  12215. }
  12216. }
  12217. }
  12218. }
  12219. // GL
  12220. if (!options.disableWebGL2Support) {
  12221. try {
  12222. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12223. if (this._gl) {
  12224. this._webGLVersion = 2.0;
  12225. }
  12226. }
  12227. catch (e) {
  12228. // Do nothing
  12229. }
  12230. }
  12231. if (!this._gl) {
  12232. if (!canvas) {
  12233. throw new Error("The provided canvas is null or undefined.");
  12234. }
  12235. try {
  12236. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12237. }
  12238. catch (e) {
  12239. throw new Error("WebGL not supported");
  12240. }
  12241. }
  12242. if (!this._gl) {
  12243. throw new Error("WebGL not supported");
  12244. }
  12245. this._onCanvasFocus = function () {
  12246. _this.onCanvasFocusObservable.notifyObservers(_this);
  12247. };
  12248. this._onCanvasBlur = function () {
  12249. _this.onCanvasBlurObservable.notifyObservers(_this);
  12250. };
  12251. canvas.addEventListener("focus", this._onCanvasFocus);
  12252. canvas.addEventListener("blur", this._onCanvasBlur);
  12253. this._onBlur = function () {
  12254. if (_this.disablePerformanceMonitorInBackground) {
  12255. _this._performanceMonitor.disable();
  12256. }
  12257. _this._windowIsBackground = true;
  12258. };
  12259. this._onFocus = function () {
  12260. if (_this.disablePerformanceMonitorInBackground) {
  12261. _this._performanceMonitor.enable();
  12262. }
  12263. _this._windowIsBackground = false;
  12264. };
  12265. this._onCanvasPointerOut = function (ev) {
  12266. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12267. };
  12268. window.addEventListener("blur", this._onBlur);
  12269. window.addEventListener("focus", this._onFocus);
  12270. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12271. // Context lost
  12272. if (!this._doNotHandleContextLost) {
  12273. this._onContextLost = function (evt) {
  12274. evt.preventDefault();
  12275. _this._contextWasLost = true;
  12276. BABYLON.Tools.Warn("WebGL context lost.");
  12277. _this.onContextLostObservable.notifyObservers(_this);
  12278. };
  12279. this._onContextRestored = function (evt) {
  12280. // Adding a timeout to avoid race condition at browser level
  12281. setTimeout(function () {
  12282. // Rebuild gl context
  12283. _this._initGLContext();
  12284. // Rebuild effects
  12285. _this._rebuildEffects();
  12286. // Rebuild textures
  12287. _this._rebuildInternalTextures();
  12288. // Rebuild buffers
  12289. _this._rebuildBuffers();
  12290. // Cache
  12291. _this.wipeCaches(true);
  12292. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12293. _this.onContextRestoredObservable.notifyObservers(_this);
  12294. _this._contextWasLost = false;
  12295. }, 0);
  12296. };
  12297. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12298. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12299. }
  12300. }
  12301. else {
  12302. this._gl = canvasOrContext;
  12303. this._renderingCanvas = this._gl.canvas;
  12304. if (this._gl.renderbufferStorageMultisample) {
  12305. this._webGLVersion = 2.0;
  12306. }
  12307. options.stencil = this._gl.getContextAttributes().stencil;
  12308. }
  12309. // Viewport
  12310. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12311. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12312. this.resize();
  12313. this._isStencilEnable = options.stencil ? true : false;
  12314. this._initGLContext();
  12315. if (canvas) {
  12316. // Fullscreen
  12317. this._onFullscreenChange = function () {
  12318. if (document.fullscreen !== undefined) {
  12319. _this.isFullscreen = document.fullscreen;
  12320. }
  12321. else if (document.mozFullScreen !== undefined) {
  12322. _this.isFullscreen = document.mozFullScreen;
  12323. }
  12324. else if (document.webkitIsFullScreen !== undefined) {
  12325. _this.isFullscreen = document.webkitIsFullScreen;
  12326. }
  12327. else if (document.msIsFullScreen !== undefined) {
  12328. _this.isFullscreen = document.msIsFullScreen;
  12329. }
  12330. // Pointer lock
  12331. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12332. canvas.requestPointerLock = canvas.requestPointerLock ||
  12333. canvas.msRequestPointerLock ||
  12334. canvas.mozRequestPointerLock ||
  12335. canvas.webkitRequestPointerLock;
  12336. if (canvas.requestPointerLock) {
  12337. canvas.requestPointerLock();
  12338. }
  12339. }
  12340. };
  12341. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12342. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12343. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12344. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12345. // Pointer lock
  12346. this._onPointerLockChange = function () {
  12347. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12348. document.webkitPointerLockElement === canvas ||
  12349. document.msPointerLockElement === canvas ||
  12350. document.pointerLockElement === canvas);
  12351. };
  12352. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12353. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12354. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12355. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12356. this._onVRDisplayPointerRestricted = function () {
  12357. if (canvas) {
  12358. canvas.requestPointerLock();
  12359. }
  12360. };
  12361. this._onVRDisplayPointerUnrestricted = function () {
  12362. document.exitPointerLock();
  12363. };
  12364. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12365. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12366. }
  12367. // Create Audio Engine if needed.
  12368. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12369. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12370. }
  12371. // Prepare buffer pointers
  12372. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12373. this._currentBufferPointers[i] = new BufferPointer();
  12374. }
  12375. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12376. // Load WebVR Devices
  12377. if (options.autoEnableWebVR) {
  12378. this.initWebVR();
  12379. }
  12380. // Detect if we are running on a faulty buggy OS.
  12381. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12382. // Detect if we are running on a faulty buggy desktop OS.
  12383. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12384. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12385. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12386. }
  12387. Object.defineProperty(Engine, "LastCreatedEngine", {
  12388. /**
  12389. * Gets the latest created engine
  12390. */
  12391. get: function () {
  12392. if (Engine.Instances.length === 0) {
  12393. return null;
  12394. }
  12395. return Engine.Instances[Engine.Instances.length - 1];
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. Object.defineProperty(Engine, "LastCreatedScene", {
  12401. /**
  12402. * Gets the latest created scene
  12403. */
  12404. get: function () {
  12405. var lastCreatedEngine = Engine.LastCreatedEngine;
  12406. if (!lastCreatedEngine) {
  12407. return null;
  12408. }
  12409. if (lastCreatedEngine.scenes.length === 0) {
  12410. return null;
  12411. }
  12412. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12413. },
  12414. enumerable: true,
  12415. configurable: true
  12416. });
  12417. /**
  12418. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12419. * @param flag defines which part of the materials must be marked as dirty
  12420. * @param predicate defines a predicate used to filter which materials should be affected
  12421. */
  12422. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12423. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12424. var engine = Engine.Instances[engineIndex];
  12425. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12426. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12427. }
  12428. }
  12429. };
  12430. Object.defineProperty(Engine, "Version", {
  12431. /**
  12432. * Returns the current version of the framework
  12433. */
  12434. get: function () {
  12435. return "3.3.0-rc.2";
  12436. },
  12437. enumerable: true,
  12438. configurable: true
  12439. });
  12440. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12441. /**
  12442. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12443. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12444. */
  12445. get: function () {
  12446. return this._vrExclusivePointerMode;
  12447. },
  12448. enumerable: true,
  12449. configurable: true
  12450. });
  12451. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12452. /**
  12453. * Gets a boolean indicating that the engine supports uniform buffers
  12454. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12455. */
  12456. get: function () {
  12457. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12458. },
  12459. enumerable: true,
  12460. configurable: true
  12461. });
  12462. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12463. /**
  12464. * Gets a boolean indicating that only power of 2 textures are supported
  12465. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12466. */
  12467. get: function () {
  12468. return this._webGLVersion < 2 || this.forcePOTTextures;
  12469. },
  12470. enumerable: true,
  12471. configurable: true
  12472. });
  12473. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12474. /**
  12475. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12476. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12477. */
  12478. get: function () {
  12479. return this._doNotHandleContextLost;
  12480. },
  12481. set: function (value) {
  12482. this._doNotHandleContextLost = value;
  12483. },
  12484. enumerable: true,
  12485. configurable: true
  12486. });
  12487. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12488. /**
  12489. * Gets the performance monitor attached to this engine
  12490. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12491. */
  12492. get: function () {
  12493. return this._performanceMonitor;
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12499. /**
  12500. * Gets the list of texture formats supported
  12501. */
  12502. get: function () {
  12503. return this._texturesSupported;
  12504. },
  12505. enumerable: true,
  12506. configurable: true
  12507. });
  12508. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12509. /**
  12510. * Gets the list of texture formats in use
  12511. */
  12512. get: function () {
  12513. return this._textureFormatInUse;
  12514. },
  12515. enumerable: true,
  12516. configurable: true
  12517. });
  12518. Object.defineProperty(Engine.prototype, "currentViewport", {
  12519. /**
  12520. * Gets the current viewport
  12521. */
  12522. get: function () {
  12523. return this._cachedViewport;
  12524. },
  12525. enumerable: true,
  12526. configurable: true
  12527. });
  12528. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12529. /**
  12530. * Gets the default empty texture
  12531. */
  12532. get: function () {
  12533. if (!this._emptyTexture) {
  12534. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12535. }
  12536. return this._emptyTexture;
  12537. },
  12538. enumerable: true,
  12539. configurable: true
  12540. });
  12541. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12542. /**
  12543. * Gets the default empty 3D texture
  12544. */
  12545. get: function () {
  12546. if (!this._emptyTexture3D) {
  12547. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12548. }
  12549. return this._emptyTexture3D;
  12550. },
  12551. enumerable: true,
  12552. configurable: true
  12553. });
  12554. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12555. /**
  12556. * Gets the default empty cube texture
  12557. */
  12558. get: function () {
  12559. if (!this._emptyCubeTexture) {
  12560. var faceData = new Uint8Array(4);
  12561. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12562. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12563. }
  12564. return this._emptyCubeTexture;
  12565. },
  12566. enumerable: true,
  12567. configurable: true
  12568. });
  12569. Engine.prototype._rebuildInternalTextures = function () {
  12570. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12571. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12572. var internalTexture = currentState_1[_i];
  12573. internalTexture._rebuild();
  12574. }
  12575. };
  12576. Engine.prototype._rebuildEffects = function () {
  12577. for (var key in this._compiledEffects) {
  12578. var effect = this._compiledEffects[key];
  12579. effect._prepareEffect();
  12580. }
  12581. BABYLON.Effect.ResetCache();
  12582. };
  12583. Engine.prototype._rebuildBuffers = function () {
  12584. // Index / Vertex
  12585. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12586. var scene = _a[_i];
  12587. scene.resetCachedMaterial();
  12588. scene._rebuildGeometries();
  12589. scene._rebuildTextures();
  12590. }
  12591. // Uniforms
  12592. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12593. var uniformBuffer = _c[_b];
  12594. uniformBuffer._rebuild();
  12595. }
  12596. };
  12597. Engine.prototype._initGLContext = function () {
  12598. // Caps
  12599. this._caps = new EngineCapabilities();
  12600. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12601. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12602. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12603. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12604. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12605. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12606. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12607. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12608. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12609. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12610. // Infos
  12611. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12612. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12613. if (rendererInfo != null) {
  12614. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12615. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12616. }
  12617. if (!this._glVendor) {
  12618. this._glVendor = "Unknown vendor";
  12619. }
  12620. if (!this._glRenderer) {
  12621. this._glRenderer = "Unknown renderer";
  12622. }
  12623. // Constants
  12624. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12625. if (this._gl.RGBA16F !== 0x881A) {
  12626. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12627. }
  12628. if (this._gl.RGBA32F !== 0x8814) {
  12629. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12630. }
  12631. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12632. this._gl.DEPTH24_STENCIL8 = 35056;
  12633. }
  12634. // Extensions
  12635. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12636. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12637. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12638. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12639. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12640. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12641. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12642. 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');
  12643. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12644. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12645. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12646. this._caps.highPrecisionShaderSupported = true;
  12647. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12648. if (this._caps.timerQuery) {
  12649. if (this._webGLVersion === 1) {
  12650. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12651. }
  12652. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12653. }
  12654. // Checks if some of the format renders first to allow the use of webgl inspector.
  12655. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12656. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12657. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12658. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12659. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12660. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12661. if (this._webGLVersion > 1) {
  12662. this._gl.HALF_FLOAT_OES = 0x140B;
  12663. }
  12664. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12665. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12666. // Draw buffers
  12667. if (this._webGLVersion > 1) {
  12668. this._caps.drawBuffersExtension = true;
  12669. }
  12670. else {
  12671. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12672. if (drawBuffersExtension !== null) {
  12673. this._caps.drawBuffersExtension = true;
  12674. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12675. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12676. for (var i = 0; i < 16; i++) {
  12677. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12678. }
  12679. }
  12680. else {
  12681. this._caps.drawBuffersExtension = false;
  12682. }
  12683. }
  12684. // Depth Texture
  12685. if (this._webGLVersion > 1) {
  12686. this._caps.depthTextureExtension = true;
  12687. }
  12688. else {
  12689. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12690. if (depthTextureExtension != null) {
  12691. this._caps.depthTextureExtension = true;
  12692. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12693. }
  12694. }
  12695. // Vertex array object
  12696. if (this._webGLVersion > 1) {
  12697. this._caps.vertexArrayObject = true;
  12698. }
  12699. else {
  12700. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12701. if (vertexArrayObjectExtension != null) {
  12702. this._caps.vertexArrayObject = true;
  12703. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12704. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12705. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12706. }
  12707. else {
  12708. this._caps.vertexArrayObject = false;
  12709. }
  12710. }
  12711. // Instances count
  12712. if (this._webGLVersion > 1) {
  12713. this._caps.instancedArrays = true;
  12714. }
  12715. else {
  12716. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12717. if (instanceExtension != null) {
  12718. this._caps.instancedArrays = true;
  12719. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12720. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12721. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12722. }
  12723. else {
  12724. this._caps.instancedArrays = false;
  12725. }
  12726. }
  12727. // Intelligently add supported compressed formats in order to check for.
  12728. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12729. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12730. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12731. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12732. if (this._caps.astc)
  12733. this.texturesSupported.push('-astc.ktx');
  12734. if (this._caps.s3tc)
  12735. this.texturesSupported.push('-dxt.ktx');
  12736. if (this._caps.pvrtc)
  12737. this.texturesSupported.push('-pvrtc.ktx');
  12738. if (this._caps.etc2)
  12739. this.texturesSupported.push('-etc2.ktx');
  12740. if (this._caps.etc1)
  12741. this.texturesSupported.push('-etc1.ktx');
  12742. if (this._gl.getShaderPrecisionFormat) {
  12743. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12744. if (highp) {
  12745. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12746. }
  12747. }
  12748. // Depth buffer
  12749. this.setDepthBuffer(true);
  12750. this.setDepthFunctionToLessOrEqual();
  12751. this.setDepthWrite(true);
  12752. // Texture maps
  12753. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12754. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12755. this._nextFreeTextureSlots.push(slot);
  12756. }
  12757. };
  12758. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12759. /**
  12760. * Gets version of the current webGL context
  12761. */
  12762. get: function () {
  12763. return this._webGLVersion;
  12764. },
  12765. enumerable: true,
  12766. configurable: true
  12767. });
  12768. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12769. /**
  12770. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12771. */
  12772. get: function () {
  12773. return this._isStencilEnable;
  12774. },
  12775. enumerable: true,
  12776. configurable: true
  12777. });
  12778. Engine.prototype._prepareWorkingCanvas = function () {
  12779. if (this._workingCanvas) {
  12780. return;
  12781. }
  12782. this._workingCanvas = document.createElement("canvas");
  12783. var context = this._workingCanvas.getContext("2d");
  12784. if (context) {
  12785. this._workingContext = context;
  12786. }
  12787. };
  12788. /**
  12789. * Reset the texture cache to empty state
  12790. */
  12791. Engine.prototype.resetTextureCache = function () {
  12792. for (var key in this._boundTexturesCache) {
  12793. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12794. continue;
  12795. }
  12796. var boundTexture = this._boundTexturesCache[key];
  12797. if (boundTexture) {
  12798. this._removeDesignatedSlot(boundTexture);
  12799. }
  12800. this._boundTexturesCache[key] = null;
  12801. }
  12802. if (!this.disableTextureBindingOptimization) {
  12803. this._nextFreeTextureSlots = [];
  12804. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12805. this._nextFreeTextureSlots.push(slot);
  12806. }
  12807. }
  12808. this._currentTextureChannel = -1;
  12809. };
  12810. /**
  12811. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12812. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12813. * @returns true if engine is in deterministic lock step mode
  12814. */
  12815. Engine.prototype.isDeterministicLockStep = function () {
  12816. return this._deterministicLockstep;
  12817. };
  12818. /**
  12819. * Gets the max steps when engine is running in deterministic lock step
  12820. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12821. * @returns the max steps
  12822. */
  12823. Engine.prototype.getLockstepMaxSteps = function () {
  12824. return this._lockstepMaxSteps;
  12825. };
  12826. /**
  12827. * Gets an object containing information about the current webGL context
  12828. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12829. */
  12830. Engine.prototype.getGlInfo = function () {
  12831. return {
  12832. vendor: this._glVendor,
  12833. renderer: this._glRenderer,
  12834. version: this._glVersion
  12835. };
  12836. };
  12837. /**
  12838. * Gets current aspect ratio
  12839. * @param camera defines the camera to use to get the aspect ratio
  12840. * @param useScreen defines if screen size must be used (or the current render target if any)
  12841. * @returns a number defining the aspect ratio
  12842. */
  12843. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12844. if (useScreen === void 0) { useScreen = false; }
  12845. var viewport = camera.viewport;
  12846. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12847. };
  12848. /**
  12849. * Gets current screen aspect ratio
  12850. * @returns a number defining the aspect ratio
  12851. */
  12852. Engine.prototype.getScreenAspectRatio = function () {
  12853. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12854. };
  12855. /**
  12856. * Gets the current render width
  12857. * @param useScreen defines if screen size must be used (or the current render target if any)
  12858. * @returns a number defining the current render width
  12859. */
  12860. Engine.prototype.getRenderWidth = function (useScreen) {
  12861. if (useScreen === void 0) { useScreen = false; }
  12862. if (!useScreen && this._currentRenderTarget) {
  12863. return this._currentRenderTarget.width;
  12864. }
  12865. return this._gl.drawingBufferWidth;
  12866. };
  12867. /**
  12868. * Gets the current render height
  12869. * @param useScreen defines if screen size must be used (or the current render target if any)
  12870. * @returns a number defining the current render height
  12871. */
  12872. Engine.prototype.getRenderHeight = function (useScreen) {
  12873. if (useScreen === void 0) { useScreen = false; }
  12874. if (!useScreen && this._currentRenderTarget) {
  12875. return this._currentRenderTarget.height;
  12876. }
  12877. return this._gl.drawingBufferHeight;
  12878. };
  12879. /**
  12880. * Gets the HTML canvas attached with the current webGL context
  12881. * @returns a HTML canvas
  12882. */
  12883. Engine.prototype.getRenderingCanvas = function () {
  12884. return this._renderingCanvas;
  12885. };
  12886. /**
  12887. * Gets the client rect of the HTML canvas attached with the current webGL context
  12888. * @returns a client rectanglee
  12889. */
  12890. Engine.prototype.getRenderingCanvasClientRect = function () {
  12891. if (!this._renderingCanvas) {
  12892. return null;
  12893. }
  12894. return this._renderingCanvas.getBoundingClientRect();
  12895. };
  12896. /**
  12897. * Defines the hardware scaling level.
  12898. * By default the hardware scaling level is computed from the window device ratio.
  12899. * 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.
  12900. * @param level defines the level to use
  12901. */
  12902. Engine.prototype.setHardwareScalingLevel = function (level) {
  12903. this._hardwareScalingLevel = level;
  12904. this.resize();
  12905. };
  12906. /**
  12907. * Gets the current hardware scaling level.
  12908. * By default the hardware scaling level is computed from the window device ratio.
  12909. * 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.
  12910. * @returns a number indicating the current hardware scaling level
  12911. */
  12912. Engine.prototype.getHardwareScalingLevel = function () {
  12913. return this._hardwareScalingLevel;
  12914. };
  12915. /**
  12916. * Gets the list of loaded textures
  12917. * @returns an array containing all loaded textures
  12918. */
  12919. Engine.prototype.getLoadedTexturesCache = function () {
  12920. return this._internalTexturesCache;
  12921. };
  12922. /**
  12923. * Gets the object containing all engine capabilities
  12924. * @returns the EngineCapabilities object
  12925. */
  12926. Engine.prototype.getCaps = function () {
  12927. return this._caps;
  12928. };
  12929. Object.defineProperty(Engine.prototype, "drawCalls", {
  12930. /** @hidden */
  12931. get: function () {
  12932. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12933. return 0;
  12934. },
  12935. enumerable: true,
  12936. configurable: true
  12937. });
  12938. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12939. /** @hidden */
  12940. get: function () {
  12941. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12942. return null;
  12943. },
  12944. enumerable: true,
  12945. configurable: true
  12946. });
  12947. /**
  12948. * Gets the current depth function
  12949. * @returns a number defining the depth function
  12950. */
  12951. Engine.prototype.getDepthFunction = function () {
  12952. return this._depthCullingState.depthFunc;
  12953. };
  12954. /**
  12955. * Sets the current depth function
  12956. * @param depthFunc defines the function to use
  12957. */
  12958. Engine.prototype.setDepthFunction = function (depthFunc) {
  12959. this._depthCullingState.depthFunc = depthFunc;
  12960. };
  12961. /**
  12962. * Sets the current depth function to GREATER
  12963. */
  12964. Engine.prototype.setDepthFunctionToGreater = function () {
  12965. this._depthCullingState.depthFunc = this._gl.GREATER;
  12966. };
  12967. /**
  12968. * Sets the current depth function to GEQUAL
  12969. */
  12970. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12971. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12972. };
  12973. /**
  12974. * Sets the current depth function to LESS
  12975. */
  12976. Engine.prototype.setDepthFunctionToLess = function () {
  12977. this._depthCullingState.depthFunc = this._gl.LESS;
  12978. };
  12979. /**
  12980. * Sets the current depth function to LEQUAL
  12981. */
  12982. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12983. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12984. };
  12985. /**
  12986. * Gets a boolean indicating if stencil buffer is enabled
  12987. * @returns the current stencil buffer state
  12988. */
  12989. Engine.prototype.getStencilBuffer = function () {
  12990. return this._stencilState.stencilTest;
  12991. };
  12992. /**
  12993. * Enable or disable the stencil buffer
  12994. * @param enable defines if the stencil buffer must be enabled or disabled
  12995. */
  12996. Engine.prototype.setStencilBuffer = function (enable) {
  12997. this._stencilState.stencilTest = enable;
  12998. };
  12999. /**
  13000. * Gets the current stencil mask
  13001. * @returns a number defining the new stencil mask to use
  13002. */
  13003. Engine.prototype.getStencilMask = function () {
  13004. return this._stencilState.stencilMask;
  13005. };
  13006. /**
  13007. * Sets the current stencil mask
  13008. * @param mask defines the new stencil mask to use
  13009. */
  13010. Engine.prototype.setStencilMask = function (mask) {
  13011. this._stencilState.stencilMask = mask;
  13012. };
  13013. /**
  13014. * Gets the current stencil function
  13015. * @returns a number defining the stencil function to use
  13016. */
  13017. Engine.prototype.getStencilFunction = function () {
  13018. return this._stencilState.stencilFunc;
  13019. };
  13020. /**
  13021. * Gets the current stencil reference value
  13022. * @returns a number defining the stencil reference value to use
  13023. */
  13024. Engine.prototype.getStencilFunctionReference = function () {
  13025. return this._stencilState.stencilFuncRef;
  13026. };
  13027. /**
  13028. * Gets the current stencil mask
  13029. * @returns a number defining the stencil mask to use
  13030. */
  13031. Engine.prototype.getStencilFunctionMask = function () {
  13032. return this._stencilState.stencilFuncMask;
  13033. };
  13034. /**
  13035. * Sets the current stencil function
  13036. * @param stencilFunc defines the new stencil function to use
  13037. */
  13038. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13039. this._stencilState.stencilFunc = stencilFunc;
  13040. };
  13041. /**
  13042. * Sets the current stencil reference
  13043. * @param reference defines the new stencil reference to use
  13044. */
  13045. Engine.prototype.setStencilFunctionReference = function (reference) {
  13046. this._stencilState.stencilFuncRef = reference;
  13047. };
  13048. /**
  13049. * Sets the current stencil mask
  13050. * @param mask defines the new stencil mask to use
  13051. */
  13052. Engine.prototype.setStencilFunctionMask = function (mask) {
  13053. this._stencilState.stencilFuncMask = mask;
  13054. };
  13055. /**
  13056. * Gets the current stencil operation when stencil fails
  13057. * @returns a number defining stencil operation to use when stencil fails
  13058. */
  13059. Engine.prototype.getStencilOperationFail = function () {
  13060. return this._stencilState.stencilOpStencilFail;
  13061. };
  13062. /**
  13063. * Gets the current stencil operation when depth fails
  13064. * @returns a number defining stencil operation to use when depth fails
  13065. */
  13066. Engine.prototype.getStencilOperationDepthFail = function () {
  13067. return this._stencilState.stencilOpDepthFail;
  13068. };
  13069. /**
  13070. * Gets the current stencil operation when stencil passes
  13071. * @returns a number defining stencil operation to use when stencil passes
  13072. */
  13073. Engine.prototype.getStencilOperationPass = function () {
  13074. return this._stencilState.stencilOpStencilDepthPass;
  13075. };
  13076. /**
  13077. * Sets the stencil operation to use when stencil fails
  13078. * @param operation defines the stencil operation to use when stencil fails
  13079. */
  13080. Engine.prototype.setStencilOperationFail = function (operation) {
  13081. this._stencilState.stencilOpStencilFail = operation;
  13082. };
  13083. /**
  13084. * Sets the stencil operation to use when depth fails
  13085. * @param operation defines the stencil operation to use when depth fails
  13086. */
  13087. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13088. this._stencilState.stencilOpDepthFail = operation;
  13089. };
  13090. /**
  13091. * Sets the stencil operation to use when stencil passes
  13092. * @param operation defines the stencil operation to use when stencil passes
  13093. */
  13094. Engine.prototype.setStencilOperationPass = function (operation) {
  13095. this._stencilState.stencilOpStencilDepthPass = operation;
  13096. };
  13097. /**
  13098. * Sets a boolean indicating if the dithering state is enabled or disabled
  13099. * @param value defines the dithering state
  13100. */
  13101. Engine.prototype.setDitheringState = function (value) {
  13102. if (value) {
  13103. this._gl.enable(this._gl.DITHER);
  13104. }
  13105. else {
  13106. this._gl.disable(this._gl.DITHER);
  13107. }
  13108. };
  13109. /**
  13110. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13111. * @param value defines the rasterizer state
  13112. */
  13113. Engine.prototype.setRasterizerState = function (value) {
  13114. if (value) {
  13115. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13116. }
  13117. else {
  13118. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13119. }
  13120. };
  13121. /**
  13122. * stop executing a render loop function and remove it from the execution array
  13123. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13124. */
  13125. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13126. if (!renderFunction) {
  13127. this._activeRenderLoops = [];
  13128. return;
  13129. }
  13130. var index = this._activeRenderLoops.indexOf(renderFunction);
  13131. if (index >= 0) {
  13132. this._activeRenderLoops.splice(index, 1);
  13133. }
  13134. };
  13135. /** @hidden */
  13136. Engine.prototype._renderLoop = function () {
  13137. if (!this._contextWasLost) {
  13138. var shouldRender = true;
  13139. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13140. shouldRender = false;
  13141. }
  13142. if (shouldRender) {
  13143. // Start new frame
  13144. this.beginFrame();
  13145. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13146. var renderFunction = this._activeRenderLoops[index];
  13147. renderFunction();
  13148. }
  13149. // Present
  13150. this.endFrame();
  13151. }
  13152. }
  13153. if (this._activeRenderLoops.length > 0) {
  13154. // Register new frame
  13155. var requester = null;
  13156. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13157. requester = this._vrDisplay;
  13158. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13159. }
  13160. else {
  13161. this._renderingQueueLaunched = false;
  13162. }
  13163. };
  13164. /**
  13165. * Register and execute a render loop. The engine can have more than one render function
  13166. * @param renderFunction defines the function to continuously execute
  13167. */
  13168. Engine.prototype.runRenderLoop = function (renderFunction) {
  13169. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13170. return;
  13171. }
  13172. this._activeRenderLoops.push(renderFunction);
  13173. if (!this._renderingQueueLaunched) {
  13174. this._renderingQueueLaunched = true;
  13175. this._bindedRenderFunction = this._renderLoop.bind(this);
  13176. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13177. }
  13178. };
  13179. /**
  13180. * Toggle full screen mode
  13181. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13182. */
  13183. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13184. if (this.isFullscreen) {
  13185. BABYLON.Tools.ExitFullscreen();
  13186. }
  13187. else {
  13188. this._pointerLockRequested = requestPointerLock;
  13189. if (this._renderingCanvas) {
  13190. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13191. }
  13192. }
  13193. };
  13194. /**
  13195. * Clear the current render buffer or the current render target (if any is set up)
  13196. * @param color defines the color to use
  13197. * @param backBuffer defines if the back buffer must be cleared
  13198. * @param depth defines if the depth buffer must be cleared
  13199. * @param stencil defines if the stencil buffer must be cleared
  13200. */
  13201. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13202. if (stencil === void 0) { stencil = false; }
  13203. this.applyStates();
  13204. var mode = 0;
  13205. if (backBuffer && color) {
  13206. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13207. mode |= this._gl.COLOR_BUFFER_BIT;
  13208. }
  13209. if (depth) {
  13210. this._gl.clearDepth(1.0);
  13211. mode |= this._gl.DEPTH_BUFFER_BIT;
  13212. }
  13213. if (stencil) {
  13214. this._gl.clearStencil(0);
  13215. mode |= this._gl.STENCIL_BUFFER_BIT;
  13216. }
  13217. this._gl.clear(mode);
  13218. };
  13219. /**
  13220. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13221. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13222. * @param y defines the y-coordinate of the corner of the clear rectangle
  13223. * @param width defines the width of the clear rectangle
  13224. * @param height defines the height of the clear rectangle
  13225. * @param clearColor defines the clear color
  13226. */
  13227. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13228. var gl = this._gl;
  13229. // Save state
  13230. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13231. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13232. // Change state
  13233. gl.enable(gl.SCISSOR_TEST);
  13234. gl.scissor(x, y, width, height);
  13235. // Clear
  13236. this.clear(clearColor, true, true, true);
  13237. // Restore state
  13238. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13239. if (curScissor === true) {
  13240. gl.enable(gl.SCISSOR_TEST);
  13241. }
  13242. else {
  13243. gl.disable(gl.SCISSOR_TEST);
  13244. }
  13245. };
  13246. /** @hidden */
  13247. Engine.prototype._viewport = function (x, y, width, height) {
  13248. if (x !== this._viewportCached.x ||
  13249. y !== this._viewportCached.y ||
  13250. width !== this._viewportCached.z ||
  13251. height !== this._viewportCached.w) {
  13252. this._viewportCached.x = x;
  13253. this._viewportCached.y = y;
  13254. this._viewportCached.z = width;
  13255. this._viewportCached.w = height;
  13256. this._gl.viewport(x, y, width, height);
  13257. }
  13258. };
  13259. /**
  13260. * Set the WebGL's viewport
  13261. * @param viewport defines the viewport element to be used
  13262. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13263. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13264. */
  13265. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13266. var width = requiredWidth || this.getRenderWidth();
  13267. var height = requiredHeight || this.getRenderHeight();
  13268. var x = viewport.x || 0;
  13269. var y = viewport.y || 0;
  13270. this._cachedViewport = viewport;
  13271. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13272. };
  13273. /**
  13274. * Directly set the WebGL Viewport
  13275. * @param x defines the x coordinate of the viewport (in screen space)
  13276. * @param y defines the y coordinate of the viewport (in screen space)
  13277. * @param width defines the width of the viewport (in screen space)
  13278. * @param height defines the height of the viewport (in screen space)
  13279. * @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
  13280. */
  13281. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13282. var currentViewport = this._cachedViewport;
  13283. this._cachedViewport = null;
  13284. this._viewport(x, y, width, height);
  13285. return currentViewport;
  13286. };
  13287. /**
  13288. * Begin a new frame
  13289. */
  13290. Engine.prototype.beginFrame = function () {
  13291. this.onBeginFrameObservable.notifyObservers(this);
  13292. this._measureFps();
  13293. };
  13294. /**
  13295. * Enf the current frame
  13296. */
  13297. Engine.prototype.endFrame = function () {
  13298. // Force a flush in case we are using a bad OS.
  13299. if (this._badOS) {
  13300. this.flushFramebuffer();
  13301. }
  13302. // Submit frame to the vr device, if enabled
  13303. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13304. // TODO: We should only submit the frame if we read frameData successfully.
  13305. this._vrDisplay.submitFrame();
  13306. }
  13307. this.onEndFrameObservable.notifyObservers(this);
  13308. };
  13309. /**
  13310. * Resize the view according to the canvas' size
  13311. */
  13312. Engine.prototype.resize = function () {
  13313. // We're not resizing the size of the canvas while in VR mode & presenting
  13314. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13315. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13316. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13317. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13318. }
  13319. };
  13320. /**
  13321. * Force a specific size of the canvas
  13322. * @param width defines the new canvas' width
  13323. * @param height defines the new canvas' height
  13324. */
  13325. Engine.prototype.setSize = function (width, height) {
  13326. if (!this._renderingCanvas) {
  13327. return;
  13328. }
  13329. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13330. return;
  13331. }
  13332. this._renderingCanvas.width = width;
  13333. this._renderingCanvas.height = height;
  13334. for (var index = 0; index < this.scenes.length; index++) {
  13335. var scene = this.scenes[index];
  13336. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13337. var cam = scene.cameras[camIndex];
  13338. cam._currentRenderId = 0;
  13339. }
  13340. }
  13341. if (this.onResizeObservable.hasObservers) {
  13342. this.onResizeObservable.notifyObservers(this);
  13343. }
  13344. };
  13345. // WebVR functions
  13346. /**
  13347. * Gets a boolean indicating if a webVR device was detected
  13348. * @returns true if a webVR device was detected
  13349. */
  13350. Engine.prototype.isVRDevicePresent = function () {
  13351. return !!this._vrDisplay;
  13352. };
  13353. /**
  13354. * Gets the current webVR device
  13355. * @returns the current webVR device (or null)
  13356. */
  13357. Engine.prototype.getVRDevice = function () {
  13358. return this._vrDisplay;
  13359. };
  13360. /**
  13361. * Initializes a webVR display and starts listening to display change events
  13362. * The onVRDisplayChangedObservable will be notified upon these changes
  13363. * @returns The onVRDisplayChangedObservable
  13364. */
  13365. Engine.prototype.initWebVR = function () {
  13366. this.initWebVRAsync();
  13367. return this.onVRDisplayChangedObservable;
  13368. };
  13369. /**
  13370. * Initializes a webVR display and starts listening to display change events
  13371. * The onVRDisplayChangedObservable will be notified upon these changes
  13372. * @returns A promise containing a VRDisplay and if vr is supported
  13373. */
  13374. Engine.prototype.initWebVRAsync = function () {
  13375. var _this = this;
  13376. var notifyObservers = function () {
  13377. var eventArgs = {
  13378. vrDisplay: _this._vrDisplay,
  13379. vrSupported: _this._vrSupported
  13380. };
  13381. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13382. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13383. };
  13384. if (!this._onVrDisplayConnect) {
  13385. this._onVrDisplayConnect = function (event) {
  13386. _this._vrDisplay = event.display;
  13387. notifyObservers();
  13388. };
  13389. this._onVrDisplayDisconnect = function () {
  13390. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13391. _this._vrDisplay = undefined;
  13392. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13393. notifyObservers();
  13394. };
  13395. this._onVrDisplayPresentChange = function () {
  13396. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13397. };
  13398. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13399. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13400. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13401. }
  13402. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13403. this._webVRInitPromise.then(notifyObservers);
  13404. return this._webVRInitPromise;
  13405. };
  13406. /**
  13407. * Call this function to switch to webVR mode
  13408. * Will do nothing if webVR is not supported or if there is no webVR device
  13409. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13410. */
  13411. Engine.prototype.enableVR = function () {
  13412. var _this = this;
  13413. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13414. var onResolved = function () {
  13415. _this.onVRRequestPresentComplete.notifyObservers(true);
  13416. _this._onVRFullScreenTriggered();
  13417. };
  13418. var onRejected = function () {
  13419. _this.onVRRequestPresentComplete.notifyObservers(false);
  13420. };
  13421. this.onVRRequestPresentStart.notifyObservers(this);
  13422. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13423. }
  13424. };
  13425. /**
  13426. * Call this function to leave webVR mode
  13427. * Will do nothing if webVR is not supported or if there is no webVR device
  13428. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13429. */
  13430. Engine.prototype.disableVR = function () {
  13431. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13432. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13433. }
  13434. };
  13435. Engine.prototype._getVRDisplaysAsync = function () {
  13436. var _this = this;
  13437. return new Promise(function (res, rej) {
  13438. if (navigator.getVRDisplays) {
  13439. navigator.getVRDisplays().then(function (devices) {
  13440. _this._vrSupported = true;
  13441. // note that devices may actually be an empty array. This is fine;
  13442. // we expect this._vrDisplay to be undefined in this case.
  13443. _this._vrDisplay = devices[0];
  13444. res({
  13445. vrDisplay: _this._vrDisplay,
  13446. vrSupported: _this._vrSupported
  13447. });
  13448. });
  13449. }
  13450. else {
  13451. _this._vrDisplay = undefined;
  13452. _this._vrSupported = false;
  13453. res({
  13454. vrDisplay: _this._vrDisplay,
  13455. vrSupported: _this._vrSupported
  13456. });
  13457. }
  13458. });
  13459. };
  13460. /**
  13461. * Binds the frame buffer to the specified texture.
  13462. * @param texture The texture to render to or null for the default canvas
  13463. * @param faceIndex The face of the texture to render to in case of cube texture
  13464. * @param requiredWidth The width of the target to render to
  13465. * @param requiredHeight The height of the target to render to
  13466. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13467. * @param depthStencilTexture The depth stencil texture to use to render
  13468. * @param lodLevel defines le lod level to bind to the frame buffer
  13469. */
  13470. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13471. if (lodLevel === void 0) { lodLevel = 0; }
  13472. if (this._currentRenderTarget) {
  13473. this.unBindFramebuffer(this._currentRenderTarget);
  13474. }
  13475. this._currentRenderTarget = texture;
  13476. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13477. var gl = this._gl;
  13478. if (texture.isCube) {
  13479. if (faceIndex === undefined) {
  13480. faceIndex = 0;
  13481. }
  13482. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13483. if (depthStencilTexture) {
  13484. if (depthStencilTexture._generateStencilBuffer) {
  13485. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13486. }
  13487. else {
  13488. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13489. }
  13490. }
  13491. }
  13492. if (this._cachedViewport && !forceFullscreenViewport) {
  13493. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13494. }
  13495. else {
  13496. if (!requiredWidth) {
  13497. requiredWidth = texture.width;
  13498. if (lodLevel) {
  13499. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13500. }
  13501. }
  13502. if (!requiredHeight) {
  13503. requiredHeight = texture.height;
  13504. if (lodLevel) {
  13505. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13506. }
  13507. }
  13508. this._viewport(0, 0, requiredWidth, requiredHeight);
  13509. }
  13510. this.wipeCaches();
  13511. };
  13512. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13513. if (this._currentFramebuffer !== framebuffer) {
  13514. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13515. this._currentFramebuffer = framebuffer;
  13516. }
  13517. };
  13518. /**
  13519. * Unbind the current render target texture from the webGL context
  13520. * @param texture defines the render target texture to unbind
  13521. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13522. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13523. */
  13524. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13525. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13526. this._currentRenderTarget = null;
  13527. // If MSAA, we need to bitblt back to main texture
  13528. var gl = this._gl;
  13529. if (texture._MSAAFramebuffer) {
  13530. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13531. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13532. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13533. }
  13534. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13535. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13536. gl.generateMipmap(gl.TEXTURE_2D);
  13537. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13538. }
  13539. if (onBeforeUnbind) {
  13540. if (texture._MSAAFramebuffer) {
  13541. // Bind the correct framebuffer
  13542. this.bindUnboundFramebuffer(texture._framebuffer);
  13543. }
  13544. onBeforeUnbind();
  13545. }
  13546. this.bindUnboundFramebuffer(null);
  13547. };
  13548. /**
  13549. * Unbind a list of render target textures from the webGL context
  13550. * This is used only when drawBuffer extension or webGL2 are active
  13551. * @param textures defines the render target textures to unbind
  13552. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13553. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13554. */
  13555. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13556. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13557. this._currentRenderTarget = null;
  13558. // If MSAA, we need to bitblt back to main texture
  13559. var gl = this._gl;
  13560. if (textures[0]._MSAAFramebuffer) {
  13561. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13562. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13563. var attachments = textures[0]._attachments;
  13564. if (!attachments) {
  13565. attachments = new Array(textures.length);
  13566. textures[0]._attachments = attachments;
  13567. }
  13568. for (var i = 0; i < textures.length; i++) {
  13569. var texture = textures[i];
  13570. for (var j = 0; j < attachments.length; j++) {
  13571. attachments[j] = gl.NONE;
  13572. }
  13573. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13574. gl.readBuffer(attachments[i]);
  13575. gl.drawBuffers(attachments);
  13576. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13577. }
  13578. for (var i = 0; i < attachments.length; i++) {
  13579. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13580. }
  13581. gl.drawBuffers(attachments);
  13582. }
  13583. for (var i = 0; i < textures.length; i++) {
  13584. var texture = textures[i];
  13585. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13586. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13587. gl.generateMipmap(gl.TEXTURE_2D);
  13588. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13589. }
  13590. }
  13591. if (onBeforeUnbind) {
  13592. if (textures[0]._MSAAFramebuffer) {
  13593. // Bind the correct framebuffer
  13594. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13595. }
  13596. onBeforeUnbind();
  13597. }
  13598. this.bindUnboundFramebuffer(null);
  13599. };
  13600. /**
  13601. * Force the mipmap generation for the given render target texture
  13602. * @param texture defines the render target texture to use
  13603. */
  13604. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13605. if (texture.generateMipMaps) {
  13606. var gl = this._gl;
  13607. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13608. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13609. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13610. }
  13611. };
  13612. /**
  13613. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13614. */
  13615. Engine.prototype.flushFramebuffer = function () {
  13616. this._gl.flush();
  13617. };
  13618. /**
  13619. * Unbind the current render target and bind the default framebuffer
  13620. */
  13621. Engine.prototype.restoreDefaultFramebuffer = function () {
  13622. if (this._currentRenderTarget) {
  13623. this.unBindFramebuffer(this._currentRenderTarget);
  13624. }
  13625. else {
  13626. this.bindUnboundFramebuffer(null);
  13627. }
  13628. if (this._cachedViewport) {
  13629. this.setViewport(this._cachedViewport);
  13630. }
  13631. this.wipeCaches();
  13632. };
  13633. // UBOs
  13634. /**
  13635. * Create an uniform buffer
  13636. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13637. * @param elements defines the content of the uniform buffer
  13638. * @returns the webGL uniform buffer
  13639. */
  13640. Engine.prototype.createUniformBuffer = function (elements) {
  13641. var ubo = this._gl.createBuffer();
  13642. if (!ubo) {
  13643. throw new Error("Unable to create uniform buffer");
  13644. }
  13645. this.bindUniformBuffer(ubo);
  13646. if (elements instanceof Float32Array) {
  13647. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13648. }
  13649. else {
  13650. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13651. }
  13652. this.bindUniformBuffer(null);
  13653. ubo.references = 1;
  13654. return ubo;
  13655. };
  13656. /**
  13657. * Create a dynamic uniform buffer
  13658. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13659. * @param elements defines the content of the uniform buffer
  13660. * @returns the webGL uniform buffer
  13661. */
  13662. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13663. var ubo = this._gl.createBuffer();
  13664. if (!ubo) {
  13665. throw new Error("Unable to create dynamic uniform buffer");
  13666. }
  13667. this.bindUniformBuffer(ubo);
  13668. if (elements instanceof Float32Array) {
  13669. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13670. }
  13671. else {
  13672. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13673. }
  13674. this.bindUniformBuffer(null);
  13675. ubo.references = 1;
  13676. return ubo;
  13677. };
  13678. /**
  13679. * Update an existing uniform buffer
  13680. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13681. * @param uniformBuffer defines the target uniform buffer
  13682. * @param elements defines the content to update
  13683. * @param offset defines the offset in the uniform buffer where update should start
  13684. * @param count defines the size of the data to update
  13685. */
  13686. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13687. this.bindUniformBuffer(uniformBuffer);
  13688. if (offset === undefined) {
  13689. offset = 0;
  13690. }
  13691. if (count === undefined) {
  13692. if (elements instanceof Float32Array) {
  13693. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13694. }
  13695. else {
  13696. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13697. }
  13698. }
  13699. else {
  13700. if (elements instanceof Float32Array) {
  13701. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13702. }
  13703. else {
  13704. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13705. }
  13706. }
  13707. this.bindUniformBuffer(null);
  13708. };
  13709. // VBOs
  13710. Engine.prototype._resetVertexBufferBinding = function () {
  13711. this.bindArrayBuffer(null);
  13712. this._cachedVertexBuffers = null;
  13713. };
  13714. /**
  13715. * Creates a vertex buffer
  13716. * @param data the data for the vertex buffer
  13717. * @returns the new WebGL static buffer
  13718. */
  13719. Engine.prototype.createVertexBuffer = function (data) {
  13720. var vbo = this._gl.createBuffer();
  13721. if (!vbo) {
  13722. throw new Error("Unable to create vertex buffer");
  13723. }
  13724. this.bindArrayBuffer(vbo);
  13725. if (data instanceof Array) {
  13726. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13727. }
  13728. else {
  13729. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13730. }
  13731. this._resetVertexBufferBinding();
  13732. vbo.references = 1;
  13733. return vbo;
  13734. };
  13735. /**
  13736. * Creates a dynamic vertex buffer
  13737. * @param data the data for the dynamic vertex buffer
  13738. * @returns the new WebGL dynamic buffer
  13739. */
  13740. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13741. var vbo = this._gl.createBuffer();
  13742. if (!vbo) {
  13743. throw new Error("Unable to create dynamic vertex buffer");
  13744. }
  13745. this.bindArrayBuffer(vbo);
  13746. if (data instanceof Array) {
  13747. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13748. }
  13749. else {
  13750. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13751. }
  13752. this._resetVertexBufferBinding();
  13753. vbo.references = 1;
  13754. return vbo;
  13755. };
  13756. /**
  13757. * Update a dynamic index buffer
  13758. * @param indexBuffer defines the target index buffer
  13759. * @param indices defines the data to update
  13760. * @param offset defines the offset in the target index buffer where update should start
  13761. */
  13762. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13763. if (offset === void 0) { offset = 0; }
  13764. // Force cache update
  13765. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13766. this.bindIndexBuffer(indexBuffer);
  13767. var arrayBuffer;
  13768. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13769. arrayBuffer = indices;
  13770. }
  13771. else {
  13772. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13773. }
  13774. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13775. this._resetIndexBufferBinding();
  13776. };
  13777. /**
  13778. * Updates a dynamic vertex buffer.
  13779. * @param vertexBuffer the vertex buffer to update
  13780. * @param data the data used to update the vertex buffer
  13781. * @param byteOffset the byte offset of the data
  13782. * @param byteLength the byte length of the data
  13783. */
  13784. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13785. this.bindArrayBuffer(vertexBuffer);
  13786. if (byteOffset === undefined) {
  13787. byteOffset = 0;
  13788. }
  13789. if (byteLength === undefined) {
  13790. if (data instanceof Array) {
  13791. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13792. }
  13793. else {
  13794. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13795. }
  13796. }
  13797. else {
  13798. if (data instanceof Array) {
  13799. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13800. }
  13801. else {
  13802. if (data instanceof ArrayBuffer) {
  13803. data = new Uint8Array(data, byteOffset, byteLength);
  13804. }
  13805. else {
  13806. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13807. }
  13808. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13809. }
  13810. }
  13811. this._resetVertexBufferBinding();
  13812. };
  13813. Engine.prototype._resetIndexBufferBinding = function () {
  13814. this.bindIndexBuffer(null);
  13815. this._cachedIndexBuffer = null;
  13816. };
  13817. /**
  13818. * Creates a new index buffer
  13819. * @param indices defines the content of the index buffer
  13820. * @param updatable defines if the index buffer must be updatable
  13821. * @returns a new webGL buffer
  13822. */
  13823. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13824. var vbo = this._gl.createBuffer();
  13825. if (!vbo) {
  13826. throw new Error("Unable to create index buffer");
  13827. }
  13828. this.bindIndexBuffer(vbo);
  13829. // Check for 32 bits indices
  13830. var arrayBuffer;
  13831. var need32Bits = false;
  13832. if (indices instanceof Uint16Array) {
  13833. arrayBuffer = indices;
  13834. }
  13835. else {
  13836. //check 32 bit support
  13837. if (this._caps.uintIndices) {
  13838. if (indices instanceof Uint32Array) {
  13839. arrayBuffer = indices;
  13840. need32Bits = true;
  13841. }
  13842. else {
  13843. //number[] or Int32Array, check if 32 bit is necessary
  13844. for (var index = 0; index < indices.length; index++) {
  13845. if (indices[index] > 65535) {
  13846. need32Bits = true;
  13847. break;
  13848. }
  13849. }
  13850. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13851. }
  13852. }
  13853. else {
  13854. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13855. arrayBuffer = new Uint16Array(indices);
  13856. }
  13857. }
  13858. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13859. this._resetIndexBufferBinding();
  13860. vbo.references = 1;
  13861. vbo.is32Bits = need32Bits;
  13862. return vbo;
  13863. };
  13864. /**
  13865. * Bind a webGL buffer to the webGL context
  13866. * @param buffer defines the buffer to bind
  13867. */
  13868. Engine.prototype.bindArrayBuffer = function (buffer) {
  13869. if (!this._vaoRecordInProgress) {
  13870. this._unbindVertexArrayObject();
  13871. }
  13872. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13873. };
  13874. /**
  13875. * Bind an uniform buffer to the current webGL context
  13876. * @param buffer defines the buffer to bind
  13877. */
  13878. Engine.prototype.bindUniformBuffer = function (buffer) {
  13879. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13880. };
  13881. /**
  13882. * Bind a buffer to the current webGL context at a given location
  13883. * @param buffer defines the buffer to bind
  13884. * @param location defines the index where to bind the buffer
  13885. */
  13886. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13887. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13888. };
  13889. /**
  13890. * Bind a specific block at a given index in a specific shader program
  13891. * @param shaderProgram defines the shader program
  13892. * @param blockName defines the block name
  13893. * @param index defines the index where to bind the block
  13894. */
  13895. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13896. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13897. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13898. };
  13899. ;
  13900. Engine.prototype.bindIndexBuffer = function (buffer) {
  13901. if (!this._vaoRecordInProgress) {
  13902. this._unbindVertexArrayObject();
  13903. }
  13904. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13905. };
  13906. Engine.prototype.bindBuffer = function (buffer, target) {
  13907. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13908. this._gl.bindBuffer(target, buffer);
  13909. this._currentBoundBuffer[target] = buffer;
  13910. }
  13911. };
  13912. /**
  13913. * update the bound buffer with the given data
  13914. * @param data defines the data to update
  13915. */
  13916. Engine.prototype.updateArrayBuffer = function (data) {
  13917. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13918. };
  13919. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13920. var pointer = this._currentBufferPointers[indx];
  13921. var changed = false;
  13922. if (!pointer.active) {
  13923. changed = true;
  13924. pointer.active = true;
  13925. pointer.index = indx;
  13926. pointer.size = size;
  13927. pointer.type = type;
  13928. pointer.normalized = normalized;
  13929. pointer.stride = stride;
  13930. pointer.offset = offset;
  13931. pointer.buffer = buffer;
  13932. }
  13933. else {
  13934. if (pointer.buffer !== buffer) {
  13935. pointer.buffer = buffer;
  13936. changed = true;
  13937. }
  13938. if (pointer.size !== size) {
  13939. pointer.size = size;
  13940. changed = true;
  13941. }
  13942. if (pointer.type !== type) {
  13943. pointer.type = type;
  13944. changed = true;
  13945. }
  13946. if (pointer.normalized !== normalized) {
  13947. pointer.normalized = normalized;
  13948. changed = true;
  13949. }
  13950. if (pointer.stride !== stride) {
  13951. pointer.stride = stride;
  13952. changed = true;
  13953. }
  13954. if (pointer.offset !== offset) {
  13955. pointer.offset = offset;
  13956. changed = true;
  13957. }
  13958. }
  13959. if (changed || this._vaoRecordInProgress) {
  13960. this.bindArrayBuffer(buffer);
  13961. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13962. }
  13963. };
  13964. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13965. if (indexBuffer == null) {
  13966. return;
  13967. }
  13968. if (this._cachedIndexBuffer !== indexBuffer) {
  13969. this._cachedIndexBuffer = indexBuffer;
  13970. this.bindIndexBuffer(indexBuffer);
  13971. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13972. }
  13973. };
  13974. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13975. var attributes = effect.getAttributesNames();
  13976. if (!this._vaoRecordInProgress) {
  13977. this._unbindVertexArrayObject();
  13978. }
  13979. this.unbindAllAttributes();
  13980. for (var index = 0; index < attributes.length; index++) {
  13981. var order = effect.getAttributeLocation(index);
  13982. if (order >= 0) {
  13983. var vertexBuffer = vertexBuffers[attributes[index]];
  13984. if (!vertexBuffer) {
  13985. continue;
  13986. }
  13987. this._gl.enableVertexAttribArray(order);
  13988. if (!this._vaoRecordInProgress) {
  13989. this._vertexAttribArraysEnabled[order] = true;
  13990. }
  13991. var buffer = vertexBuffer.getBuffer();
  13992. if (buffer) {
  13993. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13994. if (vertexBuffer.getIsInstanced()) {
  13995. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13996. if (!this._vaoRecordInProgress) {
  13997. this._currentInstanceLocations.push(order);
  13998. this._currentInstanceBuffers.push(buffer);
  13999. }
  14000. }
  14001. }
  14002. }
  14003. }
  14004. };
  14005. /**
  14006. * Records a vertex array object
  14007. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14008. * @param vertexBuffers defines the list of vertex buffers to store
  14009. * @param indexBuffer defines the index buffer to store
  14010. * @param effect defines the effect to store
  14011. * @returns the new vertex array object
  14012. */
  14013. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14014. var vao = this._gl.createVertexArray();
  14015. this._vaoRecordInProgress = true;
  14016. this._gl.bindVertexArray(vao);
  14017. this._mustWipeVertexAttributes = true;
  14018. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14019. this.bindIndexBuffer(indexBuffer);
  14020. this._vaoRecordInProgress = false;
  14021. this._gl.bindVertexArray(null);
  14022. return vao;
  14023. };
  14024. /**
  14025. * Bind a specific vertex array object
  14026. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14027. * @param vertexArrayObject defines the vertex array object to bind
  14028. * @param indexBuffer defines the index buffer to bind
  14029. */
  14030. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14031. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14032. this._cachedVertexArrayObject = vertexArrayObject;
  14033. this._gl.bindVertexArray(vertexArrayObject);
  14034. this._cachedVertexBuffers = null;
  14035. this._cachedIndexBuffer = null;
  14036. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14037. this._mustWipeVertexAttributes = true;
  14038. }
  14039. };
  14040. /**
  14041. * Bind webGl buffers directly to the webGL context
  14042. * @param vertexBuffer defines the vertex buffer to bind
  14043. * @param indexBuffer defines the index buffer to bind
  14044. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14045. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14046. * @param effect defines the effect associated with the vertex buffer
  14047. */
  14048. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14049. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14050. this._cachedVertexBuffers = vertexBuffer;
  14051. this._cachedEffectForVertexBuffers = effect;
  14052. var attributesCount = effect.getAttributesCount();
  14053. this._unbindVertexArrayObject();
  14054. this.unbindAllAttributes();
  14055. var offset = 0;
  14056. for (var index = 0; index < attributesCount; index++) {
  14057. if (index < vertexDeclaration.length) {
  14058. var order = effect.getAttributeLocation(index);
  14059. if (order >= 0) {
  14060. this._gl.enableVertexAttribArray(order);
  14061. this._vertexAttribArraysEnabled[order] = true;
  14062. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14063. }
  14064. offset += vertexDeclaration[index] * 4;
  14065. }
  14066. }
  14067. }
  14068. this._bindIndexBufferWithCache(indexBuffer);
  14069. };
  14070. Engine.prototype._unbindVertexArrayObject = function () {
  14071. if (!this._cachedVertexArrayObject) {
  14072. return;
  14073. }
  14074. this._cachedVertexArrayObject = null;
  14075. this._gl.bindVertexArray(null);
  14076. };
  14077. /**
  14078. * Bind a list of vertex buffers to the webGL context
  14079. * @param vertexBuffers defines the list of vertex buffers to bind
  14080. * @param indexBuffer defines the index buffer to bind
  14081. * @param effect defines the effect associated with the vertex buffers
  14082. */
  14083. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14084. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14085. this._cachedVertexBuffers = vertexBuffers;
  14086. this._cachedEffectForVertexBuffers = effect;
  14087. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14088. }
  14089. this._bindIndexBufferWithCache(indexBuffer);
  14090. };
  14091. /**
  14092. * Unbind all instance attributes
  14093. */
  14094. Engine.prototype.unbindInstanceAttributes = function () {
  14095. var boundBuffer;
  14096. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14097. var instancesBuffer = this._currentInstanceBuffers[i];
  14098. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14099. boundBuffer = instancesBuffer;
  14100. this.bindArrayBuffer(instancesBuffer);
  14101. }
  14102. var offsetLocation = this._currentInstanceLocations[i];
  14103. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14104. }
  14105. this._currentInstanceBuffers.length = 0;
  14106. this._currentInstanceLocations.length = 0;
  14107. };
  14108. /**
  14109. * Release and free the memory of a vertex array object
  14110. * @param vao defines the vertex array object to delete
  14111. */
  14112. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14113. this._gl.deleteVertexArray(vao);
  14114. };
  14115. /** @hidden */
  14116. Engine.prototype._releaseBuffer = function (buffer) {
  14117. buffer.references--;
  14118. if (buffer.references === 0) {
  14119. this._gl.deleteBuffer(buffer);
  14120. return true;
  14121. }
  14122. return false;
  14123. };
  14124. /**
  14125. * Creates a webGL buffer to use with instanciation
  14126. * @param capacity defines the size of the buffer
  14127. * @returns the webGL buffer
  14128. */
  14129. Engine.prototype.createInstancesBuffer = function (capacity) {
  14130. var buffer = this._gl.createBuffer();
  14131. if (!buffer) {
  14132. throw new Error("Unable to create instance buffer");
  14133. }
  14134. buffer.capacity = capacity;
  14135. this.bindArrayBuffer(buffer);
  14136. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14137. return buffer;
  14138. };
  14139. /**
  14140. * Delete a webGL buffer used with instanciation
  14141. * @param buffer defines the webGL buffer to delete
  14142. */
  14143. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14144. this._gl.deleteBuffer(buffer);
  14145. };
  14146. /**
  14147. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14148. * @param instancesBuffer defines the webGL buffer to update and bind
  14149. * @param data defines the data to store in the buffer
  14150. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14151. */
  14152. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14153. this.bindArrayBuffer(instancesBuffer);
  14154. if (data) {
  14155. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14156. }
  14157. if (offsetLocations[0].index !== undefined) {
  14158. var stride = 0;
  14159. for (var i = 0; i < offsetLocations.length; i++) {
  14160. var ai = offsetLocations[i];
  14161. stride += ai.attributeSize * 4;
  14162. }
  14163. for (var i = 0; i < offsetLocations.length; i++) {
  14164. var ai = offsetLocations[i];
  14165. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14166. this._gl.enableVertexAttribArray(ai.index);
  14167. this._vertexAttribArraysEnabled[ai.index] = true;
  14168. }
  14169. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14170. this._gl.vertexAttribDivisor(ai.index, 1);
  14171. this._currentInstanceLocations.push(ai.index);
  14172. this._currentInstanceBuffers.push(instancesBuffer);
  14173. }
  14174. }
  14175. else {
  14176. for (var index = 0; index < 4; index++) {
  14177. var offsetLocation = offsetLocations[index];
  14178. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14179. this._gl.enableVertexAttribArray(offsetLocation);
  14180. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14181. }
  14182. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14183. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14184. this._currentInstanceLocations.push(offsetLocation);
  14185. this._currentInstanceBuffers.push(instancesBuffer);
  14186. }
  14187. }
  14188. };
  14189. /**
  14190. * Apply all cached states (depth, culling, stencil and alpha)
  14191. */
  14192. Engine.prototype.applyStates = function () {
  14193. this._depthCullingState.apply(this._gl);
  14194. this._stencilState.apply(this._gl);
  14195. this._alphaState.apply(this._gl);
  14196. };
  14197. /**
  14198. * Send a draw order
  14199. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14200. * @param indexStart defines the starting index
  14201. * @param indexCount defines the number of index to draw
  14202. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14203. */
  14204. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14205. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14206. };
  14207. /**
  14208. * Draw a list of points
  14209. * @param verticesStart defines the index of first vertex to draw
  14210. * @param verticesCount defines the count of vertices to draw
  14211. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14212. */
  14213. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14214. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14215. };
  14216. /**
  14217. * Draw a list of unindexed primitives
  14218. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14219. * @param verticesStart defines the index of first vertex to draw
  14220. * @param verticesCount defines the count of vertices to draw
  14221. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14222. */
  14223. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14224. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14225. };
  14226. /**
  14227. * Draw a list of indexed primitives
  14228. * @param fillMode defines the primitive to use
  14229. * @param indexStart defines the starting index
  14230. * @param indexCount defines the number of index to draw
  14231. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14232. */
  14233. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14234. // Apply states
  14235. this.applyStates();
  14236. this._drawCalls.addCount(1, false);
  14237. // Render
  14238. var drawMode = this._drawMode(fillMode);
  14239. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14240. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14241. if (instancesCount) {
  14242. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14243. }
  14244. else {
  14245. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14246. }
  14247. };
  14248. /**
  14249. * Draw a list of unindexed primitives
  14250. * @param fillMode defines the primitive to use
  14251. * @param verticesStart defines the index of first vertex to draw
  14252. * @param verticesCount defines the count of vertices to draw
  14253. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14254. */
  14255. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14256. // Apply states
  14257. this.applyStates();
  14258. this._drawCalls.addCount(1, false);
  14259. var drawMode = this._drawMode(fillMode);
  14260. if (instancesCount) {
  14261. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14262. }
  14263. else {
  14264. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14265. }
  14266. };
  14267. Engine.prototype._drawMode = function (fillMode) {
  14268. switch (fillMode) {
  14269. // Triangle views
  14270. case BABYLON.Material.TriangleFillMode:
  14271. return this._gl.TRIANGLES;
  14272. case BABYLON.Material.PointFillMode:
  14273. return this._gl.POINTS;
  14274. case BABYLON.Material.WireFrameFillMode:
  14275. return this._gl.LINES;
  14276. // Draw modes
  14277. case BABYLON.Material.PointListDrawMode:
  14278. return this._gl.POINTS;
  14279. case BABYLON.Material.LineListDrawMode:
  14280. return this._gl.LINES;
  14281. case BABYLON.Material.LineLoopDrawMode:
  14282. return this._gl.LINE_LOOP;
  14283. case BABYLON.Material.LineStripDrawMode:
  14284. return this._gl.LINE_STRIP;
  14285. case BABYLON.Material.TriangleStripDrawMode:
  14286. return this._gl.TRIANGLE_STRIP;
  14287. case BABYLON.Material.TriangleFanDrawMode:
  14288. return this._gl.TRIANGLE_FAN;
  14289. default:
  14290. return this._gl.TRIANGLES;
  14291. }
  14292. };
  14293. // Shaders
  14294. /** @hidden */
  14295. Engine.prototype._releaseEffect = function (effect) {
  14296. if (this._compiledEffects[effect._key]) {
  14297. delete this._compiledEffects[effect._key];
  14298. this._deleteProgram(effect.getProgram());
  14299. }
  14300. };
  14301. /** @hidden */
  14302. Engine.prototype._deleteProgram = function (program) {
  14303. if (program) {
  14304. program.__SPECTOR_rebuildProgram = null;
  14305. if (program.transformFeedback) {
  14306. this.deleteTransformFeedback(program.transformFeedback);
  14307. program.transformFeedback = null;
  14308. }
  14309. this._gl.deleteProgram(program);
  14310. }
  14311. };
  14312. /**
  14313. * Create a new effect (used to store vertex/fragment shaders)
  14314. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14315. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14316. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14317. * @param samplers defines an array of string used to represent textures
  14318. * @param defines defines the string containing the defines to use to compile the shaders
  14319. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14320. * @param onCompiled defines a function to call when the effect creation is successful
  14321. * @param onError defines a function to call when the effect creation has failed
  14322. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14323. * @returns the new Effect
  14324. */
  14325. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14326. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14327. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14328. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14329. if (this._compiledEffects[name]) {
  14330. var compiledEffect = this._compiledEffects[name];
  14331. if (onCompiled && compiledEffect.isReady()) {
  14332. onCompiled(compiledEffect);
  14333. }
  14334. return compiledEffect;
  14335. }
  14336. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14337. effect._key = name;
  14338. this._compiledEffects[name] = effect;
  14339. return effect;
  14340. };
  14341. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14342. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14343. };
  14344. ;
  14345. Engine.prototype._compileRawShader = function (source, type) {
  14346. var gl = this._gl;
  14347. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14348. gl.shaderSource(shader, source);
  14349. gl.compileShader(shader);
  14350. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14351. var log = gl.getShaderInfoLog(shader);
  14352. if (log) {
  14353. throw new Error(log);
  14354. }
  14355. }
  14356. if (!shader) {
  14357. throw new Error("Something went wrong while compile the shader.");
  14358. }
  14359. return shader;
  14360. };
  14361. ;
  14362. /**
  14363. * Directly creates a webGL program
  14364. * @param vertexCode defines the vertex shader code to use
  14365. * @param fragmentCode defines the fragment shader code to use
  14366. * @param context defines the webGL context to use (if not set, the current one will be used)
  14367. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14368. * @returns the new webGL program
  14369. */
  14370. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14371. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14372. context = context || this._gl;
  14373. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14374. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14375. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14376. };
  14377. /**
  14378. * Creates a webGL program
  14379. * @param vertexCode defines the vertex shader code to use
  14380. * @param fragmentCode defines the fragment shader code to use
  14381. * @param defines defines the string containing the defines to use to compile the shaders
  14382. * @param context defines the webGL context to use (if not set, the current one will be used)
  14383. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14384. * @returns the new webGL program
  14385. */
  14386. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14387. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14388. context = context || this._gl;
  14389. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14390. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14391. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14392. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14393. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14394. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14395. return program;
  14396. };
  14397. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14398. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14399. var shaderProgram = context.createProgram();
  14400. if (!shaderProgram) {
  14401. throw new Error("Unable to create program");
  14402. }
  14403. context.attachShader(shaderProgram, vertexShader);
  14404. context.attachShader(shaderProgram, fragmentShader);
  14405. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14406. var transformFeedback = this.createTransformFeedback();
  14407. this.bindTransformFeedback(transformFeedback);
  14408. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14409. shaderProgram.transformFeedback = transformFeedback;
  14410. }
  14411. context.linkProgram(shaderProgram);
  14412. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14413. this.bindTransformFeedback(null);
  14414. }
  14415. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14416. if (!linked) {
  14417. var error = context.getProgramInfoLog(shaderProgram);
  14418. if (error) {
  14419. throw new Error(error);
  14420. }
  14421. }
  14422. if (this.validateShaderPrograms) {
  14423. context.validateProgram(shaderProgram);
  14424. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14425. if (!validated) {
  14426. var error = context.getProgramInfoLog(shaderProgram);
  14427. if (error) {
  14428. throw new Error(error);
  14429. }
  14430. }
  14431. }
  14432. context.deleteShader(vertexShader);
  14433. context.deleteShader(fragmentShader);
  14434. return shaderProgram;
  14435. };
  14436. /**
  14437. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14438. * @param shaderProgram defines the webGL program to use
  14439. * @param uniformsNames defines the list of uniform names
  14440. * @returns an array of webGL uniform locations
  14441. */
  14442. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14443. var results = new Array();
  14444. for (var index = 0; index < uniformsNames.length; index++) {
  14445. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14446. }
  14447. return results;
  14448. };
  14449. /**
  14450. * Gets the lsit of active attributes for a given webGL program
  14451. * @param shaderProgram defines the webGL program to use
  14452. * @param attributesNames defines the list of attribute names to get
  14453. * @returns an array of indices indicating the offset of each attribute
  14454. */
  14455. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14456. var results = [];
  14457. for (var index = 0; index < attributesNames.length; index++) {
  14458. try {
  14459. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14460. }
  14461. catch (e) {
  14462. results.push(-1);
  14463. }
  14464. }
  14465. return results;
  14466. };
  14467. /**
  14468. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14469. * @param effect defines the effect to activate
  14470. */
  14471. Engine.prototype.enableEffect = function (effect) {
  14472. if (!effect || effect === this._currentEffect) {
  14473. return;
  14474. }
  14475. // Use program
  14476. this.bindSamplers(effect);
  14477. this._currentEffect = effect;
  14478. if (effect.onBind) {
  14479. effect.onBind(effect);
  14480. }
  14481. if (effect._onBindObservable) {
  14482. effect._onBindObservable.notifyObservers(effect);
  14483. }
  14484. };
  14485. /**
  14486. * Set the value of an uniform to an array of int32
  14487. * @param uniform defines the webGL uniform location where to store the value
  14488. * @param array defines the array of int32 to store
  14489. */
  14490. Engine.prototype.setIntArray = function (uniform, array) {
  14491. if (!uniform)
  14492. return;
  14493. this._gl.uniform1iv(uniform, array);
  14494. };
  14495. /**
  14496. * Set the value of an uniform to an array of int32 (stored as vec2)
  14497. * @param uniform defines the webGL uniform location where to store the value
  14498. * @param array defines the array of int32 to store
  14499. */
  14500. Engine.prototype.setIntArray2 = function (uniform, array) {
  14501. if (!uniform || array.length % 2 !== 0)
  14502. return;
  14503. this._gl.uniform2iv(uniform, array);
  14504. };
  14505. /**
  14506. * Set the value of an uniform to an array of int32 (stored as vec3)
  14507. * @param uniform defines the webGL uniform location where to store the value
  14508. * @param array defines the array of int32 to store
  14509. */
  14510. Engine.prototype.setIntArray3 = function (uniform, array) {
  14511. if (!uniform || array.length % 3 !== 0)
  14512. return;
  14513. this._gl.uniform3iv(uniform, array);
  14514. };
  14515. /**
  14516. * Set the value of an uniform to an array of int32 (stored as vec4)
  14517. * @param uniform defines the webGL uniform location where to store the value
  14518. * @param array defines the array of int32 to store
  14519. */
  14520. Engine.prototype.setIntArray4 = function (uniform, array) {
  14521. if (!uniform || array.length % 4 !== 0)
  14522. return;
  14523. this._gl.uniform4iv(uniform, array);
  14524. };
  14525. /**
  14526. * Set the value of an uniform to an array of float32
  14527. * @param uniform defines the webGL uniform location where to store the value
  14528. * @param array defines the array of float32 to store
  14529. */
  14530. Engine.prototype.setFloatArray = function (uniform, array) {
  14531. if (!uniform)
  14532. return;
  14533. this._gl.uniform1fv(uniform, array);
  14534. };
  14535. /**
  14536. * Set the value of an uniform to an array of float32 (stored as vec2)
  14537. * @param uniform defines the webGL uniform location where to store the value
  14538. * @param array defines the array of float32 to store
  14539. */
  14540. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14541. if (!uniform || array.length % 2 !== 0)
  14542. return;
  14543. this._gl.uniform2fv(uniform, array);
  14544. };
  14545. /**
  14546. * Set the value of an uniform to an array of float32 (stored as vec3)
  14547. * @param uniform defines the webGL uniform location where to store the value
  14548. * @param array defines the array of float32 to store
  14549. */
  14550. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14551. if (!uniform || array.length % 3 !== 0)
  14552. return;
  14553. this._gl.uniform3fv(uniform, array);
  14554. };
  14555. /**
  14556. * Set the value of an uniform to an array of float32 (stored as vec4)
  14557. * @param uniform defines the webGL uniform location where to store the value
  14558. * @param array defines the array of float32 to store
  14559. */
  14560. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14561. if (!uniform || array.length % 4 !== 0)
  14562. return;
  14563. this._gl.uniform4fv(uniform, array);
  14564. };
  14565. /**
  14566. * Set the value of an uniform to an array of number
  14567. * @param uniform defines the webGL uniform location where to store the value
  14568. * @param array defines the array of number to store
  14569. */
  14570. Engine.prototype.setArray = function (uniform, array) {
  14571. if (!uniform)
  14572. return;
  14573. this._gl.uniform1fv(uniform, array);
  14574. };
  14575. /**
  14576. * Set the value of an uniform to an array of number (stored as vec2)
  14577. * @param uniform defines the webGL uniform location where to store the value
  14578. * @param array defines the array of number to store
  14579. */
  14580. Engine.prototype.setArray2 = function (uniform, array) {
  14581. if (!uniform || array.length % 2 !== 0)
  14582. return;
  14583. this._gl.uniform2fv(uniform, array);
  14584. };
  14585. /**
  14586. * Set the value of an uniform to an array of number (stored as vec3)
  14587. * @param uniform defines the webGL uniform location where to store the value
  14588. * @param array defines the array of number to store
  14589. */
  14590. Engine.prototype.setArray3 = function (uniform, array) {
  14591. if (!uniform || array.length % 3 !== 0)
  14592. return;
  14593. this._gl.uniform3fv(uniform, array);
  14594. };
  14595. /**
  14596. * Set the value of an uniform to an array of number (stored as vec4)
  14597. * @param uniform defines the webGL uniform location where to store the value
  14598. * @param array defines the array of number to store
  14599. */
  14600. Engine.prototype.setArray4 = function (uniform, array) {
  14601. if (!uniform || array.length % 4 !== 0)
  14602. return;
  14603. this._gl.uniform4fv(uniform, array);
  14604. };
  14605. /**
  14606. * Set the value of an uniform to an array of float32 (stored as matrices)
  14607. * @param uniform defines the webGL uniform location where to store the value
  14608. * @param matrices defines the array of float32 to store
  14609. */
  14610. Engine.prototype.setMatrices = function (uniform, matrices) {
  14611. if (!uniform)
  14612. return;
  14613. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14614. };
  14615. /**
  14616. * Set the value of an uniform to a matrix
  14617. * @param uniform defines the webGL uniform location where to store the value
  14618. * @param matrix defines the matrix to store
  14619. */
  14620. Engine.prototype.setMatrix = function (uniform, matrix) {
  14621. if (!uniform)
  14622. return;
  14623. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14624. };
  14625. /**
  14626. * Set the value of an uniform to a matrix (3x3)
  14627. * @param uniform defines the webGL uniform location where to store the value
  14628. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14629. */
  14630. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14631. if (!uniform)
  14632. return;
  14633. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14634. };
  14635. /**
  14636. * Set the value of an uniform to a matrix (2x2)
  14637. * @param uniform defines the webGL uniform location where to store the value
  14638. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14639. */
  14640. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14641. if (!uniform)
  14642. return;
  14643. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14644. };
  14645. /**
  14646. * Set the value of an uniform to a number (int)
  14647. * @param uniform defines the webGL uniform location where to store the value
  14648. * @param value defines the int number to store
  14649. */
  14650. Engine.prototype.setInt = function (uniform, value) {
  14651. if (!uniform)
  14652. return;
  14653. this._gl.uniform1i(uniform, value);
  14654. };
  14655. /**
  14656. * Set the value of an uniform to a number (float)
  14657. * @param uniform defines the webGL uniform location where to store the value
  14658. * @param value defines the float number to store
  14659. */
  14660. Engine.prototype.setFloat = function (uniform, value) {
  14661. if (!uniform)
  14662. return;
  14663. this._gl.uniform1f(uniform, value);
  14664. };
  14665. /**
  14666. * Set the value of an uniform to a vec2
  14667. * @param uniform defines the webGL uniform location where to store the value
  14668. * @param x defines the 1st component of the value
  14669. * @param y defines the 2nd component of the value
  14670. */
  14671. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14672. if (!uniform)
  14673. return;
  14674. this._gl.uniform2f(uniform, x, y);
  14675. };
  14676. /**
  14677. * Set the value of an uniform to a vec3
  14678. * @param uniform defines the webGL uniform location where to store the value
  14679. * @param x defines the 1st component of the value
  14680. * @param y defines the 2nd component of the value
  14681. * @param z defines the 3rd component of the value
  14682. */
  14683. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14684. if (!uniform)
  14685. return;
  14686. this._gl.uniform3f(uniform, x, y, z);
  14687. };
  14688. /**
  14689. * Set the value of an uniform to a boolean
  14690. * @param uniform defines the webGL uniform location where to store the value
  14691. * @param bool defines the boolean to store
  14692. */
  14693. Engine.prototype.setBool = function (uniform, bool) {
  14694. if (!uniform)
  14695. return;
  14696. this._gl.uniform1i(uniform, bool);
  14697. };
  14698. /**
  14699. * Set the value of an uniform to a vec4
  14700. * @param uniform defines the webGL uniform location where to store the value
  14701. * @param x defines the 1st component of the value
  14702. * @param y defines the 2nd component of the value
  14703. * @param z defines the 3rd component of the value
  14704. * @param w defines the 4th component of the value
  14705. */
  14706. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14707. if (!uniform)
  14708. return;
  14709. this._gl.uniform4f(uniform, x, y, z, w);
  14710. };
  14711. /**
  14712. * Set the value of an uniform to a Color3
  14713. * @param uniform defines the webGL uniform location where to store the value
  14714. * @param color3 defines the color to store
  14715. */
  14716. Engine.prototype.setColor3 = function (uniform, color3) {
  14717. if (!uniform)
  14718. return;
  14719. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14720. };
  14721. /**
  14722. * Set the value of an uniform to a Color3 and an alpha value
  14723. * @param uniform defines the webGL uniform location where to store the value
  14724. * @param color3 defines the color to store
  14725. * @param alpha defines the alpha component to store
  14726. */
  14727. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14728. if (!uniform)
  14729. return;
  14730. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14731. };
  14732. /**
  14733. * Sets a Color4 on a uniform variable
  14734. * @param uniform defines the uniform location
  14735. * @param color4 defines the value to be set
  14736. */
  14737. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14738. if (!uniform)
  14739. return;
  14740. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14741. };
  14742. // States
  14743. /**
  14744. * Set various states to the webGL context
  14745. * @param culling defines backface culling state
  14746. * @param zOffset defines the value to apply to zOffset (0 by default)
  14747. * @param force defines if states must be applied even if cache is up to date
  14748. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14749. */
  14750. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14751. if (zOffset === void 0) { zOffset = 0; }
  14752. if (reverseSide === void 0) { reverseSide = false; }
  14753. // Culling
  14754. if (this._depthCullingState.cull !== culling || force) {
  14755. this._depthCullingState.cull = culling;
  14756. }
  14757. // Cull face
  14758. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14759. if (this._depthCullingState.cullFace !== cullFace || force) {
  14760. this._depthCullingState.cullFace = cullFace;
  14761. }
  14762. // Z offset
  14763. this.setZOffset(zOffset);
  14764. // Front face
  14765. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14766. if (this._depthCullingState.frontFace !== frontFace || force) {
  14767. this._depthCullingState.frontFace = frontFace;
  14768. }
  14769. };
  14770. /**
  14771. * Set the z offset to apply to current rendering
  14772. * @param value defines the offset to apply
  14773. */
  14774. Engine.prototype.setZOffset = function (value) {
  14775. this._depthCullingState.zOffset = value;
  14776. };
  14777. /**
  14778. * Gets the current value of the zOffset
  14779. * @returns the current zOffset state
  14780. */
  14781. Engine.prototype.getZOffset = function () {
  14782. return this._depthCullingState.zOffset;
  14783. };
  14784. /**
  14785. * Enable or disable depth buffering
  14786. * @param enable defines the state to set
  14787. */
  14788. Engine.prototype.setDepthBuffer = function (enable) {
  14789. this._depthCullingState.depthTest = enable;
  14790. };
  14791. /**
  14792. * Gets a boolean indicating if depth writing is enabled
  14793. * @returns the current depth writing state
  14794. */
  14795. Engine.prototype.getDepthWrite = function () {
  14796. return this._depthCullingState.depthMask;
  14797. };
  14798. /**
  14799. * Enable or disable depth writing
  14800. * @param enable defines the state to set
  14801. */
  14802. Engine.prototype.setDepthWrite = function (enable) {
  14803. this._depthCullingState.depthMask = enable;
  14804. };
  14805. /**
  14806. * Enable or disable color writing
  14807. * @param enable defines the state to set
  14808. */
  14809. Engine.prototype.setColorWrite = function (enable) {
  14810. this._gl.colorMask(enable, enable, enable, enable);
  14811. this._colorWrite = enable;
  14812. };
  14813. /**
  14814. * Gets a boolean indicating if color writing is enabled
  14815. * @returns the current color writing state
  14816. */
  14817. Engine.prototype.getColorWrite = function () {
  14818. return this._colorWrite;
  14819. };
  14820. /**
  14821. * Sets alpha constants used by some alpha blending modes
  14822. * @param r defines the red component
  14823. * @param g defines the green component
  14824. * @param b defines the blue component
  14825. * @param a defines the alpha component
  14826. */
  14827. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14828. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14829. };
  14830. /**
  14831. * Sets the current alpha mode
  14832. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14833. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14834. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14835. */
  14836. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14837. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14838. if (this._alphaMode === mode) {
  14839. return;
  14840. }
  14841. switch (mode) {
  14842. case Engine.ALPHA_DISABLE:
  14843. this._alphaState.alphaBlend = false;
  14844. break;
  14845. case Engine.ALPHA_PREMULTIPLIED:
  14846. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14847. this._alphaState.alphaBlend = true;
  14848. break;
  14849. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14850. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14851. this._alphaState.alphaBlend = true;
  14852. break;
  14853. case Engine.ALPHA_COMBINE:
  14854. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14855. this._alphaState.alphaBlend = true;
  14856. break;
  14857. case Engine.ALPHA_ONEONE:
  14858. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14859. this._alphaState.alphaBlend = true;
  14860. break;
  14861. case Engine.ALPHA_ADD:
  14862. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14863. this._alphaState.alphaBlend = true;
  14864. break;
  14865. case Engine.ALPHA_SUBTRACT:
  14866. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14867. this._alphaState.alphaBlend = true;
  14868. break;
  14869. case Engine.ALPHA_MULTIPLY:
  14870. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14871. this._alphaState.alphaBlend = true;
  14872. break;
  14873. case Engine.ALPHA_MAXIMIZED:
  14874. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14875. this._alphaState.alphaBlend = true;
  14876. break;
  14877. case Engine.ALPHA_INTERPOLATE:
  14878. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14879. this._alphaState.alphaBlend = true;
  14880. break;
  14881. case Engine.ALPHA_SCREENMODE:
  14882. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14883. this._alphaState.alphaBlend = true;
  14884. break;
  14885. }
  14886. if (!noDepthWriteChange) {
  14887. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14888. }
  14889. this._alphaMode = mode;
  14890. };
  14891. /**
  14892. * Gets the current alpha mode
  14893. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14894. * @returns the current alpha mode
  14895. */
  14896. Engine.prototype.getAlphaMode = function () {
  14897. return this._alphaMode;
  14898. };
  14899. // Textures
  14900. /**
  14901. * Clears the list of texture accessible through engine.
  14902. * This can help preventing texture load conflict due to name collision.
  14903. */
  14904. Engine.prototype.clearInternalTexturesCache = function () {
  14905. this._internalTexturesCache = [];
  14906. };
  14907. /**
  14908. * Force the entire cache to be cleared
  14909. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14910. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14911. */
  14912. Engine.prototype.wipeCaches = function (bruteForce) {
  14913. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14914. return;
  14915. }
  14916. this._currentEffect = null;
  14917. this._viewportCached.x = 0;
  14918. this._viewportCached.y = 0;
  14919. this._viewportCached.z = 0;
  14920. this._viewportCached.w = 0;
  14921. if (bruteForce) {
  14922. this.resetTextureCache();
  14923. this._currentProgram = null;
  14924. this._stencilState.reset();
  14925. this._depthCullingState.reset();
  14926. this.setDepthFunctionToLessOrEqual();
  14927. this._alphaState.reset();
  14928. this._unpackFlipYCached = null;
  14929. }
  14930. this._resetVertexBufferBinding();
  14931. this._cachedIndexBuffer = null;
  14932. this._cachedEffectForVertexBuffers = null;
  14933. this._unbindVertexArrayObject();
  14934. this.bindIndexBuffer(null);
  14935. };
  14936. /**
  14937. * Set the compressed texture format to use, based on the formats you have, and the formats
  14938. * supported by the hardware / browser.
  14939. *
  14940. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14941. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14942. * to API arguments needed to compressed textures. This puts the burden on the container
  14943. * generator to house the arcane code for determining these for current & future formats.
  14944. *
  14945. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14946. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14947. *
  14948. * Note: The result of this call is not taken into account when a texture is base64.
  14949. *
  14950. * @param formatsAvailable defines the list of those format families you have created
  14951. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14952. *
  14953. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14954. * @returns The extension selected.
  14955. */
  14956. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14957. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14958. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14959. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14960. return this._textureFormatInUse = this._texturesSupported[i];
  14961. }
  14962. }
  14963. }
  14964. // actively set format to nothing, to allow this to be called more than once
  14965. // and possibly fail the 2nd time
  14966. this._textureFormatInUse = null;
  14967. return null;
  14968. };
  14969. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14970. var gl = this._gl;
  14971. var magFilter = gl.NEAREST;
  14972. var minFilter = gl.NEAREST;
  14973. switch (samplingMode) {
  14974. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14975. magFilter = gl.LINEAR;
  14976. if (generateMipMaps) {
  14977. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14978. }
  14979. else {
  14980. minFilter = gl.LINEAR;
  14981. }
  14982. break;
  14983. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14984. magFilter = gl.LINEAR;
  14985. if (generateMipMaps) {
  14986. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14987. }
  14988. else {
  14989. minFilter = gl.LINEAR;
  14990. }
  14991. break;
  14992. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14993. magFilter = gl.NEAREST;
  14994. if (generateMipMaps) {
  14995. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14996. }
  14997. else {
  14998. minFilter = gl.NEAREST;
  14999. }
  15000. break;
  15001. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15002. magFilter = gl.NEAREST;
  15003. if (generateMipMaps) {
  15004. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15005. }
  15006. else {
  15007. minFilter = gl.NEAREST;
  15008. }
  15009. break;
  15010. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15011. magFilter = gl.NEAREST;
  15012. if (generateMipMaps) {
  15013. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15014. }
  15015. else {
  15016. minFilter = gl.LINEAR;
  15017. }
  15018. break;
  15019. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15020. magFilter = gl.NEAREST;
  15021. if (generateMipMaps) {
  15022. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15023. }
  15024. else {
  15025. minFilter = gl.LINEAR;
  15026. }
  15027. break;
  15028. case Engine.TEXTURE_NEAREST_LINEAR:
  15029. magFilter = gl.NEAREST;
  15030. minFilter = gl.LINEAR;
  15031. break;
  15032. case Engine.TEXTURE_NEAREST_NEAREST:
  15033. magFilter = gl.NEAREST;
  15034. minFilter = gl.NEAREST;
  15035. break;
  15036. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15037. magFilter = gl.LINEAR;
  15038. if (generateMipMaps) {
  15039. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15040. }
  15041. else {
  15042. minFilter = gl.NEAREST;
  15043. }
  15044. break;
  15045. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15046. magFilter = gl.LINEAR;
  15047. if (generateMipMaps) {
  15048. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15049. }
  15050. else {
  15051. minFilter = gl.NEAREST;
  15052. }
  15053. break;
  15054. case Engine.TEXTURE_LINEAR_LINEAR:
  15055. magFilter = gl.LINEAR;
  15056. minFilter = gl.LINEAR;
  15057. break;
  15058. case Engine.TEXTURE_LINEAR_NEAREST:
  15059. magFilter = gl.LINEAR;
  15060. minFilter = gl.NEAREST;
  15061. break;
  15062. }
  15063. return {
  15064. min: minFilter,
  15065. mag: magFilter
  15066. };
  15067. };
  15068. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15069. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15070. var img;
  15071. var onload = function () {
  15072. loadedImages[index] = img;
  15073. loadedImages._internalCount++;
  15074. if (scene) {
  15075. scene._removePendingData(img);
  15076. }
  15077. if (loadedImages._internalCount === 6) {
  15078. onfinish(loadedImages);
  15079. }
  15080. };
  15081. var onerror = function (message, exception) {
  15082. if (scene) {
  15083. scene._removePendingData(img);
  15084. }
  15085. if (onErrorCallBack) {
  15086. onErrorCallBack(message, exception);
  15087. }
  15088. };
  15089. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15090. if (scene) {
  15091. scene._addPendingData(img);
  15092. }
  15093. };
  15094. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15095. if (onError === void 0) { onError = null; }
  15096. var loadedImages = [];
  15097. loadedImages._internalCount = 0;
  15098. for (var index = 0; index < 6; index++) {
  15099. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15100. }
  15101. };
  15102. ;
  15103. /** @hidden */
  15104. Engine.prototype._createTexture = function () {
  15105. var texture = this._gl.createTexture();
  15106. if (!texture) {
  15107. throw new Error("Unable to create texture");
  15108. }
  15109. return texture;
  15110. };
  15111. /**
  15112. * Usually called from BABYLON.Texture.ts.
  15113. * Passed information to create a WebGLTexture
  15114. * @param urlArg defines a value which contains one of the following:
  15115. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15116. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15117. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15118. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15119. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15120. * @param scene needed for loading to the correct scene
  15121. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15122. * @param onLoad optional callback to be called upon successful completion
  15123. * @param onError optional callback to be called upon failure
  15124. * @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
  15125. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15126. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15127. * @param forcedExtension defines the extension to use to pick the right loader
  15128. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15129. */
  15130. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15131. var _this = this;
  15132. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15133. if (onLoad === void 0) { onLoad = null; }
  15134. if (onError === void 0) { onError = null; }
  15135. if (buffer === void 0) { buffer = null; }
  15136. if (fallback === void 0) { fallback = null; }
  15137. if (format === void 0) { format = null; }
  15138. if (forcedExtension === void 0) { forcedExtension = null; }
  15139. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15140. var fromData = url.substr(0, 5) === "data:";
  15141. var fromBlob = url.substr(0, 5) === "blob:";
  15142. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15143. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15144. // establish the file extension, if possible
  15145. var lastDot = url.lastIndexOf('.');
  15146. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15147. var loader = null;
  15148. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15149. var availableLoader = _a[_i];
  15150. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15151. loader = availableLoader;
  15152. break;
  15153. }
  15154. }
  15155. if (loader) {
  15156. url = loader.transformUrl(url, this._textureFormatInUse);
  15157. }
  15158. if (scene) {
  15159. scene._addPendingData(texture);
  15160. }
  15161. texture.url = url;
  15162. texture.generateMipMaps = !noMipmap;
  15163. texture.samplingMode = samplingMode;
  15164. texture.invertY = invertY;
  15165. if (!this._doNotHandleContextLost) {
  15166. // Keep a link to the buffer only if we plan to handle context lost
  15167. texture._buffer = buffer;
  15168. }
  15169. var onLoadObserver = null;
  15170. if (onLoad && !fallback) {
  15171. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15172. }
  15173. if (!fallback)
  15174. this._internalTexturesCache.push(texture);
  15175. var onInternalError = function (message, exception) {
  15176. if (scene) {
  15177. scene._removePendingData(texture);
  15178. }
  15179. var customFallback = false;
  15180. if (loader) {
  15181. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15182. if (fallbackUrl) {
  15183. // Add Back
  15184. customFallback = true;
  15185. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15186. }
  15187. }
  15188. if (!customFallback) {
  15189. if (onLoadObserver) {
  15190. texture.onLoadedObservable.remove(onLoadObserver);
  15191. }
  15192. if (BABYLON.Tools.UseFallbackTexture) {
  15193. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15194. }
  15195. }
  15196. if (onError) {
  15197. onError(message || "Unknown error", exception);
  15198. }
  15199. };
  15200. // processing for non-image formats
  15201. if (loader) {
  15202. var callback = function (data) {
  15203. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15204. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15205. done();
  15206. return false;
  15207. }, samplingMode);
  15208. });
  15209. };
  15210. if (!buffer) {
  15211. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15212. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15213. });
  15214. }
  15215. else {
  15216. callback(buffer);
  15217. }
  15218. }
  15219. else {
  15220. var onload = function (img) {
  15221. if (fromBlob && !_this._doNotHandleContextLost) {
  15222. // We need to store the image if we need to rebuild the texture
  15223. // in case of a webgl context lost
  15224. texture._buffer = img;
  15225. }
  15226. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15227. var gl = _this._gl;
  15228. var isPot = (img.width === potWidth && img.height === potHeight);
  15229. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15230. if (isPot) {
  15231. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15232. return false;
  15233. }
  15234. var maxTextureSize = _this._caps.maxTextureSize;
  15235. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15236. _this._prepareWorkingCanvas();
  15237. if (!_this._workingCanvas || !_this._workingContext) {
  15238. return false;
  15239. }
  15240. _this._workingCanvas.width = potWidth;
  15241. _this._workingCanvas.height = potHeight;
  15242. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15243. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15244. texture.width = potWidth;
  15245. texture.height = potHeight;
  15246. return false;
  15247. }
  15248. else {
  15249. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15250. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15251. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15252. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15257. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15258. _this._releaseTexture(source_1);
  15259. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15260. continuationCallback();
  15261. });
  15262. }
  15263. return true;
  15264. }, samplingMode);
  15265. };
  15266. if (!fromData || isBase64) {
  15267. if (buffer instanceof HTMLImageElement) {
  15268. onload(buffer);
  15269. }
  15270. else {
  15271. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15272. }
  15273. }
  15274. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15275. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15276. }
  15277. else {
  15278. onload(buffer);
  15279. }
  15280. }
  15281. return texture;
  15282. };
  15283. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15284. var _this = this;
  15285. var rtt = this.createRenderTargetTexture({
  15286. width: destination.width,
  15287. height: destination.height,
  15288. }, {
  15289. generateMipMaps: false,
  15290. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15291. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15292. generateDepthBuffer: false,
  15293. generateStencilBuffer: false
  15294. });
  15295. if (!this._rescalePostProcess) {
  15296. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15297. }
  15298. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15299. _this._rescalePostProcess.onApply = function (effect) {
  15300. effect._bindTexture("textureSampler", source);
  15301. };
  15302. var hostingScene = scene;
  15303. if (!hostingScene) {
  15304. hostingScene = _this.scenes[_this.scenes.length - 1];
  15305. }
  15306. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15307. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15308. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15309. _this.unBindFramebuffer(rtt);
  15310. _this._releaseTexture(rtt);
  15311. if (onComplete) {
  15312. onComplete();
  15313. }
  15314. });
  15315. };
  15316. /**
  15317. * Update a raw texture
  15318. * @param texture defines the texture to update
  15319. * @param data defines the data to store in the texture
  15320. * @param format defines the format of the data
  15321. * @param invertY defines if data must be stored with Y axis inverted
  15322. * @param compression defines the compression used (null by default)
  15323. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15324. */
  15325. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15326. if (compression === void 0) { compression = null; }
  15327. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15328. if (!texture) {
  15329. return;
  15330. }
  15331. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15332. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15333. // babylon's internalFormat but gl's texImage2D format
  15334. var internalFormat = this._getInternalFormat(format);
  15335. var textureType = this._getWebGLTextureType(type);
  15336. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15337. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15338. if (!this._doNotHandleContextLost) {
  15339. texture._bufferView = data;
  15340. texture.format = format;
  15341. texture.type = type;
  15342. texture.invertY = invertY;
  15343. texture._compression = compression;
  15344. }
  15345. if (texture.width % 4 !== 0) {
  15346. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15347. }
  15348. if (compression && data) {
  15349. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15350. }
  15351. else {
  15352. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15353. }
  15354. if (texture.generateMipMaps) {
  15355. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15356. }
  15357. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15358. // this.resetTextureCache();
  15359. texture.isReady = true;
  15360. };
  15361. /**
  15362. * Creates a raw texture
  15363. * @param data defines the data to store in the texture
  15364. * @param width defines the width of the texture
  15365. * @param height defines the height of the texture
  15366. * @param format defines the format of the data
  15367. * @param generateMipMaps defines if the engine should generate the mip levels
  15368. * @param invertY defines if data must be stored with Y axis inverted
  15369. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15370. * @param compression defines the compression used (null by default)
  15371. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15372. * @returns the raw texture inside an InternalTexture
  15373. */
  15374. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15375. if (compression === void 0) { compression = null; }
  15376. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15377. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15378. texture.baseWidth = width;
  15379. texture.baseHeight = height;
  15380. texture.width = width;
  15381. texture.height = height;
  15382. texture.format = format;
  15383. texture.generateMipMaps = generateMipMaps;
  15384. texture.samplingMode = samplingMode;
  15385. texture.invertY = invertY;
  15386. texture._compression = compression;
  15387. texture.type = type;
  15388. if (!this._doNotHandleContextLost) {
  15389. texture._bufferView = data;
  15390. }
  15391. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15392. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15393. // Filters
  15394. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15396. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15397. if (generateMipMaps) {
  15398. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15399. }
  15400. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15401. this._internalTexturesCache.push(texture);
  15402. return texture;
  15403. };
  15404. /** @hidden */
  15405. Engine.prototype._unpackFlipY = function (value) {
  15406. if (this._unpackFlipYCached !== value) {
  15407. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15408. if (this.enableUnpackFlipYCached) {
  15409. this._unpackFlipYCached = value;
  15410. }
  15411. }
  15412. };
  15413. /** @hidden */
  15414. Engine.prototype._getUnpackAlignement = function () {
  15415. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15416. };
  15417. /**
  15418. * Creates a dynamic texture
  15419. * @param width defines the width of the texture
  15420. * @param height defines the height of the texture
  15421. * @param generateMipMaps defines if the engine should generate the mip levels
  15422. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15423. * @returns the dynamic texture inside an InternalTexture
  15424. */
  15425. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15426. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15427. texture.baseWidth = width;
  15428. texture.baseHeight = height;
  15429. if (generateMipMaps) {
  15430. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15431. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15432. }
  15433. // this.resetTextureCache();
  15434. texture.width = width;
  15435. texture.height = height;
  15436. texture.isReady = false;
  15437. texture.generateMipMaps = generateMipMaps;
  15438. texture.samplingMode = samplingMode;
  15439. this.updateTextureSamplingMode(samplingMode, texture);
  15440. this._internalTexturesCache.push(texture);
  15441. return texture;
  15442. };
  15443. /**
  15444. * Update the sampling mode of a given texture
  15445. * @param samplingMode defines the required sampling mode
  15446. * @param texture defines the texture to update
  15447. */
  15448. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15449. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15450. if (texture.isCube) {
  15451. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15452. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15453. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15454. }
  15455. else if (texture.is3D) {
  15456. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15457. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15458. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15459. }
  15460. else {
  15461. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15462. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15463. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15464. }
  15465. texture.samplingMode = samplingMode;
  15466. };
  15467. /**
  15468. * Update the content of a dynamic texture
  15469. * @param texture defines the texture to update
  15470. * @param canvas defines the canvas containing the source
  15471. * @param invertY defines if data must be stored with Y axis inverted
  15472. * @param premulAlpha defines if alpha is stored as premultiplied
  15473. * @param format defines the format of the data
  15474. */
  15475. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15476. if (premulAlpha === void 0) { premulAlpha = false; }
  15477. if (!texture) {
  15478. return;
  15479. }
  15480. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15481. this._unpackFlipY(invertY);
  15482. if (premulAlpha) {
  15483. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15484. }
  15485. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15486. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15487. if (texture.generateMipMaps) {
  15488. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15489. }
  15490. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15491. if (premulAlpha) {
  15492. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15493. }
  15494. texture.isReady = true;
  15495. };
  15496. /**
  15497. * Update a video texture
  15498. * @param texture defines the texture to update
  15499. * @param video defines the video element to use
  15500. * @param invertY defines if data must be stored with Y axis inverted
  15501. */
  15502. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15503. if (!texture || texture._isDisabled) {
  15504. return;
  15505. }
  15506. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15507. this._unpackFlipY(!invertY); // Video are upside down by default
  15508. try {
  15509. // Testing video texture support
  15510. if (this._videoTextureSupported === undefined) {
  15511. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15512. if (this._gl.getError() !== 0) {
  15513. this._videoTextureSupported = false;
  15514. }
  15515. else {
  15516. this._videoTextureSupported = true;
  15517. }
  15518. }
  15519. // Copy video through the current working canvas if video texture is not supported
  15520. if (!this._videoTextureSupported) {
  15521. if (!texture._workingCanvas) {
  15522. texture._workingCanvas = document.createElement("canvas");
  15523. var context = texture._workingCanvas.getContext("2d");
  15524. if (!context) {
  15525. throw new Error("Unable to get 2d context");
  15526. }
  15527. texture._workingContext = context;
  15528. texture._workingCanvas.width = texture.width;
  15529. texture._workingCanvas.height = texture.height;
  15530. }
  15531. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15532. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15533. }
  15534. else {
  15535. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15536. }
  15537. if (texture.generateMipMaps) {
  15538. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15539. }
  15540. if (!wasPreviouslyBound) {
  15541. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15542. }
  15543. // this.resetTextureCache();
  15544. texture.isReady = true;
  15545. }
  15546. catch (ex) {
  15547. // Something unexpected
  15548. // Let's disable the texture
  15549. texture._isDisabled = true;
  15550. }
  15551. };
  15552. /**
  15553. * Updates a depth texture Comparison Mode and Function.
  15554. * If the comparison Function is equal to 0, the mode will be set to none.
  15555. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15556. * @param texture The texture to set the comparison function for
  15557. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15558. */
  15559. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15560. if (this.webGLVersion === 1) {
  15561. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15562. return;
  15563. }
  15564. var gl = this._gl;
  15565. if (texture.isCube) {
  15566. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15567. if (comparisonFunction === 0) {
  15568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15570. }
  15571. else {
  15572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15574. }
  15575. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15576. }
  15577. else {
  15578. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15579. if (comparisonFunction === 0) {
  15580. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15582. }
  15583. else {
  15584. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15586. }
  15587. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15588. }
  15589. texture._comparisonFunction = comparisonFunction;
  15590. };
  15591. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15592. var width = size.width || size;
  15593. var height = size.height || size;
  15594. internalTexture.baseWidth = width;
  15595. internalTexture.baseHeight = height;
  15596. internalTexture.width = width;
  15597. internalTexture.height = height;
  15598. internalTexture.isReady = true;
  15599. internalTexture.samples = 1;
  15600. internalTexture.generateMipMaps = false;
  15601. internalTexture._generateDepthBuffer = true;
  15602. internalTexture._generateStencilBuffer = generateStencil;
  15603. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15604. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15605. internalTexture._comparisonFunction = comparisonFunction;
  15606. var gl = this._gl;
  15607. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15608. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15609. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15610. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15611. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15612. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15613. if (comparisonFunction === 0) {
  15614. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15615. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15616. }
  15617. else {
  15618. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15619. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15620. }
  15621. };
  15622. /**
  15623. * Creates a depth stencil texture.
  15624. * This is only available in WebGL 2 or with the depth texture extension available.
  15625. * @param size The size of face edge in the texture.
  15626. * @param options The options defining the texture.
  15627. * @returns The texture
  15628. */
  15629. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15630. if (options.isCube) {
  15631. var width = size.width || size;
  15632. return this._createDepthStencilCubeTexture(width, options);
  15633. }
  15634. else {
  15635. return this._createDepthStencilTexture(size, options);
  15636. }
  15637. };
  15638. /**
  15639. * Creates a depth stencil texture.
  15640. * This is only available in WebGL 2 or with the depth texture extension available.
  15641. * @param size The size of face edge in the texture.
  15642. * @param options The options defining the texture.
  15643. * @returns The texture
  15644. */
  15645. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15646. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15647. if (!this._caps.depthTextureExtension) {
  15648. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15649. return internalTexture;
  15650. }
  15651. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15652. var gl = this._gl;
  15653. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15654. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15655. if (this.webGLVersion > 1) {
  15656. if (internalOptions.generateStencil) {
  15657. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15658. }
  15659. else {
  15660. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15661. }
  15662. }
  15663. else {
  15664. if (internalOptions.generateStencil) {
  15665. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15666. }
  15667. else {
  15668. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15669. }
  15670. }
  15671. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15672. return internalTexture;
  15673. };
  15674. /**
  15675. * Creates a depth stencil cube texture.
  15676. * This is only available in WebGL 2.
  15677. * @param size The size of face edge in the cube texture.
  15678. * @param options The options defining the cube texture.
  15679. * @returns The cube texture
  15680. */
  15681. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15682. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15683. internalTexture.isCube = true;
  15684. if (this.webGLVersion === 1) {
  15685. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15686. return internalTexture;
  15687. }
  15688. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15689. var gl = this._gl;
  15690. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15691. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15692. // Create the depth/stencil buffer
  15693. for (var face = 0; face < 6; face++) {
  15694. if (internalOptions.generateStencil) {
  15695. 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);
  15696. }
  15697. else {
  15698. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15699. }
  15700. }
  15701. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15702. return internalTexture;
  15703. };
  15704. /**
  15705. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15706. * @param renderTarget The render target to set the frame buffer for
  15707. */
  15708. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15709. // Create the framebuffer
  15710. var internalTexture = renderTarget.getInternalTexture();
  15711. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15712. return;
  15713. }
  15714. var gl = this._gl;
  15715. var depthStencilTexture = renderTarget.depthStencilTexture;
  15716. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15717. if (depthStencilTexture.isCube) {
  15718. if (depthStencilTexture._generateStencilBuffer) {
  15719. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15720. }
  15721. else {
  15722. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15723. }
  15724. }
  15725. else {
  15726. if (depthStencilTexture._generateStencilBuffer) {
  15727. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15728. }
  15729. else {
  15730. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15731. }
  15732. }
  15733. this.bindUnboundFramebuffer(null);
  15734. };
  15735. /**
  15736. * Creates a new render target texture
  15737. * @param size defines the size of the texture
  15738. * @param options defines the options used to create the texture
  15739. * @returns a new render target texture stored in an InternalTexture
  15740. */
  15741. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15742. var fullOptions = new RenderTargetCreationOptions();
  15743. if (options !== undefined && typeof options === "object") {
  15744. fullOptions.generateMipMaps = options.generateMipMaps;
  15745. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15746. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15747. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15748. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15749. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15750. }
  15751. else {
  15752. fullOptions.generateMipMaps = options;
  15753. fullOptions.generateDepthBuffer = true;
  15754. fullOptions.generateStencilBuffer = false;
  15755. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15756. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15757. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15758. }
  15759. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15760. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15761. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15762. }
  15763. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15764. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15765. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15766. }
  15767. var gl = this._gl;
  15768. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15769. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15770. var width = size.width || size;
  15771. var height = size.height || size;
  15772. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15773. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15774. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15775. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15776. }
  15777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15781. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15782. // Create the framebuffer
  15783. var currentFrameBuffer = this._currentFramebuffer;
  15784. var framebuffer = gl.createFramebuffer();
  15785. this.bindUnboundFramebuffer(framebuffer);
  15786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15787. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15788. if (fullOptions.generateMipMaps) {
  15789. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15790. }
  15791. // Unbind
  15792. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15793. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15794. this.bindUnboundFramebuffer(currentFrameBuffer);
  15795. texture._framebuffer = framebuffer;
  15796. texture.baseWidth = width;
  15797. texture.baseHeight = height;
  15798. texture.width = width;
  15799. texture.height = height;
  15800. texture.isReady = true;
  15801. texture.samples = 1;
  15802. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15803. texture.samplingMode = fullOptions.samplingMode;
  15804. texture.type = fullOptions.type;
  15805. texture.format = fullOptions.format;
  15806. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15807. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15808. // this.resetTextureCache();
  15809. this._internalTexturesCache.push(texture);
  15810. return texture;
  15811. };
  15812. /**
  15813. * Create a multi render target texture
  15814. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15815. * @param size defines the size of the texture
  15816. * @param options defines the creation options
  15817. * @returns the cube texture as an InternalTexture
  15818. */
  15819. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15820. var generateMipMaps = false;
  15821. var generateDepthBuffer = true;
  15822. var generateStencilBuffer = false;
  15823. var generateDepthTexture = false;
  15824. var textureCount = 1;
  15825. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15826. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15827. var types = new Array();
  15828. var samplingModes = new Array();
  15829. if (options !== undefined) {
  15830. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15831. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15832. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15833. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15834. textureCount = options.textureCount || 1;
  15835. if (options.types) {
  15836. types = options.types;
  15837. }
  15838. if (options.samplingModes) {
  15839. samplingModes = options.samplingModes;
  15840. }
  15841. }
  15842. var gl = this._gl;
  15843. // Create the framebuffer
  15844. var framebuffer = gl.createFramebuffer();
  15845. this.bindUnboundFramebuffer(framebuffer);
  15846. var width = size.width || size;
  15847. var height = size.height || size;
  15848. var textures = [];
  15849. var attachments = [];
  15850. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15851. for (var i = 0; i < textureCount; i++) {
  15852. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15853. var type = types[i] || defaultType;
  15854. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15855. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15856. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15857. }
  15858. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15859. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15860. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15861. }
  15862. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15863. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15864. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15865. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15866. }
  15867. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15868. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15869. textures.push(texture);
  15870. attachments.push(attachment);
  15871. gl.activeTexture(gl["TEXTURE" + i]);
  15872. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15875. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15876. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15877. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15878. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15879. if (generateMipMaps) {
  15880. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15881. }
  15882. // Unbind
  15883. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15884. texture._framebuffer = framebuffer;
  15885. texture._depthStencilBuffer = depthStencilBuffer;
  15886. texture.baseWidth = width;
  15887. texture.baseHeight = height;
  15888. texture.width = width;
  15889. texture.height = height;
  15890. texture.isReady = true;
  15891. texture.samples = 1;
  15892. texture.generateMipMaps = generateMipMaps;
  15893. texture.samplingMode = samplingMode;
  15894. texture.type = type;
  15895. texture._generateDepthBuffer = generateDepthBuffer;
  15896. texture._generateStencilBuffer = generateStencilBuffer;
  15897. texture._attachments = attachments;
  15898. this._internalTexturesCache.push(texture);
  15899. }
  15900. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15901. // Depth texture
  15902. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15903. gl.activeTexture(gl.TEXTURE0);
  15904. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15905. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15906. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15907. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15909. 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);
  15910. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15911. depthTexture._framebuffer = framebuffer;
  15912. depthTexture.baseWidth = width;
  15913. depthTexture.baseHeight = height;
  15914. depthTexture.width = width;
  15915. depthTexture.height = height;
  15916. depthTexture.isReady = true;
  15917. depthTexture.samples = 1;
  15918. depthTexture.generateMipMaps = generateMipMaps;
  15919. depthTexture.samplingMode = gl.NEAREST;
  15920. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15921. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15922. textures.push(depthTexture);
  15923. this._internalTexturesCache.push(depthTexture);
  15924. }
  15925. gl.drawBuffers(attachments);
  15926. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15927. this.bindUnboundFramebuffer(null);
  15928. this.resetTextureCache();
  15929. return textures;
  15930. };
  15931. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15932. if (samples === void 0) { samples = 1; }
  15933. var depthStencilBuffer = null;
  15934. var gl = this._gl;
  15935. // Create the depth/stencil buffer
  15936. if (generateStencilBuffer) {
  15937. depthStencilBuffer = gl.createRenderbuffer();
  15938. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15939. if (samples > 1) {
  15940. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15941. }
  15942. else {
  15943. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15944. }
  15945. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15946. }
  15947. else if (generateDepthBuffer) {
  15948. depthStencilBuffer = gl.createRenderbuffer();
  15949. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15950. if (samples > 1) {
  15951. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15952. }
  15953. else {
  15954. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15955. }
  15956. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15957. }
  15958. return depthStencilBuffer;
  15959. };
  15960. /**
  15961. * Updates the sample count of a render target texture
  15962. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15963. * @param texture defines the texture to update
  15964. * @param samples defines the sample count to set
  15965. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15966. */
  15967. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15968. if (this.webGLVersion < 2 || !texture) {
  15969. return 1;
  15970. }
  15971. if (texture.samples === samples) {
  15972. return samples;
  15973. }
  15974. var gl = this._gl;
  15975. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15976. // Dispose previous render buffers
  15977. if (texture._depthStencilBuffer) {
  15978. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15979. texture._depthStencilBuffer = null;
  15980. }
  15981. if (texture._MSAAFramebuffer) {
  15982. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15983. texture._MSAAFramebuffer = null;
  15984. }
  15985. if (texture._MSAARenderBuffer) {
  15986. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15987. texture._MSAARenderBuffer = null;
  15988. }
  15989. if (samples > 1) {
  15990. var framebuffer = gl.createFramebuffer();
  15991. if (!framebuffer) {
  15992. throw new Error("Unable to create multi sampled framebuffer");
  15993. }
  15994. texture._MSAAFramebuffer = framebuffer;
  15995. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15996. var colorRenderbuffer = gl.createRenderbuffer();
  15997. if (!colorRenderbuffer) {
  15998. throw new Error("Unable to create multi sampled framebuffer");
  15999. }
  16000. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16001. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16002. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16003. texture._MSAARenderBuffer = colorRenderbuffer;
  16004. }
  16005. else {
  16006. this.bindUnboundFramebuffer(texture._framebuffer);
  16007. }
  16008. texture.samples = samples;
  16009. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16010. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16011. this.bindUnboundFramebuffer(null);
  16012. return samples;
  16013. };
  16014. /**
  16015. * Update the sample count for a given multiple render target texture
  16016. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16017. * @param textures defines the textures to update
  16018. * @param samples defines the sample count to set
  16019. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16020. */
  16021. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16022. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16023. return 1;
  16024. }
  16025. if (textures[0].samples === samples) {
  16026. return samples;
  16027. }
  16028. var gl = this._gl;
  16029. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16030. // Dispose previous render buffers
  16031. if (textures[0]._depthStencilBuffer) {
  16032. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16033. textures[0]._depthStencilBuffer = null;
  16034. }
  16035. if (textures[0]._MSAAFramebuffer) {
  16036. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16037. textures[0]._MSAAFramebuffer = null;
  16038. }
  16039. for (var i = 0; i < textures.length; i++) {
  16040. if (textures[i]._MSAARenderBuffer) {
  16041. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16042. textures[i]._MSAARenderBuffer = null;
  16043. }
  16044. }
  16045. if (samples > 1) {
  16046. var framebuffer = gl.createFramebuffer();
  16047. if (!framebuffer) {
  16048. throw new Error("Unable to create multi sampled framebuffer");
  16049. }
  16050. this.bindUnboundFramebuffer(framebuffer);
  16051. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16052. var attachments = [];
  16053. for (var i = 0; i < textures.length; i++) {
  16054. var texture = textures[i];
  16055. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16056. var colorRenderbuffer = gl.createRenderbuffer();
  16057. if (!colorRenderbuffer) {
  16058. throw new Error("Unable to create multi sampled framebuffer");
  16059. }
  16060. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16061. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16062. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16063. texture._MSAAFramebuffer = framebuffer;
  16064. texture._MSAARenderBuffer = colorRenderbuffer;
  16065. texture.samples = samples;
  16066. texture._depthStencilBuffer = depthStencilBuffer;
  16067. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16068. attachments.push(attachment);
  16069. }
  16070. gl.drawBuffers(attachments);
  16071. }
  16072. else {
  16073. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16074. }
  16075. this.bindUnboundFramebuffer(null);
  16076. return samples;
  16077. };
  16078. /** @hidden */
  16079. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16080. if (faceIndex === void 0) { faceIndex = 0; }
  16081. if (lod === void 0) { lod = 0; }
  16082. var gl = this._gl;
  16083. var target = gl.TEXTURE_2D;
  16084. if (texture.isCube) {
  16085. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16086. }
  16087. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16088. };
  16089. /** @hidden */
  16090. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16091. if (faceIndex === void 0) { faceIndex = 0; }
  16092. if (lod === void 0) { lod = 0; }
  16093. var gl = this._gl;
  16094. var textureType = this._getWebGLTextureType(texture.type);
  16095. var format = this._getInternalFormat(texture.format);
  16096. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16097. this._unpackFlipY(texture.invertY);
  16098. var target = gl.TEXTURE_2D;
  16099. if (texture.isCube) {
  16100. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16101. }
  16102. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16103. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16104. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16105. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16106. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16107. };
  16108. /** @hidden */
  16109. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16110. if (faceIndex === void 0) { faceIndex = 0; }
  16111. if (lod === void 0) { lod = 0; }
  16112. var gl = this._gl;
  16113. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16114. this._bindTextureDirectly(bindTarget, texture, true);
  16115. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16116. this._bindTextureDirectly(bindTarget, null, true);
  16117. };
  16118. /** @hidden */
  16119. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16120. if (faceIndex === void 0) { faceIndex = 0; }
  16121. if (lod === void 0) { lod = 0; }
  16122. var gl = this._gl;
  16123. var textureType = this._getWebGLTextureType(texture.type);
  16124. var format = this._getInternalFormat(texture.format);
  16125. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16126. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16127. this._bindTextureDirectly(bindTarget, texture, true);
  16128. this._unpackFlipY(texture.invertY);
  16129. var target = gl.TEXTURE_2D;
  16130. if (texture.isCube) {
  16131. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16132. }
  16133. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16134. this._bindTextureDirectly(bindTarget, null, true);
  16135. };
  16136. /**
  16137. * Creates a new render target cube texture
  16138. * @param size defines the size of the texture
  16139. * @param options defines the options used to create the texture
  16140. * @returns a new render target cube texture stored in an InternalTexture
  16141. */
  16142. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16143. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16144. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16145. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16146. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16147. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16148. }
  16149. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16150. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16151. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16152. }
  16153. var gl = this._gl;
  16154. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16155. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16156. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16157. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16158. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16159. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16160. }
  16161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16165. for (var face = 0; face < 6; face++) {
  16166. 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);
  16167. }
  16168. // Create the framebuffer
  16169. var framebuffer = gl.createFramebuffer();
  16170. this.bindUnboundFramebuffer(framebuffer);
  16171. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16172. // MipMaps
  16173. if (fullOptions.generateMipMaps) {
  16174. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16175. }
  16176. // Unbind
  16177. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16178. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16179. this.bindUnboundFramebuffer(null);
  16180. texture._framebuffer = framebuffer;
  16181. texture.width = size;
  16182. texture.height = size;
  16183. texture.isReady = true;
  16184. texture.isCube = true;
  16185. texture.samples = 1;
  16186. texture.generateMipMaps = fullOptions.generateMipMaps;
  16187. texture.samplingMode = fullOptions.samplingMode;
  16188. texture.type = fullOptions.type;
  16189. texture.format = fullOptions.format;
  16190. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16191. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16192. this._internalTexturesCache.push(texture);
  16193. return texture;
  16194. };
  16195. /**
  16196. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16197. * @param rootUrl defines the url where the file to load is located
  16198. * @param scene defines the current scene
  16199. * @param lodScale defines scale to apply to the mip map selection
  16200. * @param lodOffset defines offset to apply to the mip map selection
  16201. * @param onLoad defines an optional callback raised when the texture is loaded
  16202. * @param onError defines an optional callback raised if there is an issue to load the texture
  16203. * @param format defines the format of the data
  16204. * @param forcedExtension defines the extension to use to pick the right loader
  16205. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16206. * @returns the cube texture as an InternalTexture
  16207. */
  16208. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16209. var _this = this;
  16210. if (onLoad === void 0) { onLoad = null; }
  16211. if (onError === void 0) { onError = null; }
  16212. if (forcedExtension === void 0) { forcedExtension = null; }
  16213. if (createPolynomials === void 0) { createPolynomials = true; }
  16214. var callback = function (loadData) {
  16215. if (!loadData) {
  16216. if (onLoad) {
  16217. onLoad(null);
  16218. }
  16219. return;
  16220. }
  16221. var texture = loadData.texture;
  16222. if (!createPolynomials) {
  16223. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16224. }
  16225. else if (loadData.info.sphericalPolynomial) {
  16226. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16227. }
  16228. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16229. if (_this._caps.textureLOD) {
  16230. // Do not add extra process if texture lod is supported.
  16231. if (onLoad) {
  16232. onLoad(texture);
  16233. }
  16234. return;
  16235. }
  16236. var mipSlices = 3;
  16237. var gl = _this._gl;
  16238. var width = loadData.width;
  16239. if (!width) {
  16240. return;
  16241. }
  16242. var textures = [];
  16243. for (var i = 0; i < mipSlices; i++) {
  16244. //compute LOD from even spacing in smoothness (matching shader calculation)
  16245. var smoothness = i / (mipSlices - 1);
  16246. var roughness = 1 - smoothness;
  16247. var minLODIndex = lodOffset; // roughness = 0
  16248. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16249. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16250. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16251. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16252. glTextureFromLod.type = texture.type;
  16253. glTextureFromLod.format = texture.format;
  16254. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16255. glTextureFromLod.height = glTextureFromLod.width;
  16256. glTextureFromLod.isCube = true;
  16257. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16262. if (loadData.isDDS) {
  16263. var info = loadData.info;
  16264. var data = loadData.data;
  16265. _this._unpackFlipY(info.isCompressed);
  16266. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16267. }
  16268. else {
  16269. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16270. }
  16271. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16272. // Wrap in a base texture for easy binding.
  16273. var lodTexture = new BABYLON.BaseTexture(scene);
  16274. lodTexture.isCube = true;
  16275. lodTexture._texture = glTextureFromLod;
  16276. glTextureFromLod.isReady = true;
  16277. textures.push(lodTexture);
  16278. }
  16279. texture._lodTextureHigh = textures[2];
  16280. texture._lodTextureMid = textures[1];
  16281. texture._lodTextureLow = textures[0];
  16282. if (onLoad) {
  16283. onLoad(texture);
  16284. }
  16285. };
  16286. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16287. };
  16288. /**
  16289. * Creates a cube texture
  16290. * @param rootUrl defines the url where the files to load is located
  16291. * @param scene defines the current scene
  16292. * @param files defines the list of files to load (1 per face)
  16293. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16294. * @param onLoad defines an optional callback raised when the texture is loaded
  16295. * @param onError defines an optional callback raised if there is an issue to load the texture
  16296. * @param format defines the format of the data
  16297. * @param forcedExtension defines the extension to use to pick the right loader
  16298. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16299. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16300. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16301. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16302. * @returns the cube texture as an InternalTexture
  16303. */
  16304. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16305. var _this = this;
  16306. if (onLoad === void 0) { onLoad = null; }
  16307. if (onError === void 0) { onError = null; }
  16308. if (forcedExtension === void 0) { forcedExtension = null; }
  16309. if (createPolynomials === void 0) { createPolynomials = false; }
  16310. if (lodScale === void 0) { lodScale = 0; }
  16311. if (lodOffset === void 0) { lodOffset = 0; }
  16312. if (fallback === void 0) { fallback = null; }
  16313. var gl = this._gl;
  16314. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16315. texture.isCube = true;
  16316. texture.url = rootUrl;
  16317. texture.generateMipMaps = !noMipmap;
  16318. texture._lodGenerationScale = lodScale;
  16319. texture._lodGenerationOffset = lodOffset;
  16320. if (!this._doNotHandleContextLost) {
  16321. texture._extension = forcedExtension;
  16322. texture._files = files;
  16323. }
  16324. var lastDot = rootUrl.lastIndexOf('.');
  16325. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16326. var loader = null;
  16327. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16328. var availableLoader = _a[_i];
  16329. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16330. loader = availableLoader;
  16331. break;
  16332. }
  16333. }
  16334. var onInternalError = function (request, exception) {
  16335. if (loader) {
  16336. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16337. if (fallbackUrl) {
  16338. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16339. }
  16340. }
  16341. if (onError && request) {
  16342. onError(request.status + " " + request.statusText, exception);
  16343. }
  16344. };
  16345. if (loader) {
  16346. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16347. var onloaddata = function (data) {
  16348. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16349. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16350. };
  16351. if (files && files.length === 6) {
  16352. if (loader.supportCascades) {
  16353. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16354. }
  16355. else if (onError) {
  16356. onError("Textures type does not support cascades.");
  16357. }
  16358. }
  16359. else {
  16360. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16361. }
  16362. }
  16363. else {
  16364. if (!files) {
  16365. throw new Error("Cannot load cubemap because files were not defined");
  16366. }
  16367. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16368. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16369. var height = width;
  16370. _this._prepareWorkingCanvas();
  16371. if (!_this._workingCanvas || !_this._workingContext) {
  16372. return;
  16373. }
  16374. _this._workingCanvas.width = width;
  16375. _this._workingCanvas.height = height;
  16376. var faces = [
  16377. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16378. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16379. ];
  16380. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16381. _this._unpackFlipY(false);
  16382. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16383. for (var index = 0; index < faces.length; index++) {
  16384. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16385. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16386. }
  16387. if (!noMipmap) {
  16388. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16389. }
  16390. _this._setCubeMapTextureParams(!noMipmap);
  16391. texture.width = width;
  16392. texture.height = height;
  16393. texture.isReady = true;
  16394. if (format) {
  16395. texture.format = format;
  16396. }
  16397. texture.onLoadedObservable.notifyObservers(texture);
  16398. texture.onLoadedObservable.clear();
  16399. if (onLoad) {
  16400. onLoad();
  16401. }
  16402. }, files, onError);
  16403. }
  16404. this._internalTexturesCache.push(texture);
  16405. return texture;
  16406. };
  16407. /**
  16408. * @hidden
  16409. */
  16410. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16411. var gl = this._gl;
  16412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16416. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16417. // this.resetTextureCache();
  16418. };
  16419. /**
  16420. * Update a raw cube texture
  16421. * @param texture defines the texture to udpdate
  16422. * @param data defines the data to store
  16423. * @param format defines the data format
  16424. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16425. * @param invertY defines if data must be stored with Y axis inverted
  16426. * @param compression defines the compression used (null by default)
  16427. * @param level defines which level of the texture to update
  16428. */
  16429. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16430. if (compression === void 0) { compression = null; }
  16431. if (level === void 0) { level = 0; }
  16432. texture._bufferViewArray = data;
  16433. texture.format = format;
  16434. texture.type = type;
  16435. texture.invertY = invertY;
  16436. texture._compression = compression;
  16437. var gl = this._gl;
  16438. var textureType = this._getWebGLTextureType(type);
  16439. var internalFormat = this._getInternalFormat(format);
  16440. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16441. var needConversion = false;
  16442. if (internalFormat === gl.RGB) {
  16443. internalFormat = gl.RGBA;
  16444. needConversion = true;
  16445. }
  16446. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16447. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16448. if (texture.width % 4 !== 0) {
  16449. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16450. }
  16451. // Data are known to be in +X +Y +Z -X -Y -Z
  16452. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16453. var faceData = data[faceIndex];
  16454. if (compression) {
  16455. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16456. }
  16457. else {
  16458. if (needConversion) {
  16459. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16460. }
  16461. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16462. }
  16463. }
  16464. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16465. if (isPot && texture.generateMipMaps && level === 0) {
  16466. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16467. }
  16468. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16469. // this.resetTextureCache();
  16470. texture.isReady = true;
  16471. };
  16472. /**
  16473. * Creates a new raw cube texture
  16474. * @param data defines the array of data to use to create each face
  16475. * @param size defines the size of the textures
  16476. * @param format defines the format of the data
  16477. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16478. * @param generateMipMaps defines if the engine should generate the mip levels
  16479. * @param invertY defines if data must be stored with Y axis inverted
  16480. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16481. * @param compression defines the compression used (null by default)
  16482. * @returns the cube texture as an InternalTexture
  16483. */
  16484. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16485. if (compression === void 0) { compression = null; }
  16486. var gl = this._gl;
  16487. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16488. texture.isCube = true;
  16489. texture.format = format;
  16490. texture.type = type;
  16491. if (!this._doNotHandleContextLost) {
  16492. texture._bufferViewArray = data;
  16493. }
  16494. var textureType = this._getWebGLTextureType(type);
  16495. var internalFormat = this._getInternalFormat(format);
  16496. if (internalFormat === gl.RGB) {
  16497. internalFormat = gl.RGBA;
  16498. }
  16499. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16500. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16501. generateMipMaps = false;
  16502. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16503. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16504. }
  16505. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16506. generateMipMaps = false;
  16507. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16508. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16509. }
  16510. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16511. generateMipMaps = false;
  16512. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16513. }
  16514. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16515. generateMipMaps = false;
  16516. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16517. }
  16518. var width = size;
  16519. var height = width;
  16520. texture.width = width;
  16521. texture.height = height;
  16522. // Double check on POT to generate Mips.
  16523. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16524. if (!isPot) {
  16525. generateMipMaps = false;
  16526. }
  16527. // Upload data if needed. The texture won't be ready until then.
  16528. if (data) {
  16529. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16530. }
  16531. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16532. // Filters
  16533. if (data && generateMipMaps) {
  16534. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16535. }
  16536. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16541. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16542. texture.generateMipMaps = generateMipMaps;
  16543. return texture;
  16544. };
  16545. /**
  16546. * Creates a new raw cube texture from a specified url
  16547. * @param url defines the url where the data is located
  16548. * @param scene defines the current scene
  16549. * @param size defines the size of the textures
  16550. * @param format defines the format of the data
  16551. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16552. * @param noMipmap defines if the engine should avoid generating the mip levels
  16553. * @param callback defines a callback used to extract texture data from loaded data
  16554. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16555. * @param onLoad defines a callback called when texture is loaded
  16556. * @param onError defines a callback called if there is an error
  16557. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16558. * @param invertY defines if data must be stored with Y axis inverted
  16559. * @returns the cube texture as an InternalTexture
  16560. */
  16561. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16562. var _this = this;
  16563. if (onLoad === void 0) { onLoad = null; }
  16564. if (onError === void 0) { onError = null; }
  16565. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16566. if (invertY === void 0) { invertY = false; }
  16567. var gl = this._gl;
  16568. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16569. scene._addPendingData(texture);
  16570. texture.url = url;
  16571. this._internalTexturesCache.push(texture);
  16572. var onerror = function (request, exception) {
  16573. scene._removePendingData(texture);
  16574. if (onError && request) {
  16575. onError(request.status + " " + request.statusText, exception);
  16576. }
  16577. };
  16578. var internalCallback = function (data) {
  16579. var width = texture.width;
  16580. var faceDataArrays = callback(data);
  16581. if (!faceDataArrays) {
  16582. return;
  16583. }
  16584. if (mipmapGenerator) {
  16585. var textureType = _this._getWebGLTextureType(type);
  16586. var internalFormat = _this._getInternalFormat(format);
  16587. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16588. var needConversion = false;
  16589. if (internalFormat === gl.RGB) {
  16590. internalFormat = gl.RGBA;
  16591. needConversion = true;
  16592. }
  16593. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16594. _this._unpackFlipY(false);
  16595. var mipData = mipmapGenerator(faceDataArrays);
  16596. for (var level = 0; level < mipData.length; level++) {
  16597. var mipSize = width >> level;
  16598. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16599. var mipFaceData = mipData[level][faceIndex];
  16600. if (needConversion) {
  16601. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16602. }
  16603. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16604. }
  16605. }
  16606. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16607. }
  16608. else {
  16609. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16610. }
  16611. texture.isReady = true;
  16612. // this.resetTextureCache();
  16613. scene._removePendingData(texture);
  16614. if (onLoad) {
  16615. onLoad();
  16616. }
  16617. };
  16618. this._loadFile(url, function (data) {
  16619. internalCallback(data);
  16620. }, undefined, scene.database, true, onerror);
  16621. return texture;
  16622. };
  16623. ;
  16624. /**
  16625. * Update a raw 3D texture
  16626. * @param texture defines the texture to update
  16627. * @param data defines the data to store
  16628. * @param format defines the data format
  16629. * @param invertY defines if data must be stored with Y axis inverted
  16630. * @param compression defines the used compression (can be null)
  16631. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16632. */
  16633. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16634. if (compression === void 0) { compression = null; }
  16635. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16636. var internalType = this._getWebGLTextureType(textureType);
  16637. var internalFormat = this._getInternalFormat(format);
  16638. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16639. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16640. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16641. if (!this._doNotHandleContextLost) {
  16642. texture._bufferView = data;
  16643. texture.format = format;
  16644. texture.invertY = invertY;
  16645. texture._compression = compression;
  16646. }
  16647. if (texture.width % 4 !== 0) {
  16648. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16649. }
  16650. if (compression && data) {
  16651. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16652. }
  16653. else {
  16654. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16655. }
  16656. if (texture.generateMipMaps) {
  16657. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16658. }
  16659. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16660. // this.resetTextureCache();
  16661. texture.isReady = true;
  16662. };
  16663. /**
  16664. * Creates a new raw 3D texture
  16665. * @param data defines the data used to create the texture
  16666. * @param width defines the width of the texture
  16667. * @param height defines the height of the texture
  16668. * @param depth defines the depth of the texture
  16669. * @param format defines the format of the texture
  16670. * @param generateMipMaps defines if the engine must generate mip levels
  16671. * @param invertY defines if data must be stored with Y axis inverted
  16672. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16673. * @param compression defines the compressed used (can be null)
  16674. * @param textureType defines the compressed used (can be null)
  16675. * @returns a new raw 3D texture (stored in an InternalTexture)
  16676. */
  16677. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16678. if (compression === void 0) { compression = null; }
  16679. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16680. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16681. texture.baseWidth = width;
  16682. texture.baseHeight = height;
  16683. texture.baseDepth = depth;
  16684. texture.width = width;
  16685. texture.height = height;
  16686. texture.depth = depth;
  16687. texture.format = format;
  16688. texture.type = textureType;
  16689. texture.generateMipMaps = generateMipMaps;
  16690. texture.samplingMode = samplingMode;
  16691. texture.is3D = true;
  16692. if (!this._doNotHandleContextLost) {
  16693. texture._bufferView = data;
  16694. }
  16695. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16696. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16697. // Filters
  16698. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16699. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16700. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16701. if (generateMipMaps) {
  16702. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16703. }
  16704. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16705. this._internalTexturesCache.push(texture);
  16706. return texture;
  16707. };
  16708. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16709. var gl = this._gl;
  16710. if (!gl) {
  16711. return;
  16712. }
  16713. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16716. if (!noMipmap && !isCompressed) {
  16717. gl.generateMipmap(gl.TEXTURE_2D);
  16718. }
  16719. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16720. // this.resetTextureCache();
  16721. if (scene) {
  16722. scene._removePendingData(texture);
  16723. }
  16724. texture.onLoadedObservable.notifyObservers(texture);
  16725. texture.onLoadedObservable.clear();
  16726. };
  16727. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16728. var _this = this;
  16729. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16730. var maxTextureSize = this.getCaps().maxTextureSize;
  16731. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16732. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16733. var gl = this._gl;
  16734. if (!gl) {
  16735. return;
  16736. }
  16737. if (!texture._webGLTexture) {
  16738. // this.resetTextureCache();
  16739. if (scene) {
  16740. scene._removePendingData(texture);
  16741. }
  16742. return;
  16743. }
  16744. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16745. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16746. texture.baseWidth = width;
  16747. texture.baseHeight = height;
  16748. texture.width = potWidth;
  16749. texture.height = potHeight;
  16750. texture.isReady = true;
  16751. if (processFunction(potWidth, potHeight, function () {
  16752. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16753. })) {
  16754. // Returning as texture needs extra async steps
  16755. return;
  16756. }
  16757. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16758. };
  16759. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16760. // Create new RGBA data container.
  16761. var rgbaData;
  16762. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16763. rgbaData = new Float32Array(width * height * 4);
  16764. }
  16765. else {
  16766. rgbaData = new Uint32Array(width * height * 4);
  16767. }
  16768. // Convert each pixel.
  16769. for (var x = 0; x < width; x++) {
  16770. for (var y = 0; y < height; y++) {
  16771. var index = (y * width + x) * 3;
  16772. var newIndex = (y * width + x) * 4;
  16773. // Map Old Value to new value.
  16774. rgbaData[newIndex + 0] = rgbData[index + 0];
  16775. rgbaData[newIndex + 1] = rgbData[index + 1];
  16776. rgbaData[newIndex + 2] = rgbData[index + 2];
  16777. // Add fully opaque alpha channel.
  16778. rgbaData[newIndex + 3] = 1;
  16779. }
  16780. }
  16781. return rgbaData;
  16782. };
  16783. /** @hidden */
  16784. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16785. var gl = this._gl;
  16786. if (texture._framebuffer) {
  16787. gl.deleteFramebuffer(texture._framebuffer);
  16788. texture._framebuffer = null;
  16789. }
  16790. if (texture._depthStencilBuffer) {
  16791. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16792. texture._depthStencilBuffer = null;
  16793. }
  16794. if (texture._MSAAFramebuffer) {
  16795. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16796. texture._MSAAFramebuffer = null;
  16797. }
  16798. if (texture._MSAARenderBuffer) {
  16799. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16800. texture._MSAARenderBuffer = null;
  16801. }
  16802. };
  16803. /** @hidden */
  16804. Engine.prototype._releaseTexture = function (texture) {
  16805. var gl = this._gl;
  16806. this._releaseFramebufferObjects(texture);
  16807. gl.deleteTexture(texture._webGLTexture);
  16808. // Unbind channels
  16809. this.unbindAllTextures();
  16810. var index = this._internalTexturesCache.indexOf(texture);
  16811. if (index !== -1) {
  16812. this._internalTexturesCache.splice(index, 1);
  16813. }
  16814. // Integrated fixed lod samplers.
  16815. if (texture._lodTextureHigh) {
  16816. texture._lodTextureHigh.dispose();
  16817. }
  16818. if (texture._lodTextureMid) {
  16819. texture._lodTextureMid.dispose();
  16820. }
  16821. if (texture._lodTextureLow) {
  16822. texture._lodTextureLow.dispose();
  16823. }
  16824. // Set output texture of post process to null if the texture has been released/disposed
  16825. this.scenes.forEach(function (scene) {
  16826. scene.postProcesses.forEach(function (postProcess) {
  16827. if (postProcess._outputTexture == texture) {
  16828. postProcess._outputTexture = null;
  16829. }
  16830. });
  16831. scene.cameras.forEach(function (camera) {
  16832. camera._postProcesses.forEach(function (postProcess) {
  16833. if (postProcess) {
  16834. if (postProcess._outputTexture == texture) {
  16835. postProcess._outputTexture = null;
  16836. }
  16837. }
  16838. });
  16839. });
  16840. });
  16841. };
  16842. Engine.prototype.setProgram = function (program) {
  16843. if (this._currentProgram !== program) {
  16844. this._gl.useProgram(program);
  16845. this._currentProgram = program;
  16846. }
  16847. };
  16848. /**
  16849. * Binds an effect to the webGL context
  16850. * @param effect defines the effect to bind
  16851. */
  16852. Engine.prototype.bindSamplers = function (effect) {
  16853. this.setProgram(effect.getProgram());
  16854. var samplers = effect.getSamplers();
  16855. for (var index = 0; index < samplers.length; index++) {
  16856. var uniform = effect.getUniform(samplers[index]);
  16857. if (uniform) {
  16858. this._boundUniforms[index] = uniform;
  16859. }
  16860. }
  16861. this._currentEffect = null;
  16862. };
  16863. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16864. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16865. return;
  16866. }
  16867. // Remove
  16868. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16869. // Bind last to it
  16870. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16871. // Bind to dummy
  16872. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16873. };
  16874. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16875. if (!internalTexture) {
  16876. return -1;
  16877. }
  16878. internalTexture._initialSlot = channel;
  16879. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16880. if (channel !== internalTexture._designatedSlot) {
  16881. this._textureCollisions.addCount(1, false);
  16882. }
  16883. }
  16884. else {
  16885. if (channel !== internalTexture._designatedSlot) {
  16886. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16887. return internalTexture._designatedSlot;
  16888. }
  16889. else {
  16890. // No slot for this texture, let's pick a new one (if we find a free slot)
  16891. if (this._nextFreeTextureSlots.length) {
  16892. return this._nextFreeTextureSlots[0];
  16893. }
  16894. // We need to recycle the oldest bound texture, sorry.
  16895. this._textureCollisions.addCount(1, false);
  16896. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16897. }
  16898. }
  16899. }
  16900. return channel;
  16901. };
  16902. Engine.prototype._linkTrackers = function (previous, next) {
  16903. previous.next = next;
  16904. next.previous = previous;
  16905. };
  16906. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16907. var currentSlot = internalTexture._designatedSlot;
  16908. if (currentSlot === -1) {
  16909. return -1;
  16910. }
  16911. internalTexture._designatedSlot = -1;
  16912. if (this.disableTextureBindingOptimization) {
  16913. return -1;
  16914. }
  16915. // Remove from bound list
  16916. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16917. // Free the slot
  16918. this._boundTexturesCache[currentSlot] = null;
  16919. this._nextFreeTextureSlots.push(currentSlot);
  16920. return currentSlot;
  16921. };
  16922. Engine.prototype._activateCurrentTexture = function () {
  16923. if (this._currentTextureChannel !== this._activeChannel) {
  16924. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16925. this._currentTextureChannel = this._activeChannel;
  16926. }
  16927. };
  16928. /** @hidden */
  16929. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16930. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16931. if (force === void 0) { force = false; }
  16932. var wasPreviouslyBound = false;
  16933. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16934. this._activeChannel = texture._designatedSlot;
  16935. }
  16936. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16937. var isTextureForRendering = texture && texture._initialSlot > -1;
  16938. if (currentTextureBound !== texture || force) {
  16939. if (currentTextureBound) {
  16940. this._removeDesignatedSlot(currentTextureBound);
  16941. }
  16942. this._activateCurrentTexture();
  16943. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16944. this._boundTexturesCache[this._activeChannel] = texture;
  16945. if (texture) {
  16946. if (!this.disableTextureBindingOptimization) {
  16947. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16948. if (slotIndex > -1) {
  16949. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16950. }
  16951. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16952. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16953. }
  16954. texture._designatedSlot = this._activeChannel;
  16955. }
  16956. }
  16957. else if (forTextureDataUpdate) {
  16958. wasPreviouslyBound = true;
  16959. this._activateCurrentTexture();
  16960. }
  16961. if (isTextureForRendering && !forTextureDataUpdate) {
  16962. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16963. }
  16964. return wasPreviouslyBound;
  16965. };
  16966. /** @hidden */
  16967. Engine.prototype._bindTexture = function (channel, texture) {
  16968. if (channel < 0) {
  16969. return;
  16970. }
  16971. if (texture) {
  16972. channel = this._getCorrectTextureChannel(channel, texture);
  16973. }
  16974. this._activeChannel = channel;
  16975. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16976. };
  16977. /**
  16978. * Sets a texture to the webGL context from a postprocess
  16979. * @param channel defines the channel to use
  16980. * @param postProcess defines the source postprocess
  16981. */
  16982. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16983. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16984. };
  16985. /**
  16986. * Binds the output of the passed in post process to the texture channel specified
  16987. * @param channel The channel the texture should be bound to
  16988. * @param postProcess The post process which's output should be bound
  16989. */
  16990. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16991. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16992. };
  16993. /**
  16994. * Unbind all textures from the webGL context
  16995. */
  16996. Engine.prototype.unbindAllTextures = function () {
  16997. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16998. this._activeChannel = channel;
  16999. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17000. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17001. if (this.webGLVersion > 1) {
  17002. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17003. }
  17004. }
  17005. };
  17006. /**
  17007. * Sets a texture to the according uniform.
  17008. * @param channel The texture channel
  17009. * @param uniform The uniform to set
  17010. * @param texture The texture to apply
  17011. */
  17012. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17013. if (channel < 0) {
  17014. return;
  17015. }
  17016. if (uniform) {
  17017. this._boundUniforms[channel] = uniform;
  17018. }
  17019. this._setTexture(channel, texture);
  17020. };
  17021. /**
  17022. * Sets a depth stencil texture from a render target to the according uniform.
  17023. * @param channel The texture channel
  17024. * @param uniform The uniform to set
  17025. * @param texture The render target texture containing the depth stencil texture to apply
  17026. */
  17027. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17028. if (channel < 0) {
  17029. return;
  17030. }
  17031. if (uniform) {
  17032. this._boundUniforms[channel] = uniform;
  17033. }
  17034. if (!texture || !texture.depthStencilTexture) {
  17035. this._setTexture(channel, null);
  17036. }
  17037. else {
  17038. this._setTexture(channel, texture, false, true);
  17039. }
  17040. };
  17041. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17042. var uniform = this._boundUniforms[sourceSlot];
  17043. if (uniform._currentState === destination) {
  17044. return;
  17045. }
  17046. this._gl.uniform1i(uniform, destination);
  17047. uniform._currentState = destination;
  17048. };
  17049. Engine.prototype._getTextureWrapMode = function (mode) {
  17050. switch (mode) {
  17051. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17052. return this._gl.REPEAT;
  17053. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17054. return this._gl.CLAMP_TO_EDGE;
  17055. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17056. return this._gl.MIRRORED_REPEAT;
  17057. }
  17058. return this._gl.REPEAT;
  17059. };
  17060. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17061. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17062. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17063. // Not ready?
  17064. if (!texture) {
  17065. if (this._boundTexturesCache[channel] != null) {
  17066. this._activeChannel = channel;
  17067. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17068. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17069. if (this.webGLVersion > 1) {
  17070. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17071. }
  17072. }
  17073. return false;
  17074. }
  17075. // Video
  17076. if (texture.video) {
  17077. this._activeChannel = channel;
  17078. texture.update();
  17079. }
  17080. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17081. texture.delayLoad();
  17082. return false;
  17083. }
  17084. var internalTexture;
  17085. if (depthStencilTexture) {
  17086. internalTexture = texture.depthStencilTexture;
  17087. }
  17088. else if (texture.isReady()) {
  17089. internalTexture = texture.getInternalTexture();
  17090. }
  17091. else if (texture.isCube) {
  17092. internalTexture = this.emptyCubeTexture;
  17093. }
  17094. else if (texture.is3D) {
  17095. internalTexture = this.emptyTexture3D;
  17096. }
  17097. else {
  17098. internalTexture = this.emptyTexture;
  17099. }
  17100. if (!isPartOfTextureArray) {
  17101. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17102. }
  17103. var needToBind = true;
  17104. if (this._boundTexturesCache[channel] === internalTexture) {
  17105. this._moveBoundTextureOnTop(internalTexture);
  17106. if (!isPartOfTextureArray) {
  17107. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17108. }
  17109. needToBind = false;
  17110. }
  17111. this._activeChannel = channel;
  17112. if (internalTexture && internalTexture.is3D) {
  17113. if (needToBind) {
  17114. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17115. }
  17116. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17117. internalTexture._cachedWrapU = texture.wrapU;
  17118. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17119. }
  17120. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17121. internalTexture._cachedWrapV = texture.wrapV;
  17122. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17123. }
  17124. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17125. internalTexture._cachedWrapR = texture.wrapR;
  17126. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17127. }
  17128. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17129. }
  17130. else if (internalTexture && internalTexture.isCube) {
  17131. if (needToBind) {
  17132. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17133. }
  17134. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17135. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17136. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17137. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17138. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17139. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17140. }
  17141. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17142. }
  17143. else {
  17144. if (needToBind) {
  17145. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17146. }
  17147. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17148. internalTexture._cachedWrapU = texture.wrapU;
  17149. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17150. }
  17151. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17152. internalTexture._cachedWrapV = texture.wrapV;
  17153. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17154. }
  17155. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17156. }
  17157. return true;
  17158. };
  17159. /**
  17160. * Sets an array of texture to the webGL context
  17161. * @param channel defines the channel where the texture array must be set
  17162. * @param uniform defines the associated uniform location
  17163. * @param textures defines the array of textures to bind
  17164. */
  17165. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17166. if (channel < 0 || !uniform) {
  17167. return;
  17168. }
  17169. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17170. this._textureUnits = new Int32Array(textures.length);
  17171. }
  17172. for (var i = 0; i < textures.length; i++) {
  17173. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17174. }
  17175. this._gl.uniform1iv(uniform, this._textureUnits);
  17176. for (var index = 0; index < textures.length; index++) {
  17177. this._setTexture(this._textureUnits[index], textures[index], true);
  17178. }
  17179. };
  17180. /** @hidden */
  17181. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17182. var internalTexture = texture.getInternalTexture();
  17183. if (!internalTexture) {
  17184. return;
  17185. }
  17186. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17187. var value = texture.anisotropicFilteringLevel;
  17188. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17189. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17190. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17191. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17192. }
  17193. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17194. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17195. internalTexture._cachedAnisotropicFilteringLevel = value;
  17196. }
  17197. };
  17198. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17199. this._bindTextureDirectly(target, texture, true, true);
  17200. this._gl.texParameterf(target, parameter, value);
  17201. };
  17202. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17203. if (texture) {
  17204. this._bindTextureDirectly(target, texture, true, true);
  17205. }
  17206. this._gl.texParameteri(target, parameter, value);
  17207. };
  17208. /**
  17209. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17210. * @param x defines the x coordinate of the rectangle where pixels must be read
  17211. * @param y defines the y coordinate of the rectangle where pixels must be read
  17212. * @param width defines the width of the rectangle where pixels must be read
  17213. * @param height defines the height of the rectangle where pixels must be read
  17214. * @returns a Uint8Array containing RGBA colors
  17215. */
  17216. Engine.prototype.readPixels = function (x, y, width, height) {
  17217. var data = new Uint8Array(height * width * 4);
  17218. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17219. return data;
  17220. };
  17221. /**
  17222. * Add an externaly attached data from its key.
  17223. * This method call will fail and return false, if such key already exists.
  17224. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17225. * @param key the unique key that identifies the data
  17226. * @param data the data object to associate to the key for this Engine instance
  17227. * @return true if no such key were already present and the data was added successfully, false otherwise
  17228. */
  17229. Engine.prototype.addExternalData = function (key, data) {
  17230. if (!this._externalData) {
  17231. this._externalData = new BABYLON.StringDictionary();
  17232. }
  17233. return this._externalData.add(key, data);
  17234. };
  17235. /**
  17236. * Get an externaly attached data from its key
  17237. * @param key the unique key that identifies the data
  17238. * @return the associated data, if present (can be null), or undefined if not present
  17239. */
  17240. Engine.prototype.getExternalData = function (key) {
  17241. if (!this._externalData) {
  17242. this._externalData = new BABYLON.StringDictionary();
  17243. }
  17244. return this._externalData.get(key);
  17245. };
  17246. /**
  17247. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17248. * @param key the unique key that identifies the data
  17249. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17250. * @return the associated data, can be null if the factory returned null.
  17251. */
  17252. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17253. if (!this._externalData) {
  17254. this._externalData = new BABYLON.StringDictionary();
  17255. }
  17256. return this._externalData.getOrAddWithFactory(key, factory);
  17257. };
  17258. /**
  17259. * Remove an externaly attached data from the Engine instance
  17260. * @param key the unique key that identifies the data
  17261. * @return true if the data was successfully removed, false if it doesn't exist
  17262. */
  17263. Engine.prototype.removeExternalData = function (key) {
  17264. if (!this._externalData) {
  17265. this._externalData = new BABYLON.StringDictionary();
  17266. }
  17267. return this._externalData.remove(key);
  17268. };
  17269. /**
  17270. * Unbind all vertex attributes from the webGL context
  17271. */
  17272. Engine.prototype.unbindAllAttributes = function () {
  17273. if (this._mustWipeVertexAttributes) {
  17274. this._mustWipeVertexAttributes = false;
  17275. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17276. this._gl.disableVertexAttribArray(i);
  17277. this._vertexAttribArraysEnabled[i] = false;
  17278. this._currentBufferPointers[i].active = false;
  17279. }
  17280. return;
  17281. }
  17282. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17283. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17284. continue;
  17285. }
  17286. this._gl.disableVertexAttribArray(i);
  17287. this._vertexAttribArraysEnabled[i] = false;
  17288. this._currentBufferPointers[i].active = false;
  17289. }
  17290. };
  17291. /**
  17292. * 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
  17293. */
  17294. Engine.prototype.releaseEffects = function () {
  17295. for (var name in this._compiledEffects) {
  17296. this._deleteProgram(this._compiledEffects[name]._program);
  17297. }
  17298. this._compiledEffects = {};
  17299. };
  17300. /**
  17301. * Dispose and release all associated resources
  17302. */
  17303. Engine.prototype.dispose = function () {
  17304. this.hideLoadingUI();
  17305. this.stopRenderLoop();
  17306. // Release postProcesses
  17307. while (this.postProcesses.length) {
  17308. this.postProcesses[0].dispose();
  17309. }
  17310. // Empty texture
  17311. if (this._emptyTexture) {
  17312. this._releaseTexture(this._emptyTexture);
  17313. this._emptyTexture = null;
  17314. }
  17315. if (this._emptyCubeTexture) {
  17316. this._releaseTexture(this._emptyCubeTexture);
  17317. this._emptyCubeTexture = null;
  17318. }
  17319. // Rescale PP
  17320. if (this._rescalePostProcess) {
  17321. this._rescalePostProcess.dispose();
  17322. }
  17323. // Release scenes
  17324. while (this.scenes.length) {
  17325. this.scenes[0].dispose();
  17326. }
  17327. // Release audio engine
  17328. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17329. Engine.audioEngine.dispose();
  17330. }
  17331. // Release effects
  17332. this.releaseEffects();
  17333. // Unbind
  17334. this.unbindAllAttributes();
  17335. this._boundUniforms = [];
  17336. if (this._dummyFramebuffer) {
  17337. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17338. }
  17339. //WebVR
  17340. this.disableVR();
  17341. // Events
  17342. if (BABYLON.Tools.IsWindowObjectExist()) {
  17343. window.removeEventListener("blur", this._onBlur);
  17344. window.removeEventListener("focus", this._onFocus);
  17345. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17346. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17347. if (this._renderingCanvas) {
  17348. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17349. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17350. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17351. if (!this._doNotHandleContextLost) {
  17352. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17353. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17354. }
  17355. }
  17356. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17357. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17358. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17359. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17360. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17361. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17362. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17363. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17364. if (this._onVrDisplayConnect) {
  17365. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17366. if (this._onVrDisplayDisconnect) {
  17367. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17368. }
  17369. if (this._onVrDisplayPresentChange) {
  17370. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17371. }
  17372. this._onVrDisplayConnect = null;
  17373. this._onVrDisplayDisconnect = null;
  17374. }
  17375. }
  17376. // Remove from Instances
  17377. var index = Engine.Instances.indexOf(this);
  17378. if (index >= 0) {
  17379. Engine.Instances.splice(index, 1);
  17380. }
  17381. this._workingCanvas = null;
  17382. this._workingContext = null;
  17383. this._currentBufferPointers = [];
  17384. this._renderingCanvas = null;
  17385. this._currentProgram = null;
  17386. this._bindedRenderFunction = null;
  17387. this.onResizeObservable.clear();
  17388. this.onCanvasBlurObservable.clear();
  17389. this.onCanvasFocusObservable.clear();
  17390. this.onCanvasPointerOutObservable.clear();
  17391. this.onBeginFrameObservable.clear();
  17392. this.onEndFrameObservable.clear();
  17393. BABYLON.Effect.ResetCache();
  17394. // Abort active requests
  17395. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17396. var request = _a[_i];
  17397. request.abort();
  17398. }
  17399. };
  17400. // Loading screen
  17401. /**
  17402. * Display the loading screen
  17403. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17404. */
  17405. Engine.prototype.displayLoadingUI = function () {
  17406. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17407. return;
  17408. }
  17409. var loadingScreen = this.loadingScreen;
  17410. if (loadingScreen) {
  17411. loadingScreen.displayLoadingUI();
  17412. }
  17413. };
  17414. /**
  17415. * Hide the loading screen
  17416. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17417. */
  17418. Engine.prototype.hideLoadingUI = function () {
  17419. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17420. return;
  17421. }
  17422. var loadingScreen = this.loadingScreen;
  17423. if (loadingScreen) {
  17424. loadingScreen.hideLoadingUI();
  17425. }
  17426. };
  17427. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17428. /**
  17429. * Gets the current loading screen object
  17430. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17431. */
  17432. get: function () {
  17433. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17434. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17435. return this._loadingScreen;
  17436. },
  17437. /**
  17438. * Sets the current loading screen object
  17439. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17440. */
  17441. set: function (loadingScreen) {
  17442. this._loadingScreen = loadingScreen;
  17443. },
  17444. enumerable: true,
  17445. configurable: true
  17446. });
  17447. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17448. /**
  17449. * Sets the current loading screen text
  17450. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17451. */
  17452. set: function (text) {
  17453. this.loadingScreen.loadingUIText = text;
  17454. },
  17455. enumerable: true,
  17456. configurable: true
  17457. });
  17458. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17459. /**
  17460. * Sets the current loading screen background color
  17461. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17462. */
  17463. set: function (color) {
  17464. this.loadingScreen.loadingUIBackgroundColor = color;
  17465. },
  17466. enumerable: true,
  17467. configurable: true
  17468. });
  17469. /**
  17470. * Attach a new callback raised when context lost event is fired
  17471. * @param callback defines the callback to call
  17472. */
  17473. Engine.prototype.attachContextLostEvent = function (callback) {
  17474. if (this._renderingCanvas) {
  17475. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17476. }
  17477. };
  17478. /**
  17479. * Attach a new callback raised when context restored event is fired
  17480. * @param callback defines the callback to call
  17481. */
  17482. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17483. if (this._renderingCanvas) {
  17484. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17485. }
  17486. };
  17487. /**
  17488. * Gets the source code of the vertex shader associated with a specific webGL program
  17489. * @param program defines the program to use
  17490. * @returns a string containing the source code of the vertex shader associated with the program
  17491. */
  17492. Engine.prototype.getVertexShaderSource = function (program) {
  17493. var shaders = this._gl.getAttachedShaders(program);
  17494. if (!shaders) {
  17495. return null;
  17496. }
  17497. return this._gl.getShaderSource(shaders[0]);
  17498. };
  17499. /**
  17500. * Gets the source code of the fragment shader associated with a specific webGL program
  17501. * @param program defines the program to use
  17502. * @returns a string containing the source code of the fragment shader associated with the program
  17503. */
  17504. Engine.prototype.getFragmentShaderSource = function (program) {
  17505. var shaders = this._gl.getAttachedShaders(program);
  17506. if (!shaders) {
  17507. return null;
  17508. }
  17509. return this._gl.getShaderSource(shaders[1]);
  17510. };
  17511. /**
  17512. * Get the current error code of the webGL context
  17513. * @returns the error code
  17514. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17515. */
  17516. Engine.prototype.getError = function () {
  17517. return this._gl.getError();
  17518. };
  17519. // FPS
  17520. /**
  17521. * Gets the current framerate
  17522. * @returns a number representing the framerate
  17523. */
  17524. Engine.prototype.getFps = function () {
  17525. return this._fps;
  17526. };
  17527. /**
  17528. * Gets the time spent between current and previous frame
  17529. * @returns a number representing the delta time in ms
  17530. */
  17531. Engine.prototype.getDeltaTime = function () {
  17532. return this._deltaTime;
  17533. };
  17534. Engine.prototype._measureFps = function () {
  17535. this._performanceMonitor.sampleFrame();
  17536. this._fps = this._performanceMonitor.averageFPS;
  17537. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17538. };
  17539. /** @hidden */
  17540. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17541. if (faceIndex === void 0) { faceIndex = -1; }
  17542. if (level === void 0) { level = 0; }
  17543. if (buffer === void 0) { buffer = null; }
  17544. var gl = this._gl;
  17545. if (!this._dummyFramebuffer) {
  17546. var dummy = gl.createFramebuffer();
  17547. if (!dummy) {
  17548. throw new Error("Unable to create dummy framebuffer");
  17549. }
  17550. this._dummyFramebuffer = dummy;
  17551. }
  17552. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17553. if (faceIndex > -1) {
  17554. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17555. }
  17556. else {
  17557. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17558. }
  17559. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17560. switch (readType) {
  17561. case gl.UNSIGNED_BYTE:
  17562. if (!buffer) {
  17563. buffer = new Uint8Array(4 * width * height);
  17564. }
  17565. readType = gl.UNSIGNED_BYTE;
  17566. break;
  17567. default:
  17568. if (!buffer) {
  17569. buffer = new Float32Array(4 * width * height);
  17570. }
  17571. readType = gl.FLOAT;
  17572. break;
  17573. }
  17574. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17575. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17576. return buffer;
  17577. };
  17578. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17579. if (this._webGLVersion > 1) {
  17580. return this._caps.colorBufferFloat;
  17581. }
  17582. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17583. };
  17584. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17585. if (this._webGLVersion > 1) {
  17586. return this._caps.colorBufferFloat;
  17587. }
  17588. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17589. };
  17590. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17591. Engine.prototype._canRenderToFramebuffer = function (type) {
  17592. var gl = this._gl;
  17593. //clear existing errors
  17594. while (gl.getError() !== gl.NO_ERROR) { }
  17595. var successful = true;
  17596. var texture = gl.createTexture();
  17597. gl.bindTexture(gl.TEXTURE_2D, texture);
  17598. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17599. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17600. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17601. var fb = gl.createFramebuffer();
  17602. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17604. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17605. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17606. successful = successful && (gl.getError() === gl.NO_ERROR);
  17607. //try render by clearing frame buffer's color buffer
  17608. if (successful) {
  17609. gl.clear(gl.COLOR_BUFFER_BIT);
  17610. successful = successful && (gl.getError() === gl.NO_ERROR);
  17611. }
  17612. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17613. if (successful) {
  17614. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17615. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17616. var readFormat = gl.RGBA;
  17617. var readType = gl.UNSIGNED_BYTE;
  17618. var buffer = new Uint8Array(4);
  17619. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17620. successful = successful && (gl.getError() === gl.NO_ERROR);
  17621. }
  17622. //clean up
  17623. gl.deleteTexture(texture);
  17624. gl.deleteFramebuffer(fb);
  17625. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17626. //clear accumulated errors
  17627. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17628. return successful;
  17629. };
  17630. /** @hidden */
  17631. Engine.prototype._getWebGLTextureType = function (type) {
  17632. if (this._webGLVersion === 1) {
  17633. switch (type) {
  17634. case Engine.TEXTURETYPE_FLOAT:
  17635. return this._gl.FLOAT;
  17636. case Engine.TEXTURETYPE_HALF_FLOAT:
  17637. return this._gl.HALF_FLOAT_OES;
  17638. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17639. return this._gl.UNSIGNED_BYTE;
  17640. }
  17641. return this._gl.UNSIGNED_BYTE;
  17642. }
  17643. switch (type) {
  17644. case Engine.TEXTURETYPE_BYTE:
  17645. return this._gl.BYTE;
  17646. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17647. return this._gl.UNSIGNED_BYTE;
  17648. case Engine.TEXTURETYPE_SHORT:
  17649. return this._gl.SHORT;
  17650. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17651. return this._gl.UNSIGNED_SHORT;
  17652. case Engine.TEXTURETYPE_INT:
  17653. return this._gl.INT;
  17654. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17655. return this._gl.UNSIGNED_INT;
  17656. case Engine.TEXTURETYPE_FLOAT:
  17657. return this._gl.FLOAT;
  17658. case Engine.TEXTURETYPE_HALF_FLOAT:
  17659. return this._gl.HALF_FLOAT;
  17660. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17661. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17662. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17663. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17664. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17665. return this._gl.UNSIGNED_SHORT_5_6_5;
  17666. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17667. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17668. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17669. return this._gl.UNSIGNED_INT_24_8;
  17670. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17671. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17672. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17673. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17674. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17675. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17676. }
  17677. return this._gl.UNSIGNED_BYTE;
  17678. };
  17679. ;
  17680. Engine.prototype._getInternalFormat = function (format) {
  17681. var internalFormat = this._gl.RGBA;
  17682. switch (format) {
  17683. case Engine.TEXTUREFORMAT_ALPHA:
  17684. internalFormat = this._gl.ALPHA;
  17685. break;
  17686. case Engine.TEXTUREFORMAT_LUMINANCE:
  17687. internalFormat = this._gl.LUMINANCE;
  17688. break;
  17689. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17690. internalFormat = this._gl.LUMINANCE_ALPHA;
  17691. break;
  17692. case Engine.TEXTUREFORMAT_RED:
  17693. internalFormat = this._gl.RED;
  17694. break;
  17695. case Engine.TEXTUREFORMAT_RG:
  17696. internalFormat = this._gl.RG;
  17697. break;
  17698. case Engine.TEXTUREFORMAT_RGB:
  17699. internalFormat = this._gl.RGB;
  17700. break;
  17701. case Engine.TEXTUREFORMAT_RGBA:
  17702. internalFormat = this._gl.RGBA;
  17703. break;
  17704. }
  17705. if (this._webGLVersion > 1) {
  17706. switch (format) {
  17707. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17708. internalFormat = this._gl.RED_INTEGER;
  17709. break;
  17710. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17711. internalFormat = this._gl.RG_INTEGER;
  17712. break;
  17713. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17714. internalFormat = this._gl.RGB_INTEGER;
  17715. break;
  17716. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17717. internalFormat = this._gl.RGBA_INTEGER;
  17718. break;
  17719. }
  17720. }
  17721. return internalFormat;
  17722. };
  17723. /** @hidden */
  17724. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17725. if (this._webGLVersion === 1) {
  17726. if (format !== undefined) {
  17727. switch (format) {
  17728. case Engine.TEXTUREFORMAT_ALPHA:
  17729. return this._gl.ALPHA;
  17730. case Engine.TEXTUREFORMAT_LUMINANCE:
  17731. return this._gl.LUMINANCE;
  17732. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17733. return this._gl.LUMINANCE_ALPHA;
  17734. }
  17735. }
  17736. return this._gl.RGBA;
  17737. }
  17738. switch (type) {
  17739. case Engine.TEXTURETYPE_BYTE:
  17740. switch (format) {
  17741. case Engine.TEXTUREFORMAT_RED:
  17742. return this._gl.R8_SNORM;
  17743. case Engine.TEXTUREFORMAT_RG:
  17744. return this._gl.RG8_SNORM;
  17745. case Engine.TEXTUREFORMAT_RGB:
  17746. return this._gl.RGB8_SNORM;
  17747. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17748. return this._gl.R8I;
  17749. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17750. return this._gl.RG8I;
  17751. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17752. return this._gl.RGB8I;
  17753. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17754. return this._gl.RGBA8I;
  17755. default:
  17756. return this._gl.RGBA8_SNORM;
  17757. }
  17758. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17759. switch (format) {
  17760. case Engine.TEXTUREFORMAT_RED:
  17761. return this._gl.R8;
  17762. case Engine.TEXTUREFORMAT_RG:
  17763. return this._gl.RG8;
  17764. case Engine.TEXTUREFORMAT_RGB:
  17765. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17766. case Engine.TEXTUREFORMAT_RGBA:
  17767. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17768. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17769. return this._gl.R8UI;
  17770. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17771. return this._gl.RG8UI;
  17772. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17773. return this._gl.RGB8UI;
  17774. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17775. return this._gl.RGBA8UI;
  17776. default:
  17777. return this._gl.RGBA8;
  17778. }
  17779. case Engine.TEXTURETYPE_SHORT:
  17780. switch (format) {
  17781. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17782. return this._gl.R16I;
  17783. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17784. return this._gl.RG16I;
  17785. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17786. return this._gl.RGB16I;
  17787. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17788. return this._gl.RGBA16I;
  17789. default:
  17790. return this._gl.RGBA16I;
  17791. }
  17792. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17793. switch (format) {
  17794. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17795. return this._gl.R16UI;
  17796. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17797. return this._gl.RG16UI;
  17798. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17799. return this._gl.RGB16UI;
  17800. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17801. return this._gl.RGBA16UI;
  17802. default:
  17803. return this._gl.RGBA16UI;
  17804. }
  17805. case Engine.TEXTURETYPE_INT:
  17806. switch (format) {
  17807. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17808. return this._gl.R32I;
  17809. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17810. return this._gl.RG32I;
  17811. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17812. return this._gl.RGB32I;
  17813. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17814. return this._gl.RGBA32I;
  17815. default:
  17816. return this._gl.RGBA32I;
  17817. }
  17818. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17819. switch (format) {
  17820. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17821. return this._gl.R32UI;
  17822. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17823. return this._gl.RG32UI;
  17824. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17825. return this._gl.RGB32UI;
  17826. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17827. return this._gl.RGBA32UI;
  17828. default:
  17829. return this._gl.RGBA32UI;
  17830. }
  17831. case Engine.TEXTURETYPE_FLOAT:
  17832. switch (format) {
  17833. case Engine.TEXTUREFORMAT_RED:
  17834. return this._gl.R32F; // By default. Other possibility is R16F.
  17835. case Engine.TEXTUREFORMAT_RG:
  17836. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17837. case Engine.TEXTUREFORMAT_RGB:
  17838. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17839. case Engine.TEXTUREFORMAT_RGBA:
  17840. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17841. default:
  17842. return this._gl.RGBA32F;
  17843. }
  17844. case Engine.TEXTURETYPE_HALF_FLOAT:
  17845. switch (format) {
  17846. case Engine.TEXTUREFORMAT_RED:
  17847. return this._gl.R16F;
  17848. case Engine.TEXTUREFORMAT_RG:
  17849. return this._gl.RG16F;
  17850. case Engine.TEXTUREFORMAT_RGB:
  17851. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17852. case Engine.TEXTUREFORMAT_RGBA:
  17853. return this._gl.RGBA16F;
  17854. default:
  17855. return this._gl.RGBA16F;
  17856. }
  17857. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17858. return this._gl.RGB565;
  17859. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17860. return this._gl.R11F_G11F_B10F;
  17861. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17862. return this._gl.RGB9_E5;
  17863. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17864. return this._gl.RGBA4;
  17865. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17866. return this._gl.RGB5_A1;
  17867. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17868. switch (format) {
  17869. case Engine.TEXTUREFORMAT_RGBA:
  17870. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17871. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17872. return this._gl.RGB10_A2UI;
  17873. default:
  17874. return this._gl.RGB10_A2;
  17875. }
  17876. }
  17877. return this._gl.RGBA8;
  17878. };
  17879. ;
  17880. /** @hidden */
  17881. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17882. if (type === Engine.TEXTURETYPE_FLOAT) {
  17883. return this._gl.RGBA32F;
  17884. }
  17885. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17886. return this._gl.RGBA16F;
  17887. }
  17888. return this._gl.RGBA8;
  17889. };
  17890. ;
  17891. /** @hidden */
  17892. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17893. var _this = this;
  17894. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17895. this._activeRequests.push(request);
  17896. request.onCompleteObservable.add(function (request) {
  17897. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17898. });
  17899. return request;
  17900. };
  17901. /** @hidden */
  17902. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17903. var _this = this;
  17904. return new Promise(function (resolve, reject) {
  17905. _this._loadFile(url, function (data) {
  17906. resolve(data);
  17907. }, undefined, database, useArrayBuffer, function (request, exception) {
  17908. reject(exception);
  17909. });
  17910. });
  17911. };
  17912. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17913. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17914. var onload = function (data) {
  17915. loadedFiles[index] = data;
  17916. loadedFiles._internalCount++;
  17917. if (loadedFiles._internalCount === 6) {
  17918. onfinish(loadedFiles);
  17919. }
  17920. };
  17921. var onerror = function (request, exception) {
  17922. if (onErrorCallBack && request) {
  17923. onErrorCallBack(request.status + " " + request.statusText, exception);
  17924. }
  17925. };
  17926. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17927. };
  17928. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17929. if (onError === void 0) { onError = null; }
  17930. var loadedFiles = [];
  17931. loadedFiles._internalCount = 0;
  17932. for (var index = 0; index < 6; index++) {
  17933. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17934. }
  17935. };
  17936. // Statics
  17937. /**
  17938. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17939. * @returns true if the engine can be created
  17940. * @ignorenaming
  17941. */
  17942. Engine.isSupported = function () {
  17943. try {
  17944. var tempcanvas = document.createElement("canvas");
  17945. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17946. return gl != null && !!window.WebGLRenderingContext;
  17947. }
  17948. catch (e) {
  17949. return false;
  17950. }
  17951. };
  17952. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17953. Engine.ExceptionList = [
  17954. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17955. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17956. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17957. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17958. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17959. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17960. ];
  17961. /** Gets the list of created engines */
  17962. Engine.Instances = new Array();
  17963. /**
  17964. * Hidden
  17965. */
  17966. Engine._TextureLoaders = [];
  17967. // Const statics
  17968. /** Defines that alpha blending is disabled */
  17969. Engine.ALPHA_DISABLE = 0;
  17970. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17971. Engine.ALPHA_ADD = 1;
  17972. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17973. Engine.ALPHA_COMBINE = 2;
  17974. /** Defines that alpha blending to DEST - SRC * DEST */
  17975. Engine.ALPHA_SUBTRACT = 3;
  17976. /** Defines that alpha blending to SRC * DEST */
  17977. Engine.ALPHA_MULTIPLY = 4;
  17978. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17979. Engine.ALPHA_MAXIMIZED = 5;
  17980. /** Defines that alpha blending to SRC + DEST */
  17981. Engine.ALPHA_ONEONE = 6;
  17982. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17983. Engine.ALPHA_PREMULTIPLIED = 7;
  17984. /**
  17985. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17986. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17987. */
  17988. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17989. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17990. Engine.ALPHA_INTERPOLATE = 9;
  17991. /**
  17992. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17993. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17994. */
  17995. Engine.ALPHA_SCREENMODE = 10;
  17996. /** Defines that the ressource is not delayed*/
  17997. Engine.DELAYLOADSTATE_NONE = 0;
  17998. /** Defines that the ressource was successfully delay loaded */
  17999. Engine.DELAYLOADSTATE_LOADED = 1;
  18000. /** Defines that the ressource is currently delay loading */
  18001. Engine.DELAYLOADSTATE_LOADING = 2;
  18002. /** Defines that the ressource is delayed and has not started loading */
  18003. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18004. // Depht or Stencil test Constants.
  18005. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18006. Engine.NEVER = 0x0200;
  18007. /** 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 */
  18008. Engine.ALWAYS = 0x0207;
  18009. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18010. Engine.LESS = 0x0201;
  18011. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18012. Engine.EQUAL = 0x0202;
  18013. /** 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 */
  18014. Engine.LEQUAL = 0x0203;
  18015. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18016. Engine.GREATER = 0x0204;
  18017. /** 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 */
  18018. Engine.GEQUAL = 0x0206;
  18019. /** 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 */
  18020. Engine.NOTEQUAL = 0x0205;
  18021. // Stencil Actions Constants.
  18022. /** Passed to stencilOperation to specify that stencil value must be kept */
  18023. Engine.KEEP = 0x1E00;
  18024. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18025. Engine.REPLACE = 0x1E01;
  18026. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18027. Engine.INCR = 0x1E02;
  18028. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18029. Engine.DECR = 0x1E03;
  18030. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18031. Engine.INVERT = 0x150A;
  18032. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18033. Engine.INCR_WRAP = 0x8507;
  18034. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18035. Engine.DECR_WRAP = 0x8508;
  18036. /** Texture is not repeating outside of 0..1 UVs */
  18037. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18038. /** Texture is repeating outside of 0..1 UVs */
  18039. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18040. /** Texture is repeating and mirrored */
  18041. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18042. /** ALPHA */
  18043. Engine.TEXTUREFORMAT_ALPHA = 0;
  18044. /** LUMINANCE */
  18045. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18046. /** LUMINANCE_ALPHA */
  18047. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18048. /** RGB */
  18049. Engine.TEXTUREFORMAT_RGB = 4;
  18050. /** RGBA */
  18051. Engine.TEXTUREFORMAT_RGBA = 5;
  18052. /** RED */
  18053. Engine.TEXTUREFORMAT_RED = 6;
  18054. /** RED (2nd reference) */
  18055. Engine.TEXTUREFORMAT_R = 6;
  18056. /** RG */
  18057. Engine.TEXTUREFORMAT_RG = 7;
  18058. /** RED_INTEGER */
  18059. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18060. /** RED_INTEGER (2nd reference) */
  18061. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18062. /** RG_INTEGER */
  18063. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18064. /** RGB_INTEGER */
  18065. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18066. /** RGBA_INTEGER */
  18067. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18068. /** UNSIGNED_BYTE */
  18069. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18070. /** UNSIGNED_BYTE (2nd reference) */
  18071. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18072. /** FLOAT */
  18073. Engine.TEXTURETYPE_FLOAT = 1;
  18074. /** HALF_FLOAT */
  18075. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18076. /** BYTE */
  18077. Engine.TEXTURETYPE_BYTE = 3;
  18078. /** SHORT */
  18079. Engine.TEXTURETYPE_SHORT = 4;
  18080. /** UNSIGNED_SHORT */
  18081. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18082. /** INT */
  18083. Engine.TEXTURETYPE_INT = 6;
  18084. /** UNSIGNED_INT */
  18085. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18086. /** UNSIGNED_SHORT_4_4_4_4 */
  18087. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18088. /** UNSIGNED_SHORT_5_5_5_1 */
  18089. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18090. /** UNSIGNED_SHORT_5_6_5 */
  18091. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18092. /** UNSIGNED_INT_2_10_10_10_REV */
  18093. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18094. /** UNSIGNED_INT_24_8 */
  18095. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18096. /** UNSIGNED_INT_10F_11F_11F_REV */
  18097. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18098. /** UNSIGNED_INT_5_9_9_9_REV */
  18099. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18100. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18101. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18102. /** nearest is mag = nearest and min = nearest and mip = linear */
  18103. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18104. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18105. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18106. /** Trilinear is mag = linear and min = linear and mip = linear */
  18107. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18108. /** nearest is mag = nearest and min = nearest and mip = linear */
  18109. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18110. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18111. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18112. /** Trilinear is mag = linear and min = linear and mip = linear */
  18113. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18114. /** mag = nearest and min = nearest and mip = nearest */
  18115. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18116. /** mag = nearest and min = linear and mip = nearest */
  18117. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18118. /** mag = nearest and min = linear and mip = linear */
  18119. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18120. /** mag = nearest and min = linear and mip = none */
  18121. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18122. /** mag = nearest and min = nearest and mip = none */
  18123. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18124. /** mag = linear and min = nearest and mip = nearest */
  18125. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18126. /** mag = linear and min = nearest and mip = linear */
  18127. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18128. /** mag = linear and min = linear and mip = none */
  18129. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18130. /** mag = linear and min = nearest and mip = none */
  18131. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18132. /** Explicit coordinates mode */
  18133. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18134. /** Spherical coordinates mode */
  18135. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18136. /** Planar coordinates mode */
  18137. Engine.TEXTURE_PLANAR_MODE = 2;
  18138. /** Cubic coordinates mode */
  18139. Engine.TEXTURE_CUBIC_MODE = 3;
  18140. /** Projection coordinates mode */
  18141. Engine.TEXTURE_PROJECTION_MODE = 4;
  18142. /** Skybox coordinates mode */
  18143. Engine.TEXTURE_SKYBOX_MODE = 5;
  18144. /** Inverse Cubic coordinates mode */
  18145. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18146. /** Equirectangular coordinates mode */
  18147. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18148. /** Equirectangular Fixed coordinates mode */
  18149. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18150. /** Equirectangular Fixed Mirrored coordinates mode */
  18151. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18152. // Texture rescaling mode
  18153. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18154. Engine.SCALEMODE_FLOOR = 1;
  18155. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18156. Engine.SCALEMODE_NEAREST = 2;
  18157. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18158. Engine.SCALEMODE_CEILING = 3;
  18159. // Updatable statics so stick with vars here
  18160. /**
  18161. * Gets or sets the epsilon value used by collision engine
  18162. */
  18163. Engine.CollisionsEpsilon = 0.001;
  18164. /**
  18165. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18166. */
  18167. Engine.CodeRepository = "src/";
  18168. /**
  18169. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18170. */
  18171. Engine.ShadersRepository = "src/Shaders/";
  18172. return Engine;
  18173. }());
  18174. BABYLON.Engine = Engine;
  18175. })(BABYLON || (BABYLON = {}));
  18176. //# sourceMappingURL=babylon.engine.js.map
  18177. var BABYLON;
  18178. (function (BABYLON) {
  18179. /**
  18180. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18181. */
  18182. var Node = /** @class */ (function () {
  18183. /**
  18184. * Creates a new Node
  18185. * @param {string} name - the name and id to be given to this node
  18186. * @param {BABYLON.Scene} the scene this node will be added to
  18187. */
  18188. function Node(name, scene) {
  18189. if (scene === void 0) { scene = null; }
  18190. /**
  18191. * Gets or sets a string used to store user defined state for the node
  18192. */
  18193. this.state = "";
  18194. /**
  18195. * Gets or sets an object used to store user defined information for the node
  18196. */
  18197. this.metadata = null;
  18198. /**
  18199. * Gets or sets a boolean used to define if the node must be serialized
  18200. */
  18201. this.doNotSerialize = false;
  18202. /** @hidden */
  18203. this._isDisposed = false;
  18204. /**
  18205. * Gets a list of Animations associated with the node
  18206. */
  18207. this.animations = new Array();
  18208. this._ranges = {};
  18209. this._isEnabled = true;
  18210. this._isParentEnabled = true;
  18211. this._isReady = true;
  18212. /** @hidden */
  18213. this._currentRenderId = -1;
  18214. this._parentRenderId = -1;
  18215. this._childRenderId = -1;
  18216. /** @hidden */
  18217. this._worldMatrix = BABYLON.Matrix.Identity();
  18218. /** @hidden */
  18219. this._worldMatrixDeterminant = 0;
  18220. this._animationPropertiesOverride = null;
  18221. /**
  18222. * An event triggered when the mesh is disposed
  18223. */
  18224. this.onDisposeObservable = new BABYLON.Observable();
  18225. // Behaviors
  18226. this._behaviors = new Array();
  18227. this.name = name;
  18228. this.id = name;
  18229. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18230. this.uniqueId = this._scene.getUniqueId();
  18231. this._initCache();
  18232. this._scene.rootNodes.push(this);
  18233. }
  18234. /**
  18235. * Add a new node constructor
  18236. * @param type defines the type name of the node to construct
  18237. * @param constructorFunc defines the constructor function
  18238. */
  18239. Node.AddNodeConstructor = function (type, constructorFunc) {
  18240. this._NodeConstructors[type] = constructorFunc;
  18241. };
  18242. /**
  18243. * Returns a node constructor based on type name
  18244. * @param type defines the type name
  18245. * @param name defines the new node name
  18246. * @param scene defines the hosting scene
  18247. * @param options defines optional options to transmit to constructors
  18248. * @returns the new constructor or null
  18249. */
  18250. Node.Construct = function (type, name, scene, options) {
  18251. var constructorFunc = this._NodeConstructors[type];
  18252. if (!constructorFunc) {
  18253. return null;
  18254. }
  18255. return constructorFunc(name, scene, options);
  18256. };
  18257. /**
  18258. * Gets a boolean indicating if the node has been disposed
  18259. * @returns true if the node was disposed
  18260. */
  18261. Node.prototype.isDisposed = function () {
  18262. return this._isDisposed;
  18263. };
  18264. Object.defineProperty(Node.prototype, "parent", {
  18265. get: function () {
  18266. return this._parentNode;
  18267. },
  18268. /**
  18269. * Gets or sets the parent of the node
  18270. */
  18271. set: function (parent) {
  18272. if (this._parentNode === parent) {
  18273. return;
  18274. }
  18275. var previousParentNode = this._parentNode;
  18276. // Remove self from list of children of parent
  18277. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18278. var index = this._parentNode._children.indexOf(this);
  18279. if (index !== -1) {
  18280. this._parentNode._children.splice(index, 1);
  18281. }
  18282. if (!parent) {
  18283. // Need to add this node to the rootNodes
  18284. this._scene.rootNodes.push(this);
  18285. }
  18286. }
  18287. // Store new parent
  18288. this._parentNode = parent;
  18289. // Add as child to new parent
  18290. if (this._parentNode) {
  18291. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18292. this._parentNode._children = new Array();
  18293. }
  18294. this._parentNode._children.push(this);
  18295. if (!previousParentNode) {
  18296. // Need to remove from rootNodes
  18297. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18298. if (rootNodeIndex > -1) {
  18299. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18300. }
  18301. }
  18302. }
  18303. // Enabled state
  18304. this._syncParentEnabledState();
  18305. },
  18306. enumerable: true,
  18307. configurable: true
  18308. });
  18309. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18310. /**
  18311. * Gets or sets the animation properties override
  18312. */
  18313. get: function () {
  18314. if (!this._animationPropertiesOverride) {
  18315. return this._scene.animationPropertiesOverride;
  18316. }
  18317. return this._animationPropertiesOverride;
  18318. },
  18319. set: function (value) {
  18320. this._animationPropertiesOverride = value;
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. /**
  18326. * Gets a string idenfifying the name of the class
  18327. * @returns "Node" string
  18328. */
  18329. Node.prototype.getClassName = function () {
  18330. return "Node";
  18331. };
  18332. Object.defineProperty(Node.prototype, "onDispose", {
  18333. /**
  18334. * Sets a callback that will be raised when the node will be disposed
  18335. */
  18336. set: function (callback) {
  18337. if (this._onDisposeObserver) {
  18338. this.onDisposeObservable.remove(this._onDisposeObserver);
  18339. }
  18340. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18341. },
  18342. enumerable: true,
  18343. configurable: true
  18344. });
  18345. /**
  18346. * Gets the scene of the node
  18347. * @returns a {BABYLON.Scene}
  18348. */
  18349. Node.prototype.getScene = function () {
  18350. return this._scene;
  18351. };
  18352. /**
  18353. * Gets the engine of the node
  18354. * @returns a {BABYLON.Engine}
  18355. */
  18356. Node.prototype.getEngine = function () {
  18357. return this._scene.getEngine();
  18358. };
  18359. /**
  18360. * Attach a behavior to the node
  18361. * @see http://doc.babylonjs.com/features/behaviour
  18362. * @param behavior defines the behavior to attach
  18363. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18364. * @returns the current Node
  18365. */
  18366. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18367. var _this = this;
  18368. if (attachImmediately === void 0) { attachImmediately = false; }
  18369. var index = this._behaviors.indexOf(behavior);
  18370. if (index !== -1) {
  18371. return this;
  18372. }
  18373. behavior.init();
  18374. if (this._scene.isLoading && !attachImmediately) {
  18375. // We defer the attach when the scene will be loaded
  18376. this._scene.onDataLoadedObservable.addOnce(function () {
  18377. behavior.attach(_this);
  18378. });
  18379. }
  18380. else {
  18381. behavior.attach(this);
  18382. }
  18383. this._behaviors.push(behavior);
  18384. return this;
  18385. };
  18386. /**
  18387. * Remove an attached behavior
  18388. * @see http://doc.babylonjs.com/features/behaviour
  18389. * @param behavior defines the behavior to attach
  18390. * @returns the current Node
  18391. */
  18392. Node.prototype.removeBehavior = function (behavior) {
  18393. var index = this._behaviors.indexOf(behavior);
  18394. if (index === -1) {
  18395. return this;
  18396. }
  18397. this._behaviors[index].detach();
  18398. this._behaviors.splice(index, 1);
  18399. return this;
  18400. };
  18401. Object.defineProperty(Node.prototype, "behaviors", {
  18402. /**
  18403. * Gets the list of attached behaviors
  18404. * @see http://doc.babylonjs.com/features/behaviour
  18405. */
  18406. get: function () {
  18407. return this._behaviors;
  18408. },
  18409. enumerable: true,
  18410. configurable: true
  18411. });
  18412. /**
  18413. * Gets an attached behavior by name
  18414. * @param name defines the name of the behavior to look for
  18415. * @see http://doc.babylonjs.com/features/behaviour
  18416. * @returns null if behavior was not found else the requested behavior
  18417. */
  18418. Node.prototype.getBehaviorByName = function (name) {
  18419. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18420. var behavior = _a[_i];
  18421. if (behavior.name === name) {
  18422. return behavior;
  18423. }
  18424. }
  18425. return null;
  18426. };
  18427. /**
  18428. * Returns the latest update of the World matrix
  18429. * @returns a Matrix
  18430. */
  18431. Node.prototype.getWorldMatrix = function () {
  18432. if (this._currentRenderId !== this._scene.getRenderId()) {
  18433. this.computeWorldMatrix();
  18434. }
  18435. return this._worldMatrix;
  18436. };
  18437. /** @hidden */
  18438. Node.prototype._getWorldMatrixDeterminant = function () {
  18439. return this._worldMatrixDeterminant;
  18440. };
  18441. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18442. /**
  18443. * Returns directly the latest state of the mesh World matrix.
  18444. * A Matrix is returned.
  18445. */
  18446. get: function () {
  18447. return this._worldMatrix;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. // override it in derived class if you add new variables to the cache
  18453. // and call the parent class method
  18454. /** @hidden */
  18455. Node.prototype._initCache = function () {
  18456. this._cache = {};
  18457. this._cache.parent = undefined;
  18458. };
  18459. /** @hidden */
  18460. Node.prototype.updateCache = function (force) {
  18461. if (!force && this.isSynchronized())
  18462. return;
  18463. this._cache.parent = this.parent;
  18464. this._updateCache();
  18465. };
  18466. // override it in derived class if you add new variables to the cache
  18467. // and call the parent class method if !ignoreParentClass
  18468. /** @hidden */
  18469. Node.prototype._updateCache = function (ignoreParentClass) {
  18470. };
  18471. // override it in derived class if you add new variables to the cache
  18472. /** @hidden */
  18473. Node.prototype._isSynchronized = function () {
  18474. return true;
  18475. };
  18476. /** @hidden */
  18477. Node.prototype._markSyncedWithParent = function () {
  18478. if (this._parentNode) {
  18479. this._parentRenderId = this._parentNode._childRenderId;
  18480. }
  18481. };
  18482. /** @hidden */
  18483. Node.prototype.isSynchronizedWithParent = function () {
  18484. if (!this._parentNode) {
  18485. return true;
  18486. }
  18487. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18488. return false;
  18489. }
  18490. return this._parentNode.isSynchronized();
  18491. };
  18492. /** @hidden */
  18493. Node.prototype.isSynchronized = function () {
  18494. if (this._cache.parent != this._parentNode) {
  18495. this._cache.parent = this._parentNode;
  18496. return false;
  18497. }
  18498. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18499. return false;
  18500. }
  18501. return this._isSynchronized();
  18502. };
  18503. /**
  18504. * Is this node ready to be used/rendered
  18505. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18506. * @return true if the node is ready
  18507. */
  18508. Node.prototype.isReady = function (completeCheck) {
  18509. if (completeCheck === void 0) { completeCheck = false; }
  18510. return this._isReady;
  18511. };
  18512. /**
  18513. * Is this node enabled?
  18514. * 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
  18515. * @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
  18516. * @return whether this node (and its parent) is enabled
  18517. */
  18518. Node.prototype.isEnabled = function (checkAncestors) {
  18519. if (checkAncestors === void 0) { checkAncestors = true; }
  18520. if (checkAncestors === false) {
  18521. return this._isEnabled;
  18522. }
  18523. if (!this._isEnabled) {
  18524. return false;
  18525. }
  18526. return this._isParentEnabled;
  18527. };
  18528. /** @hidden */
  18529. Node.prototype._syncParentEnabledState = function () {
  18530. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18531. if (this._children) {
  18532. this._children.forEach(function (c) {
  18533. c._syncParentEnabledState(); // Force children to update accordingly
  18534. });
  18535. }
  18536. };
  18537. /**
  18538. * Set the enabled state of this node
  18539. * @param value defines the new enabled state
  18540. */
  18541. Node.prototype.setEnabled = function (value) {
  18542. this._isEnabled = value;
  18543. this._syncParentEnabledState();
  18544. };
  18545. /**
  18546. * Is this node a descendant of the given node?
  18547. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18548. * @param ancestor defines the parent node to inspect
  18549. * @returns a boolean indicating if this node is a descendant of the given node
  18550. */
  18551. Node.prototype.isDescendantOf = function (ancestor) {
  18552. if (this.parent) {
  18553. if (this.parent === ancestor) {
  18554. return true;
  18555. }
  18556. return this.parent.isDescendantOf(ancestor);
  18557. }
  18558. return false;
  18559. };
  18560. /** @hidden */
  18561. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18562. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18563. if (!this._children) {
  18564. return;
  18565. }
  18566. for (var index = 0; index < this._children.length; index++) {
  18567. var item = this._children[index];
  18568. if (!predicate || predicate(item)) {
  18569. results.push(item);
  18570. }
  18571. if (!directDescendantsOnly) {
  18572. item._getDescendants(results, false, predicate);
  18573. }
  18574. }
  18575. };
  18576. /**
  18577. * Will return all nodes that have this node as ascendant
  18578. * @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
  18579. * @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
  18580. * @return all children nodes of all types
  18581. */
  18582. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18583. var results = new Array();
  18584. this._getDescendants(results, directDescendantsOnly, predicate);
  18585. return results;
  18586. };
  18587. /**
  18588. * Get all child-meshes of this node
  18589. * @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
  18590. * @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
  18591. * @returns an array of {BABYLON.AbstractMesh}
  18592. */
  18593. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18594. var results = [];
  18595. this._getDescendants(results, directDescendantsOnly, function (node) {
  18596. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18597. });
  18598. return results;
  18599. };
  18600. /**
  18601. * Get all child-transformNodes of this node
  18602. * @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
  18603. * @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
  18604. * @returns an array of {BABYLON.TransformNode}
  18605. */
  18606. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18607. var results = [];
  18608. this._getDescendants(results, directDescendantsOnly, function (node) {
  18609. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18610. });
  18611. return results;
  18612. };
  18613. /**
  18614. * Get all direct children of this node
  18615. * @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
  18616. * @returns an array of {BABYLON.Node}
  18617. */
  18618. Node.prototype.getChildren = function (predicate) {
  18619. return this.getDescendants(true, predicate);
  18620. };
  18621. /** @hidden */
  18622. Node.prototype._setReady = function (state) {
  18623. if (state === this._isReady) {
  18624. return;
  18625. }
  18626. if (!state) {
  18627. this._isReady = false;
  18628. return;
  18629. }
  18630. if (this.onReady) {
  18631. this.onReady(this);
  18632. }
  18633. this._isReady = true;
  18634. };
  18635. /**
  18636. * Get an animation by name
  18637. * @param name defines the name of the animation to look for
  18638. * @returns null if not found else the requested animation
  18639. */
  18640. Node.prototype.getAnimationByName = function (name) {
  18641. for (var i = 0; i < this.animations.length; i++) {
  18642. var animation = this.animations[i];
  18643. if (animation.name === name) {
  18644. return animation;
  18645. }
  18646. }
  18647. return null;
  18648. };
  18649. /**
  18650. * Creates an animation range for this node
  18651. * @param name defines the name of the range
  18652. * @param from defines the starting key
  18653. * @param to defines the end key
  18654. */
  18655. Node.prototype.createAnimationRange = function (name, from, to) {
  18656. // check name not already in use
  18657. if (!this._ranges[name]) {
  18658. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18659. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18660. if (this.animations[i]) {
  18661. this.animations[i].createRange(name, from, to);
  18662. }
  18663. }
  18664. }
  18665. };
  18666. /**
  18667. * Delete a specific animation range
  18668. * @param name defines the name of the range to delete
  18669. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18670. */
  18671. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18672. if (deleteFrames === void 0) { deleteFrames = true; }
  18673. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18674. if (this.animations[i]) {
  18675. this.animations[i].deleteRange(name, deleteFrames);
  18676. }
  18677. }
  18678. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18679. };
  18680. /**
  18681. * Get an animation range by name
  18682. * @param name defines the name of the animation range to look for
  18683. * @returns null if not found else the requested animation range
  18684. */
  18685. Node.prototype.getAnimationRange = function (name) {
  18686. return this._ranges[name];
  18687. };
  18688. /**
  18689. * Will start the animation sequence
  18690. * @param name defines the range frames for animation sequence
  18691. * @param loop defines if the animation should loop (false by default)
  18692. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18693. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18694. * @returns the object created for this animation. If range does not exist, it will return null
  18695. */
  18696. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18697. var range = this.getAnimationRange(name);
  18698. if (!range) {
  18699. return null;
  18700. }
  18701. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18702. };
  18703. /**
  18704. * Serialize animation ranges into a JSON compatible object
  18705. * @returns serialization object
  18706. */
  18707. Node.prototype.serializeAnimationRanges = function () {
  18708. var serializationRanges = [];
  18709. for (var name in this._ranges) {
  18710. var localRange = this._ranges[name];
  18711. if (!localRange) {
  18712. continue;
  18713. }
  18714. var range = {};
  18715. range.name = name;
  18716. range.from = localRange.from;
  18717. range.to = localRange.to;
  18718. serializationRanges.push(range);
  18719. }
  18720. return serializationRanges;
  18721. };
  18722. /**
  18723. * Computes the world matrix of the node
  18724. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18725. * @returns the world matrix
  18726. */
  18727. Node.prototype.computeWorldMatrix = function (force) {
  18728. if (!this._worldMatrix) {
  18729. this._worldMatrix = BABYLON.Matrix.Identity();
  18730. }
  18731. return this._worldMatrix;
  18732. };
  18733. /**
  18734. * Releases resources associated with this node.
  18735. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18736. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18737. */
  18738. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18739. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18740. if (!doNotRecurse) {
  18741. var nodes = this.getDescendants(true);
  18742. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18743. var node = nodes_1[_i];
  18744. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18745. }
  18746. }
  18747. else {
  18748. var transformNodes = this.getChildTransformNodes(true);
  18749. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18750. var transformNode = transformNodes_1[_a];
  18751. transformNode.parent = null;
  18752. transformNode.computeWorldMatrix(true);
  18753. }
  18754. }
  18755. if (!this.parent) {
  18756. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18757. if (rootNodeIndex > -1) {
  18758. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18759. }
  18760. }
  18761. else {
  18762. this.parent = null;
  18763. }
  18764. // Callback
  18765. this.onDisposeObservable.notifyObservers(this);
  18766. this.onDisposeObservable.clear();
  18767. // Behaviors
  18768. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18769. var behavior = _c[_b];
  18770. behavior.detach();
  18771. }
  18772. this._behaviors = [];
  18773. this._isDisposed = true;
  18774. };
  18775. /**
  18776. * Parse animation range data from a serialization object and store them into a given node
  18777. * @param node defines where to store the animation ranges
  18778. * @param parsedNode defines the serialization object to read data from
  18779. * @param scene defines the hosting scene
  18780. */
  18781. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18782. if (parsedNode.ranges) {
  18783. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18784. var data = parsedNode.ranges[index];
  18785. node.createAnimationRange(data.name, data.from, data.to);
  18786. }
  18787. }
  18788. };
  18789. Node._NodeConstructors = {};
  18790. __decorate([
  18791. BABYLON.serialize()
  18792. ], Node.prototype, "name", void 0);
  18793. __decorate([
  18794. BABYLON.serialize()
  18795. ], Node.prototype, "id", void 0);
  18796. __decorate([
  18797. BABYLON.serialize()
  18798. ], Node.prototype, "uniqueId", void 0);
  18799. __decorate([
  18800. BABYLON.serialize()
  18801. ], Node.prototype, "state", void 0);
  18802. __decorate([
  18803. BABYLON.serialize()
  18804. ], Node.prototype, "metadata", void 0);
  18805. return Node;
  18806. }());
  18807. BABYLON.Node = Node;
  18808. })(BABYLON || (BABYLON = {}));
  18809. //# sourceMappingURL=babylon.node.js.map
  18810. var BABYLON;
  18811. (function (BABYLON) {
  18812. // This matrix is used as a value to reset the bounding box.
  18813. var _identityMatrix = BABYLON.Matrix.Identity();
  18814. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18815. /**
  18816. * Class used to store bounding sphere information
  18817. */
  18818. var BoundingSphere = /** @class */ (function () {
  18819. /**
  18820. * Creates a new bounding sphere
  18821. * @param min defines the minimum vector (in local space)
  18822. * @param max defines the maximum vector (in local space)
  18823. */
  18824. function BoundingSphere(min, max) {
  18825. this.center = BABYLON.Vector3.Zero();
  18826. this.centerWorld = BABYLON.Vector3.Zero();
  18827. this.reConstruct(min, max);
  18828. }
  18829. /**
  18830. * Recreates the entire bounding sphere from scratch
  18831. * @param min defines the new minimum vector (in local space)
  18832. * @param max defines the new maximum vector (in local space)
  18833. */
  18834. BoundingSphere.prototype.reConstruct = function (min, max) {
  18835. this.minimum = min.clone();
  18836. this.maximum = max.clone();
  18837. var distance = BABYLON.Vector3.Distance(min, max);
  18838. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18839. this.radius = distance * 0.5;
  18840. this.centerWorld.set(0, 0, 0);
  18841. this._update(_identityMatrix);
  18842. };
  18843. /**
  18844. * Scale the current bounding sphere by applying a scale factor
  18845. * @param factor defines the scale factor to apply
  18846. * @returns the current bounding box
  18847. */
  18848. BoundingSphere.prototype.scale = function (factor) {
  18849. var newRadius = this.radius * factor;
  18850. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18851. var min = this.center.subtract(_tempRadiusVector);
  18852. var max = this.center.add(_tempRadiusVector);
  18853. this.reConstruct(min, max);
  18854. return this;
  18855. };
  18856. // Methods
  18857. /** @hidden */
  18858. BoundingSphere.prototype._update = function (world) {
  18859. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18860. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18861. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18862. };
  18863. /**
  18864. * Tests if the bounding sphere is intersecting the frustum planes
  18865. * @param frustumPlanes defines the frustum planes to test
  18866. * @returns true if there is an intersection
  18867. */
  18868. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18869. for (var i = 0; i < 6; i++) {
  18870. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18871. return false;
  18872. }
  18873. return true;
  18874. };
  18875. /**
  18876. * Tests if a point is inside the bounding sphere
  18877. * @param point defines the point to test
  18878. * @returns true if the point is inside the bounding sphere
  18879. */
  18880. BoundingSphere.prototype.intersectsPoint = function (point) {
  18881. var x = this.centerWorld.x - point.x;
  18882. var y = this.centerWorld.y - point.y;
  18883. var z = this.centerWorld.z - point.z;
  18884. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18885. if (this.radiusWorld < distance)
  18886. return false;
  18887. return true;
  18888. };
  18889. // Statics
  18890. /**
  18891. * Checks if two sphere intersct
  18892. * @param sphere0 sphere 0
  18893. * @param sphere1 sphere 1
  18894. * @returns true if the speres intersect
  18895. */
  18896. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18897. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18898. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18899. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18900. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18901. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18902. return false;
  18903. return true;
  18904. };
  18905. return BoundingSphere;
  18906. }());
  18907. BABYLON.BoundingSphere = BoundingSphere;
  18908. })(BABYLON || (BABYLON = {}));
  18909. //# sourceMappingURL=babylon.boundingSphere.js.map
  18910. var BABYLON;
  18911. (function (BABYLON) {
  18912. /**
  18913. * Class used to store bounding box information
  18914. */
  18915. var BoundingBox = /** @class */ (function () {
  18916. /**
  18917. * Creates a new bounding box
  18918. * @param min defines the minimum vector (in local space)
  18919. * @param max defines the maximum vector (in local space)
  18920. */
  18921. function BoundingBox(min, max) {
  18922. /**
  18923. * Gets the 8 vectors representing the bounding box in world space
  18924. */
  18925. this.vectorsWorld = new Array();
  18926. this.reConstruct(min, max);
  18927. }
  18928. // Methods
  18929. /**
  18930. * Recreates the entire bounding box from scratch
  18931. * @param min defines the new minimum vector (in local space)
  18932. * @param max defines the new maximum vector (in local space)
  18933. */
  18934. BoundingBox.prototype.reConstruct = function (min, max) {
  18935. this.minimum = min.clone();
  18936. this.maximum = max.clone();
  18937. // Bounding vectors
  18938. this.vectors = [
  18939. this.minimum.clone(),
  18940. this.maximum.clone(),
  18941. this.minimum.clone(),
  18942. this.minimum.clone(),
  18943. this.minimum.clone(),
  18944. this.maximum.clone(),
  18945. this.maximum.clone(),
  18946. this.maximum.clone()
  18947. ];
  18948. this.vectors[2].x = this.maximum.x;
  18949. this.vectors[3].y = this.maximum.y;
  18950. this.vectors[4].z = this.maximum.z;
  18951. this.vectors[5].z = this.minimum.z;
  18952. this.vectors[6].x = this.minimum.x;
  18953. this.vectors[7].y = this.minimum.y;
  18954. // OBB
  18955. this.center = this.maximum.add(this.minimum).scale(0.5);
  18956. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18957. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18958. // World
  18959. for (var index = 0; index < this.vectors.length; index++) {
  18960. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18961. }
  18962. this.minimumWorld = BABYLON.Vector3.Zero();
  18963. this.maximumWorld = BABYLON.Vector3.Zero();
  18964. this.centerWorld = BABYLON.Vector3.Zero();
  18965. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18966. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18967. };
  18968. /**
  18969. * Scale the current bounding box by applying a scale factor
  18970. * @param factor defines the scale factor to apply
  18971. * @returns the current bounding box
  18972. */
  18973. BoundingBox.prototype.scale = function (factor) {
  18974. var diff = this.maximum.subtract(this.minimum);
  18975. var distance = diff.length() * factor;
  18976. diff.normalize();
  18977. var newRadius = diff.scale(distance / 2);
  18978. var min = this.center.subtract(newRadius);
  18979. var max = this.center.add(newRadius);
  18980. this.reConstruct(min, max);
  18981. return this;
  18982. };
  18983. /**
  18984. * Gets the world matrix of the bounding box
  18985. * @returns a matrix
  18986. */
  18987. BoundingBox.prototype.getWorldMatrix = function () {
  18988. return this._worldMatrix;
  18989. };
  18990. /**
  18991. * Sets the world matrix stored in the bounding box
  18992. * @param matrix defines the matrix to store
  18993. * @returns current bounding box
  18994. */
  18995. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18996. this._worldMatrix.copyFrom(matrix);
  18997. return this;
  18998. };
  18999. /** @hidden */
  19000. BoundingBox.prototype._update = function (world) {
  19001. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19002. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19003. for (var index = 0; index < this.vectors.length; index++) {
  19004. var v = this.vectorsWorld[index];
  19005. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19006. if (v.x < this.minimumWorld.x)
  19007. this.minimumWorld.x = v.x;
  19008. if (v.y < this.minimumWorld.y)
  19009. this.minimumWorld.y = v.y;
  19010. if (v.z < this.minimumWorld.z)
  19011. this.minimumWorld.z = v.z;
  19012. if (v.x > this.maximumWorld.x)
  19013. this.maximumWorld.x = v.x;
  19014. if (v.y > this.maximumWorld.y)
  19015. this.maximumWorld.y = v.y;
  19016. if (v.z > this.maximumWorld.z)
  19017. this.maximumWorld.z = v.z;
  19018. }
  19019. // Extend
  19020. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19021. this.extendSizeWorld.scaleInPlace(0.5);
  19022. // OBB
  19023. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19024. this.centerWorld.scaleInPlace(0.5);
  19025. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19026. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19027. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19028. this._worldMatrix = world;
  19029. };
  19030. /**
  19031. * Tests if the bounding box is intersecting the frustum planes
  19032. * @param frustumPlanes defines the frustum planes to test
  19033. * @returns true if there is an intersection
  19034. */
  19035. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19036. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19037. };
  19038. /**
  19039. * Tests if the bounding box is entirely inside the frustum planes
  19040. * @param frustumPlanes defines the frustum planes to test
  19041. * @returns true if there is an inclusion
  19042. */
  19043. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19044. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19045. };
  19046. /**
  19047. * Tests if a point is inside the bounding box
  19048. * @param point defines the point to test
  19049. * @returns true if the point is inside the bounding box
  19050. */
  19051. BoundingBox.prototype.intersectsPoint = function (point) {
  19052. var delta = -BABYLON.Epsilon;
  19053. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19054. return false;
  19055. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19056. return false;
  19057. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19058. return false;
  19059. return true;
  19060. };
  19061. /**
  19062. * Tests if the bounding box intersects with a bounding sphere
  19063. * @param sphere defines the sphere to test
  19064. * @returns true if there is an intersection
  19065. */
  19066. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19067. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19068. };
  19069. /**
  19070. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19071. * @param min defines the min vector to use
  19072. * @param max defines the max vector to use
  19073. * @returns true if there is an intersection
  19074. */
  19075. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19076. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19077. return false;
  19078. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19079. return false;
  19080. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19081. return false;
  19082. return true;
  19083. };
  19084. // Statics
  19085. /**
  19086. * Tests if two bounding boxes are intersections
  19087. * @param box0 defines the first box to test
  19088. * @param box1 defines the second box to test
  19089. * @returns true if there is an intersection
  19090. */
  19091. BoundingBox.Intersects = function (box0, box1) {
  19092. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19093. return false;
  19094. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19095. return false;
  19096. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19097. return false;
  19098. return true;
  19099. };
  19100. /**
  19101. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19102. * @param minPoint defines the minimum vector of the bounding box
  19103. * @param maxPoint defines the maximum vector of the bounding box
  19104. * @param sphereCenter defines the sphere center
  19105. * @param sphereRadius defines the sphere radius
  19106. * @returns true if there is an intersection
  19107. */
  19108. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19109. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19110. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19111. return (num <= (sphereRadius * sphereRadius));
  19112. };
  19113. /**
  19114. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19115. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19116. * @param frustumPlanes defines the frustum planes to test
  19117. * @return true if there is an inclusion
  19118. */
  19119. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19120. for (var p = 0; p < 6; p++) {
  19121. for (var i = 0; i < 8; i++) {
  19122. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19123. return false;
  19124. }
  19125. }
  19126. }
  19127. return true;
  19128. };
  19129. /**
  19130. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19131. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19132. * @param frustumPlanes defines the frustum planes to test
  19133. * @return true if there is an intersection
  19134. */
  19135. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19136. for (var p = 0; p < 6; p++) {
  19137. var inCount = 8;
  19138. for (var i = 0; i < 8; i++) {
  19139. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19140. --inCount;
  19141. }
  19142. else {
  19143. break;
  19144. }
  19145. }
  19146. if (inCount === 0)
  19147. return false;
  19148. }
  19149. return true;
  19150. };
  19151. return BoundingBox;
  19152. }());
  19153. BABYLON.BoundingBox = BoundingBox;
  19154. })(BABYLON || (BABYLON = {}));
  19155. //# sourceMappingURL=babylon.boundingBox.js.map
  19156. var BABYLON;
  19157. (function (BABYLON) {
  19158. var computeBoxExtents = function (axis, box) {
  19159. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19160. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19161. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19162. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19163. var r = r0 + r1 + r2;
  19164. return {
  19165. min: p - r,
  19166. max: p + r
  19167. };
  19168. };
  19169. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19170. var axisOverlap = function (axis, box0, box1) {
  19171. var result0 = computeBoxExtents(axis, box0);
  19172. var result1 = computeBoxExtents(axis, box1);
  19173. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19174. };
  19175. /**
  19176. * Info for a bounding data of a mesh
  19177. */
  19178. var BoundingInfo = /** @class */ (function () {
  19179. /**
  19180. * Constructs bounding info
  19181. * @param minimum min vector of the bounding box/sphere
  19182. * @param maximum max vector of the bounding box/sphere
  19183. */
  19184. function BoundingInfo(
  19185. /**
  19186. * min vector of the bounding box/sphere
  19187. */
  19188. minimum,
  19189. /**
  19190. * max vector of the bounding box/sphere
  19191. */
  19192. maximum) {
  19193. this.minimum = minimum;
  19194. this.maximum = maximum;
  19195. this._isLocked = false;
  19196. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19197. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19198. }
  19199. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19200. /**
  19201. * If the info is locked and won't be updated to avoid perf overhead
  19202. */
  19203. get: function () {
  19204. return this._isLocked;
  19205. },
  19206. set: function (value) {
  19207. this._isLocked = value;
  19208. },
  19209. enumerable: true,
  19210. configurable: true
  19211. });
  19212. // Methods
  19213. /**
  19214. * Updates the boudning sphere and box
  19215. * @param world world matrix to be used to update
  19216. */
  19217. BoundingInfo.prototype.update = function (world) {
  19218. if (this._isLocked) {
  19219. return;
  19220. }
  19221. this.boundingBox._update(world);
  19222. this.boundingSphere._update(world);
  19223. };
  19224. /**
  19225. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19226. * @param center New center of the bounding info
  19227. * @param extend New extend of the bounding info
  19228. * @returns the current bounding info
  19229. */
  19230. BoundingInfo.prototype.centerOn = function (center, extend) {
  19231. this.minimum = center.subtract(extend);
  19232. this.maximum = center.add(extend);
  19233. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  19234. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  19235. return this;
  19236. };
  19237. /**
  19238. * Scale the current bounding info by applying a scale factor
  19239. * @param factor defines the scale factor to apply
  19240. * @returns the current bounding info
  19241. */
  19242. BoundingInfo.prototype.scale = function (factor) {
  19243. this.boundingBox.scale(factor);
  19244. this.boundingSphere.scale(factor);
  19245. return this;
  19246. };
  19247. /**
  19248. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19249. * @param frustumPlanes defines the frustum to test
  19250. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19251. * @returns true if the bounding info is in the frustum planes
  19252. */
  19253. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19254. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19255. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19256. return false;
  19257. }
  19258. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19259. return true;
  19260. }
  19261. return this.boundingBox.isInFrustum(frustumPlanes);
  19262. };
  19263. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19264. /**
  19265. * Gets the world distance between the min and max points of the bounding box
  19266. */
  19267. get: function () {
  19268. var boundingBox = this.boundingBox;
  19269. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19270. return size.length();
  19271. },
  19272. enumerable: true,
  19273. configurable: true
  19274. });
  19275. /**
  19276. * Checks if a cullable object (mesh...) is in the camera frustum
  19277. * Unlike isInFrustum this cheks the full bounding box
  19278. * @param frustumPlanes Camera near/planes
  19279. * @returns true if the object is in frustum otherwise false
  19280. */
  19281. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19282. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19283. };
  19284. /** @hidden */
  19285. BoundingInfo.prototype._checkCollision = function (collider) {
  19286. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19287. };
  19288. /**
  19289. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19290. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19291. * @param point the point to check intersection with
  19292. * @returns if the point intersects
  19293. */
  19294. BoundingInfo.prototype.intersectsPoint = function (point) {
  19295. if (!this.boundingSphere.centerWorld) {
  19296. return false;
  19297. }
  19298. if (!this.boundingSphere.intersectsPoint(point)) {
  19299. return false;
  19300. }
  19301. if (!this.boundingBox.intersectsPoint(point)) {
  19302. return false;
  19303. }
  19304. return true;
  19305. };
  19306. /**
  19307. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19308. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19309. * @param boundingInfo the bounding info to check intersection with
  19310. * @param precise if the intersection should be done using OBB
  19311. * @returns if the bounding info intersects
  19312. */
  19313. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19314. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19315. return false;
  19316. }
  19317. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19318. return false;
  19319. }
  19320. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19321. return false;
  19322. }
  19323. if (!precise) {
  19324. return true;
  19325. }
  19326. var box0 = this.boundingBox;
  19327. var box1 = boundingInfo.boundingBox;
  19328. if (!axisOverlap(box0.directions[0], box0, box1))
  19329. return false;
  19330. if (!axisOverlap(box0.directions[1], box0, box1))
  19331. return false;
  19332. if (!axisOverlap(box0.directions[2], box0, box1))
  19333. return false;
  19334. if (!axisOverlap(box1.directions[0], box0, box1))
  19335. return false;
  19336. if (!axisOverlap(box1.directions[1], box0, box1))
  19337. return false;
  19338. if (!axisOverlap(box1.directions[2], box0, box1))
  19339. return false;
  19340. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19341. return false;
  19342. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19343. return false;
  19344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19345. return false;
  19346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19347. return false;
  19348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19349. return false;
  19350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19351. return false;
  19352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19353. return false;
  19354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19355. return false;
  19356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19357. return false;
  19358. return true;
  19359. };
  19360. return BoundingInfo;
  19361. }());
  19362. BABYLON.BoundingInfo = BoundingInfo;
  19363. })(BABYLON || (BABYLON = {}));
  19364. //# sourceMappingURL=babylon.boundingInfo.js.map
  19365. var BABYLON;
  19366. (function (BABYLON) {
  19367. var TransformNode = /** @class */ (function (_super) {
  19368. __extends(TransformNode, _super);
  19369. function TransformNode(name, scene, isPure) {
  19370. if (scene === void 0) { scene = null; }
  19371. if (isPure === void 0) { isPure = true; }
  19372. var _this = _super.call(this, name, scene) || this;
  19373. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19374. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19375. _this._up = new BABYLON.Vector3(0, 1, 0);
  19376. _this._right = new BABYLON.Vector3(1, 0, 0);
  19377. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19378. // Properties
  19379. _this._position = BABYLON.Vector3.Zero();
  19380. _this._rotation = BABYLON.Vector3.Zero();
  19381. _this._scaling = BABYLON.Vector3.One();
  19382. _this._isDirty = false;
  19383. /**
  19384. * Set the billboard mode. Default is 0.
  19385. *
  19386. * | Value | Type | Description |
  19387. * | --- | --- | --- |
  19388. * | 0 | BILLBOARDMODE_NONE | |
  19389. * | 1 | BILLBOARDMODE_X | |
  19390. * | 2 | BILLBOARDMODE_Y | |
  19391. * | 4 | BILLBOARDMODE_Z | |
  19392. * | 7 | BILLBOARDMODE_ALL | |
  19393. *
  19394. */
  19395. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19396. _this.scalingDeterminant = 1;
  19397. _this.infiniteDistance = false;
  19398. /**
  19399. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19400. * By default the system will update normals to compensate
  19401. */
  19402. _this.ignoreNonUniformScaling = false;
  19403. _this._localWorld = BABYLON.Matrix.Zero();
  19404. _this._absolutePosition = BABYLON.Vector3.Zero();
  19405. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19406. _this._postMultiplyPivotMatrix = false;
  19407. _this._isWorldMatrixFrozen = false;
  19408. /**
  19409. * An event triggered after the world matrix is updated
  19410. */
  19411. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19412. _this._nonUniformScaling = false;
  19413. if (isPure) {
  19414. _this.getScene().addTransformNode(_this);
  19415. }
  19416. return _this;
  19417. }
  19418. /**
  19419. * Gets a string identifying the name of the class
  19420. * @returns "TransformNode" string
  19421. */
  19422. TransformNode.prototype.getClassName = function () {
  19423. return "TransformNode";
  19424. };
  19425. Object.defineProperty(TransformNode.prototype, "position", {
  19426. /**
  19427. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19428. */
  19429. get: function () {
  19430. return this._position;
  19431. },
  19432. set: function (newPosition) {
  19433. this._position = newPosition;
  19434. this._isDirty = true;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(TransformNode.prototype, "rotation", {
  19440. /**
  19441. * 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)).
  19442. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19443. */
  19444. get: function () {
  19445. return this._rotation;
  19446. },
  19447. set: function (newRotation) {
  19448. this._rotation = newRotation;
  19449. this._isDirty = true;
  19450. },
  19451. enumerable: true,
  19452. configurable: true
  19453. });
  19454. Object.defineProperty(TransformNode.prototype, "scaling", {
  19455. /**
  19456. * 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)).
  19457. */
  19458. get: function () {
  19459. return this._scaling;
  19460. },
  19461. set: function (newScaling) {
  19462. this._scaling = newScaling;
  19463. this._isDirty = true;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19469. /**
  19470. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19471. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19472. */
  19473. get: function () {
  19474. return this._rotationQuaternion;
  19475. },
  19476. set: function (quaternion) {
  19477. this._rotationQuaternion = quaternion;
  19478. //reset the rotation vector.
  19479. if (quaternion && this.rotation.length()) {
  19480. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19481. }
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(TransformNode.prototype, "forward", {
  19487. /**
  19488. * The forward direction of that transform in world space.
  19489. */
  19490. get: function () {
  19491. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(TransformNode.prototype, "up", {
  19497. /**
  19498. * The up direction of that transform in world space.
  19499. */
  19500. get: function () {
  19501. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(TransformNode.prototype, "right", {
  19507. /**
  19508. * The right direction of that transform in world space.
  19509. */
  19510. get: function () {
  19511. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. /**
  19517. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19518. * Returns the TransformNode.
  19519. */
  19520. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19521. this._poseMatrix.copyFrom(matrix);
  19522. return this;
  19523. };
  19524. /**
  19525. * Returns the mesh Pose matrix.
  19526. * Returned object : Matrix
  19527. */
  19528. TransformNode.prototype.getPoseMatrix = function () {
  19529. return this._poseMatrix;
  19530. };
  19531. /** @hidden */
  19532. TransformNode.prototype._isSynchronized = function () {
  19533. if (this._isDirty) {
  19534. return false;
  19535. }
  19536. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19537. return false;
  19538. if (this._cache.pivotMatrixUpdated) {
  19539. return false;
  19540. }
  19541. if (this.infiniteDistance) {
  19542. return false;
  19543. }
  19544. if (!this._cache.position.equals(this._position))
  19545. return false;
  19546. if (this._rotationQuaternion) {
  19547. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19548. return false;
  19549. }
  19550. if (!this._cache.rotation.equals(this._rotation))
  19551. return false;
  19552. if (!this._cache.scaling.equals(this._scaling))
  19553. return false;
  19554. return true;
  19555. };
  19556. /** @hidden */
  19557. TransformNode.prototype._initCache = function () {
  19558. _super.prototype._initCache.call(this);
  19559. this._cache.localMatrixUpdated = false;
  19560. this._cache.position = BABYLON.Vector3.Zero();
  19561. this._cache.scaling = BABYLON.Vector3.Zero();
  19562. this._cache.rotation = BABYLON.Vector3.Zero();
  19563. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19564. this._cache.billboardMode = -1;
  19565. };
  19566. TransformNode.prototype.markAsDirty = function (property) {
  19567. if (property === "rotation") {
  19568. this.rotationQuaternion = null;
  19569. }
  19570. this._currentRenderId = Number.MAX_VALUE;
  19571. this._isDirty = true;
  19572. return this;
  19573. };
  19574. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19575. /**
  19576. * Returns the current mesh absolute position.
  19577. * Returns a Vector3.
  19578. */
  19579. get: function () {
  19580. return this._absolutePosition;
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. /**
  19586. * Sets a new matrix to apply before all other transformation
  19587. * @param matrix defines the transform matrix
  19588. * @returns the current TransformNode
  19589. */
  19590. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19591. return this.setPivotMatrix(matrix, false);
  19592. };
  19593. /**
  19594. * Sets a new pivot matrix to the current node
  19595. * @param matrix defines the new pivot matrix to use
  19596. * @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
  19597. * @returns the current TransformNode
  19598. */
  19599. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19600. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19601. this._pivotMatrix = matrix.clone();
  19602. this._cache.pivotMatrixUpdated = true;
  19603. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19604. if (this._postMultiplyPivotMatrix) {
  19605. if (!this._pivotMatrixInverse) {
  19606. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19607. }
  19608. else {
  19609. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19610. }
  19611. }
  19612. return this;
  19613. };
  19614. /**
  19615. * Returns the mesh pivot matrix.
  19616. * Default : Identity.
  19617. * A Matrix is returned.
  19618. */
  19619. TransformNode.prototype.getPivotMatrix = function () {
  19620. return this._pivotMatrix;
  19621. };
  19622. /**
  19623. * Prevents the World matrix to be computed any longer.
  19624. * Returns the TransformNode.
  19625. */
  19626. TransformNode.prototype.freezeWorldMatrix = function () {
  19627. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19628. this.computeWorldMatrix(true);
  19629. this._isWorldMatrixFrozen = true;
  19630. return this;
  19631. };
  19632. /**
  19633. * Allows back the World matrix computation.
  19634. * Returns the TransformNode.
  19635. */
  19636. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19637. this._isWorldMatrixFrozen = false;
  19638. this.computeWorldMatrix(true);
  19639. return this;
  19640. };
  19641. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19642. /**
  19643. * True if the World matrix has been frozen.
  19644. * Returns a boolean.
  19645. */
  19646. get: function () {
  19647. return this._isWorldMatrixFrozen;
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. /**
  19653. * Retuns the mesh absolute position in the World.
  19654. * Returns a Vector3.
  19655. */
  19656. TransformNode.prototype.getAbsolutePosition = function () {
  19657. this.computeWorldMatrix();
  19658. return this._absolutePosition;
  19659. };
  19660. /**
  19661. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19662. * Returns the TransformNode.
  19663. */
  19664. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19665. if (!absolutePosition) {
  19666. return this;
  19667. }
  19668. var absolutePositionX;
  19669. var absolutePositionY;
  19670. var absolutePositionZ;
  19671. if (absolutePosition.x === undefined) {
  19672. if (arguments.length < 3) {
  19673. return this;
  19674. }
  19675. absolutePositionX = arguments[0];
  19676. absolutePositionY = arguments[1];
  19677. absolutePositionZ = arguments[2];
  19678. }
  19679. else {
  19680. absolutePositionX = absolutePosition.x;
  19681. absolutePositionY = absolutePosition.y;
  19682. absolutePositionZ = absolutePosition.z;
  19683. }
  19684. if (this.parent) {
  19685. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19686. invertParentWorldMatrix.invert();
  19687. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19688. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19689. }
  19690. else {
  19691. this.position.x = absolutePositionX;
  19692. this.position.y = absolutePositionY;
  19693. this.position.z = absolutePositionZ;
  19694. }
  19695. return this;
  19696. };
  19697. /**
  19698. * Sets the mesh position in its local space.
  19699. * Returns the TransformNode.
  19700. */
  19701. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19702. this.computeWorldMatrix();
  19703. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19704. return this;
  19705. };
  19706. /**
  19707. * Returns the mesh position in the local space from the current World matrix values.
  19708. * Returns a new Vector3.
  19709. */
  19710. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19711. this.computeWorldMatrix();
  19712. var invLocalWorldMatrix = this._localWorld.clone();
  19713. invLocalWorldMatrix.invert();
  19714. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19715. };
  19716. /**
  19717. * Translates the mesh along the passed Vector3 in its local space.
  19718. * Returns the TransformNode.
  19719. */
  19720. TransformNode.prototype.locallyTranslate = function (vector3) {
  19721. this.computeWorldMatrix(true);
  19722. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19723. return this;
  19724. };
  19725. /**
  19726. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19727. * @param targetPoint the position (must be in same space as current mesh) to look at
  19728. * @param yawCor optional yaw (y-axis) correction in radians
  19729. * @param pitchCor optional pitch (x-axis) correction in radians
  19730. * @param rollCor optional roll (z-axis) correction in radians
  19731. * @param space the choosen space of the target
  19732. * @returns the TransformNode.
  19733. */
  19734. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19735. if (yawCor === void 0) { yawCor = 0; }
  19736. if (pitchCor === void 0) { pitchCor = 0; }
  19737. if (rollCor === void 0) { rollCor = 0; }
  19738. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19739. var dv = TransformNode._lookAtVectorCache;
  19740. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19741. targetPoint.subtractToRef(pos, dv);
  19742. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19743. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19744. var pitch = Math.atan2(dv.y, len);
  19745. if (this.rotationQuaternion) {
  19746. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19747. }
  19748. else {
  19749. this.rotation.x = pitch + pitchCor;
  19750. this.rotation.y = yaw + yawCor;
  19751. this.rotation.z = rollCor;
  19752. }
  19753. return this;
  19754. };
  19755. /**
  19756. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19757. * This Vector3 is expressed in the World space.
  19758. */
  19759. TransformNode.prototype.getDirection = function (localAxis) {
  19760. var result = BABYLON.Vector3.Zero();
  19761. this.getDirectionToRef(localAxis, result);
  19762. return result;
  19763. };
  19764. /**
  19765. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19766. * localAxis is expressed in the mesh local space.
  19767. * result is computed in the Wordl space from the mesh World matrix.
  19768. * Returns the TransformNode.
  19769. */
  19770. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19771. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19772. return this;
  19773. };
  19774. /**
  19775. * Sets a new pivot point to the current node
  19776. * @param point defines the new pivot point to use
  19777. * @param space defines if the point is in world or local space (local by default)
  19778. * @returns the current TransformNode
  19779. */
  19780. TransformNode.prototype.setPivotPoint = function (point, space) {
  19781. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19782. if (this.getScene().getRenderId() == 0) {
  19783. this.computeWorldMatrix(true);
  19784. }
  19785. var wm = this.getWorldMatrix();
  19786. if (space == BABYLON.Space.WORLD) {
  19787. var tmat = BABYLON.Tmp.Matrix[0];
  19788. wm.invertToRef(tmat);
  19789. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19790. }
  19791. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19792. };
  19793. /**
  19794. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19795. */
  19796. TransformNode.prototype.getPivotPoint = function () {
  19797. var point = BABYLON.Vector3.Zero();
  19798. this.getPivotPointToRef(point);
  19799. return point;
  19800. };
  19801. /**
  19802. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19803. * Returns the TransformNode.
  19804. */
  19805. TransformNode.prototype.getPivotPointToRef = function (result) {
  19806. result.x = -this._pivotMatrix.m[12];
  19807. result.y = -this._pivotMatrix.m[13];
  19808. result.z = -this._pivotMatrix.m[14];
  19809. return this;
  19810. };
  19811. /**
  19812. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19813. */
  19814. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19815. var point = BABYLON.Vector3.Zero();
  19816. this.getAbsolutePivotPointToRef(point);
  19817. return point;
  19818. };
  19819. /**
  19820. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19821. * Returns the TransformNode.
  19822. */
  19823. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19824. result.x = this._pivotMatrix.m[12];
  19825. result.y = this._pivotMatrix.m[13];
  19826. result.z = this._pivotMatrix.m[14];
  19827. this.getPivotPointToRef(result);
  19828. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19829. return this;
  19830. };
  19831. /**
  19832. * Defines the passed node as the parent of the current node.
  19833. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19834. * Returns the TransformNode.
  19835. */
  19836. TransformNode.prototype.setParent = function (node) {
  19837. if (!node && !this.parent) {
  19838. return this;
  19839. }
  19840. if (!node) {
  19841. var rotation = BABYLON.Tmp.Quaternion[0];
  19842. var position = BABYLON.Tmp.Vector3[0];
  19843. var scale = BABYLON.Tmp.Vector3[1];
  19844. if (this.parent && this.parent.computeWorldMatrix) {
  19845. this.parent.computeWorldMatrix(true);
  19846. }
  19847. this.computeWorldMatrix(true);
  19848. this.getWorldMatrix().decompose(scale, rotation, position);
  19849. if (this.rotationQuaternion) {
  19850. this.rotationQuaternion.copyFrom(rotation);
  19851. }
  19852. else {
  19853. rotation.toEulerAnglesToRef(this.rotation);
  19854. }
  19855. this.scaling.x = scale.x;
  19856. this.scaling.y = scale.y;
  19857. this.scaling.z = scale.z;
  19858. this.position.x = position.x;
  19859. this.position.y = position.y;
  19860. this.position.z = position.z;
  19861. }
  19862. else {
  19863. var rotation = BABYLON.Tmp.Quaternion[0];
  19864. var position = BABYLON.Tmp.Vector3[0];
  19865. var scale = BABYLON.Tmp.Vector3[1];
  19866. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19867. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19868. this.computeWorldMatrix(true);
  19869. node.computeWorldMatrix(true);
  19870. node.getWorldMatrix().invertToRef(invParentMatrix);
  19871. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19872. diffMatrix.decompose(scale, rotation, position);
  19873. if (this.rotationQuaternion) {
  19874. this.rotationQuaternion.copyFrom(rotation);
  19875. }
  19876. else {
  19877. rotation.toEulerAnglesToRef(this.rotation);
  19878. }
  19879. this.position.x = position.x;
  19880. this.position.y = position.y;
  19881. this.position.z = position.z;
  19882. this.scaling.x = scale.x;
  19883. this.scaling.y = scale.y;
  19884. this.scaling.z = scale.z;
  19885. }
  19886. this.parent = node;
  19887. return this;
  19888. };
  19889. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19890. get: function () {
  19891. return this._nonUniformScaling;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. /** @hidden */
  19897. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19898. if (this._nonUniformScaling === value) {
  19899. return false;
  19900. }
  19901. this._nonUniformScaling = value;
  19902. return true;
  19903. };
  19904. /**
  19905. * Attach the current TransformNode to another TransformNode associated with a bone
  19906. * @param bone Bone affecting the TransformNode
  19907. * @param affectedTransformNode TransformNode associated with the bone
  19908. */
  19909. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19910. this._transformToBoneReferal = affectedTransformNode;
  19911. this.parent = bone;
  19912. if (bone.getWorldMatrix().determinant() < 0) {
  19913. this.scalingDeterminant *= -1;
  19914. }
  19915. return this;
  19916. };
  19917. TransformNode.prototype.detachFromBone = function () {
  19918. if (!this.parent) {
  19919. return this;
  19920. }
  19921. if (this.parent.getWorldMatrix().determinant() < 0) {
  19922. this.scalingDeterminant *= -1;
  19923. }
  19924. this._transformToBoneReferal = null;
  19925. this.parent = null;
  19926. return this;
  19927. };
  19928. /**
  19929. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19930. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19931. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19932. * The passed axis is also normalized.
  19933. * Returns the TransformNode.
  19934. */
  19935. TransformNode.prototype.rotate = function (axis, amount, space) {
  19936. axis.normalize();
  19937. if (!this.rotationQuaternion) {
  19938. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19939. this.rotation = BABYLON.Vector3.Zero();
  19940. }
  19941. var rotationQuaternion;
  19942. if (!space || space === BABYLON.Space.LOCAL) {
  19943. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19944. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19945. }
  19946. else {
  19947. if (this.parent) {
  19948. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19949. invertParentWorldMatrix.invert();
  19950. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19951. }
  19952. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19953. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19954. }
  19955. return this;
  19956. };
  19957. /**
  19958. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19959. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19960. * The passed axis is also normalized.
  19961. * Returns the TransformNode.
  19962. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19963. */
  19964. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19965. axis.normalize();
  19966. if (!this.rotationQuaternion) {
  19967. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19968. this.rotation.copyFromFloats(0, 0, 0);
  19969. }
  19970. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19971. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19972. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19973. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19974. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19975. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19976. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19977. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19978. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19979. return this;
  19980. };
  19981. /**
  19982. * Translates the mesh along the axis vector for the passed distance in the given space.
  19983. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19984. * Returns the TransformNode.
  19985. */
  19986. TransformNode.prototype.translate = function (axis, distance, space) {
  19987. var displacementVector = axis.scale(distance);
  19988. if (!space || space === BABYLON.Space.LOCAL) {
  19989. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19990. this.setPositionWithLocalVector(tempV3);
  19991. }
  19992. else {
  19993. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19994. }
  19995. return this;
  19996. };
  19997. /**
  19998. * Adds a rotation step to the mesh current rotation.
  19999. * x, y, z are Euler angles expressed in radians.
  20000. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20001. * This means this rotation is made in the mesh local space only.
  20002. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20003. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20004. * ```javascript
  20005. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20006. * ```
  20007. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20008. * 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.
  20009. * Returns the TransformNode.
  20010. */
  20011. TransformNode.prototype.addRotation = function (x, y, z) {
  20012. var rotationQuaternion;
  20013. if (this.rotationQuaternion) {
  20014. rotationQuaternion = this.rotationQuaternion;
  20015. }
  20016. else {
  20017. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20018. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20019. }
  20020. var accumulation = BABYLON.Tmp.Quaternion[0];
  20021. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20022. rotationQuaternion.multiplyInPlace(accumulation);
  20023. if (!this.rotationQuaternion) {
  20024. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20025. }
  20026. return this;
  20027. };
  20028. /**
  20029. * Computes the world matrix of the node
  20030. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20031. * @returns the world matrix
  20032. */
  20033. TransformNode.prototype.computeWorldMatrix = function (force) {
  20034. if (this._isWorldMatrixFrozen) {
  20035. return this._worldMatrix;
  20036. }
  20037. if (!force && this.isSynchronized()) {
  20038. this._currentRenderId = this.getScene().getRenderId();
  20039. return this._worldMatrix;
  20040. }
  20041. this._updateCache();
  20042. this._cache.position.copyFrom(this.position);
  20043. this._cache.scaling.copyFrom(this.scaling);
  20044. this._cache.pivotMatrixUpdated = false;
  20045. this._cache.billboardMode = this.billboardMode;
  20046. this._currentRenderId = this.getScene().getRenderId();
  20047. this._childRenderId = this.getScene().getRenderId();
  20048. this._isDirty = false;
  20049. // Scaling
  20050. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20051. // Rotation
  20052. //rotate, if quaternion is set and rotation was used
  20053. if (this.rotationQuaternion) {
  20054. var len = this.rotation.length();
  20055. if (len) {
  20056. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20057. this.rotation.copyFromFloats(0, 0, 0);
  20058. }
  20059. }
  20060. if (this.rotationQuaternion) {
  20061. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20062. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20063. }
  20064. else {
  20065. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20066. this._cache.rotation.copyFrom(this.rotation);
  20067. }
  20068. // Translation
  20069. var camera = this.getScene().activeCamera;
  20070. if (this.infiniteDistance && !this.parent && camera) {
  20071. var cameraWorldMatrix = camera.getWorldMatrix();
  20072. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20073. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20074. }
  20075. else {
  20076. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20077. }
  20078. // Composing transformations
  20079. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20080. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20081. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20082. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20083. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20084. // Need to decompose each rotation here
  20085. var currentPosition = BABYLON.Tmp.Vector3[3];
  20086. if (this.parent && this.parent.getWorldMatrix) {
  20087. if (this._transformToBoneReferal) {
  20088. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20089. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20090. }
  20091. else {
  20092. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20093. }
  20094. }
  20095. else {
  20096. currentPosition.copyFrom(this.position);
  20097. }
  20098. currentPosition.subtractInPlace(camera.globalPosition);
  20099. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20100. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20101. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20102. }
  20103. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20104. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20105. }
  20106. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20107. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20108. }
  20109. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20110. }
  20111. else {
  20112. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20113. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20114. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20115. }
  20116. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20117. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20118. }
  20119. // Post multiply inverse of pivotMatrix
  20120. if (this._postMultiplyPivotMatrix) {
  20121. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20122. }
  20123. // Local world
  20124. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20125. // Parent
  20126. if (this.parent && this.parent.getWorldMatrix) {
  20127. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20128. if (this._transformToBoneReferal) {
  20129. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20130. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20131. }
  20132. else {
  20133. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20134. }
  20135. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20136. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20137. this._worldMatrix.copyFrom(this._localWorld);
  20138. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20139. }
  20140. else {
  20141. if (this._transformToBoneReferal) {
  20142. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20143. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20144. }
  20145. else {
  20146. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20147. }
  20148. }
  20149. this._markSyncedWithParent();
  20150. }
  20151. else {
  20152. this._worldMatrix.copyFrom(this._localWorld);
  20153. }
  20154. // Normal matrix
  20155. if (!this.ignoreNonUniformScaling) {
  20156. if (this.scaling.isNonUniform) {
  20157. this._updateNonUniformScalingState(true);
  20158. }
  20159. else if (this.parent && this.parent._nonUniformScaling) {
  20160. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20161. }
  20162. else {
  20163. this._updateNonUniformScalingState(false);
  20164. }
  20165. }
  20166. else {
  20167. this._updateNonUniformScalingState(false);
  20168. }
  20169. this._afterComputeWorldMatrix();
  20170. // Absolute position
  20171. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20172. // Callbacks
  20173. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20174. if (!this._poseMatrix) {
  20175. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20176. }
  20177. // Cache the determinant
  20178. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20179. return this._worldMatrix;
  20180. };
  20181. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20182. };
  20183. /**
  20184. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20185. * @param func: callback function to add
  20186. *
  20187. * Returns the TransformNode.
  20188. */
  20189. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20190. this.onAfterWorldMatrixUpdateObservable.add(func);
  20191. return this;
  20192. };
  20193. /**
  20194. * Removes a registered callback function.
  20195. * Returns the TransformNode.
  20196. */
  20197. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20198. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20199. return this;
  20200. };
  20201. /**
  20202. * Clone the current transform node
  20203. * Returns the new transform node
  20204. * @param name Name of the new clone
  20205. * @param newParent New parent for the clone
  20206. * @param doNotCloneChildren Do not clone children hierarchy
  20207. */
  20208. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20209. var _this = this;
  20210. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20211. result.name = name;
  20212. result.id = name;
  20213. if (newParent) {
  20214. result.parent = newParent;
  20215. }
  20216. if (!doNotCloneChildren) {
  20217. // Children
  20218. var directDescendants = this.getDescendants(true);
  20219. for (var index = 0; index < directDescendants.length; index++) {
  20220. var child = directDescendants[index];
  20221. if (child.clone) {
  20222. child.clone(name + "." + child.name, result);
  20223. }
  20224. }
  20225. }
  20226. return result;
  20227. };
  20228. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20229. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20230. serializationObject.type = this.getClassName();
  20231. // Parent
  20232. if (this.parent) {
  20233. serializationObject.parentId = this.parent.id;
  20234. }
  20235. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20236. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20237. }
  20238. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20239. serializationObject.isEnabled = this.isEnabled();
  20240. // Parent
  20241. if (this.parent) {
  20242. serializationObject.parentId = this.parent.id;
  20243. }
  20244. return serializationObject;
  20245. };
  20246. // Statics
  20247. /**
  20248. * Returns a new TransformNode object parsed from the source provided.
  20249. * The parameter `parsedMesh` is the source.
  20250. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20251. */
  20252. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20253. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20254. if (BABYLON.Tags) {
  20255. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20256. }
  20257. if (parsedTransformNode.localMatrix) {
  20258. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20259. }
  20260. else if (parsedTransformNode.pivotMatrix) {
  20261. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20262. }
  20263. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20264. // Parent
  20265. if (parsedTransformNode.parentId) {
  20266. transformNode._waitingParentId = parsedTransformNode.parentId;
  20267. }
  20268. return transformNode;
  20269. };
  20270. /**
  20271. * Releases resources associated with this transform node.
  20272. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20273. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20274. */
  20275. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20276. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20277. // Animations
  20278. this.getScene().stopAnimation(this);
  20279. // Remove from scene
  20280. this.getScene().removeTransformNode(this);
  20281. this.onAfterWorldMatrixUpdateObservable.clear();
  20282. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20283. };
  20284. // Statics
  20285. TransformNode.BILLBOARDMODE_NONE = 0;
  20286. TransformNode.BILLBOARDMODE_X = 1;
  20287. TransformNode.BILLBOARDMODE_Y = 2;
  20288. TransformNode.BILLBOARDMODE_Z = 4;
  20289. TransformNode.BILLBOARDMODE_ALL = 7;
  20290. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20291. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20292. __decorate([
  20293. BABYLON.serializeAsVector3("position")
  20294. ], TransformNode.prototype, "_position", void 0);
  20295. __decorate([
  20296. BABYLON.serializeAsVector3("rotation")
  20297. ], TransformNode.prototype, "_rotation", void 0);
  20298. __decorate([
  20299. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20300. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20301. __decorate([
  20302. BABYLON.serializeAsVector3("scaling")
  20303. ], TransformNode.prototype, "_scaling", void 0);
  20304. __decorate([
  20305. BABYLON.serialize()
  20306. ], TransformNode.prototype, "billboardMode", void 0);
  20307. __decorate([
  20308. BABYLON.serialize()
  20309. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20310. __decorate([
  20311. BABYLON.serialize()
  20312. ], TransformNode.prototype, "infiniteDistance", void 0);
  20313. __decorate([
  20314. BABYLON.serialize()
  20315. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20316. return TransformNode;
  20317. }(BABYLON.Node));
  20318. BABYLON.TransformNode = TransformNode;
  20319. })(BABYLON || (BABYLON = {}));
  20320. //# sourceMappingURL=babylon.transformNode.js.map
  20321. var BABYLON;
  20322. (function (BABYLON) {
  20323. /** @hidden */
  20324. var _FacetDataStorage = /** @class */ (function () {
  20325. function _FacetDataStorage() {
  20326. this.facetNb = 0; // facet number
  20327. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20328. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20329. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20330. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20331. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20332. this.subDiv = {
  20333. max: 1,
  20334. X: 1,
  20335. Y: 1,
  20336. Z: 1
  20337. };
  20338. this.facetDepthSort = false; // is the facet depth sort to be computed
  20339. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20340. }
  20341. return _FacetDataStorage;
  20342. }());
  20343. /**
  20344. * Class used to store all common mesh properties
  20345. */
  20346. var AbstractMesh = /** @class */ (function (_super) {
  20347. __extends(AbstractMesh, _super);
  20348. // Constructor
  20349. /**
  20350. * Creates a new AbstractMesh
  20351. * @param name defines the name of the mesh
  20352. * @param scene defines the hosting scene
  20353. */
  20354. function AbstractMesh(name, scene) {
  20355. if (scene === void 0) { scene = null; }
  20356. var _this = _super.call(this, name, scene, false) || this;
  20357. _this._facetData = new _FacetDataStorage();
  20358. /** Gets ot sets the culling strategy to use to find visible meshes */
  20359. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20360. // Events
  20361. /**
  20362. * An event triggered when this mesh collides with another one
  20363. */
  20364. _this.onCollideObservable = new BABYLON.Observable();
  20365. /**
  20366. * An event triggered when the collision's position changes
  20367. */
  20368. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20369. /**
  20370. * An event triggered when material is changed
  20371. */
  20372. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20373. // Properties
  20374. /**
  20375. * Gets or sets the orientation for POV movement & rotation
  20376. */
  20377. _this.definedFacingForward = true;
  20378. _this._visibility = 1.0;
  20379. /** Gets or sets the alpha index used to sort transparent meshes
  20380. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20381. */
  20382. _this.alphaIndex = Number.MAX_VALUE;
  20383. /**
  20384. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20385. */
  20386. _this.isVisible = true;
  20387. /**
  20388. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20389. */
  20390. _this.isPickable = true;
  20391. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20392. _this.showSubMeshesBoundingBox = false;
  20393. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20394. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20395. */
  20396. _this.isBlocker = false;
  20397. /**
  20398. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20399. */
  20400. _this.enablePointerMoveEvents = false;
  20401. /**
  20402. * Specifies the rendering group id for this mesh (0 by default)
  20403. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20404. */
  20405. _this.renderingGroupId = 0;
  20406. _this._receiveShadows = false;
  20407. /** Defines color to use when rendering outline */
  20408. _this.outlineColor = BABYLON.Color3.Red();
  20409. /** Define width to use when rendering outline */
  20410. _this.outlineWidth = 0.02;
  20411. /** Defines color to use when rendering overlay */
  20412. _this.overlayColor = BABYLON.Color3.Red();
  20413. /** Defines alpha to use when rendering overlay */
  20414. _this.overlayAlpha = 0.5;
  20415. _this._hasVertexAlpha = false;
  20416. _this._useVertexColors = true;
  20417. _this._computeBonesUsingShaders = true;
  20418. _this._numBoneInfluencers = 4;
  20419. _this._applyFog = true;
  20420. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20421. _this.useOctreeForRenderingSelection = true;
  20422. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20423. _this.useOctreeForPicking = true;
  20424. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20425. _this.useOctreeForCollisions = true;
  20426. _this._layerMask = 0x0FFFFFFF;
  20427. /**
  20428. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20429. */
  20430. _this.alwaysSelectAsActiveMesh = false;
  20431. /**
  20432. * Gets or sets the current action manager
  20433. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20434. */
  20435. _this.actionManager = null;
  20436. // Collisions
  20437. _this._checkCollisions = false;
  20438. _this._collisionMask = -1;
  20439. _this._collisionGroup = -1;
  20440. /**
  20441. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20442. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20443. */
  20444. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20445. /**
  20446. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20447. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20448. */
  20449. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20450. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20451. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20452. // Edges
  20453. /**
  20454. * Defines edge width used when edgesRenderer is enabled
  20455. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20456. */
  20457. _this.edgesWidth = 1;
  20458. /**
  20459. * Defines edge color used when edgesRenderer is enabled
  20460. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20461. */
  20462. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20463. // Cache
  20464. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  20465. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  20466. /** @hidden */
  20467. _this._renderId = 0;
  20468. /** @hidden */
  20469. _this._intersectionsInProgress = new Array();
  20470. /** @hidden */
  20471. _this._unIndexed = false;
  20472. /** @hidden */
  20473. _this._lightSources = new Array();
  20474. /**
  20475. * An event triggered when the mesh is rebuilt.
  20476. */
  20477. _this.onRebuildObservable = new BABYLON.Observable();
  20478. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20479. if (collidedMesh === void 0) { collidedMesh = null; }
  20480. //TODO move this to the collision coordinator!
  20481. if (_this.getScene().workerCollisions)
  20482. newPosition.multiplyInPlace(_this._collider._radius);
  20483. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20484. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20485. _this.position.addInPlace(_this._diffPositionForCollisions);
  20486. }
  20487. if (collidedMesh) {
  20488. _this.onCollideObservable.notifyObservers(collidedMesh);
  20489. }
  20490. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20491. };
  20492. _this.getScene().addMesh(_this);
  20493. _this._resyncLightSources();
  20494. return _this;
  20495. }
  20496. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20497. /**
  20498. * No billboard
  20499. */
  20500. get: function () {
  20501. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20502. },
  20503. enumerable: true,
  20504. configurable: true
  20505. });
  20506. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20507. /** Billboard on X axis */
  20508. get: function () {
  20509. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20510. },
  20511. enumerable: true,
  20512. configurable: true
  20513. });
  20514. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20515. /** Billboard on Y axis */
  20516. get: function () {
  20517. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20518. },
  20519. enumerable: true,
  20520. configurable: true
  20521. });
  20522. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20523. /** Billboard on Z axis */
  20524. get: function () {
  20525. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20526. },
  20527. enumerable: true,
  20528. configurable: true
  20529. });
  20530. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20531. /** Billboard on all axes */
  20532. get: function () {
  20533. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20534. },
  20535. enumerable: true,
  20536. configurable: true
  20537. });
  20538. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20539. /**
  20540. * Gets the number of facets in the mesh
  20541. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20542. */
  20543. get: function () {
  20544. return this._facetData.facetNb;
  20545. },
  20546. enumerable: true,
  20547. configurable: true
  20548. });
  20549. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20550. /**
  20551. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20552. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20553. */
  20554. get: function () {
  20555. return this._facetData.partitioningSubdivisions;
  20556. },
  20557. set: function (nb) {
  20558. this._facetData.partitioningSubdivisions = nb;
  20559. },
  20560. enumerable: true,
  20561. configurable: true
  20562. });
  20563. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20564. /**
  20565. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20566. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20567. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20568. */
  20569. get: function () {
  20570. return this._facetData.partitioningBBoxRatio;
  20571. },
  20572. set: function (ratio) {
  20573. this._facetData.partitioningBBoxRatio = ratio;
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20579. /**
  20580. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20581. * Works only for updatable meshes.
  20582. * Doesn't work with multi-materials
  20583. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20584. */
  20585. get: function () {
  20586. return this._facetData.facetDepthSort;
  20587. },
  20588. set: function (sort) {
  20589. this._facetData.facetDepthSort = sort;
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20595. /**
  20596. * The location (Vector3) where the facet depth sort must be computed from.
  20597. * By default, the active camera position.
  20598. * Used only when facet depth sort is enabled
  20599. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20600. */
  20601. get: function () {
  20602. return this._facetData.facetDepthSortFrom;
  20603. },
  20604. set: function (location) {
  20605. this._facetData.facetDepthSortFrom = location;
  20606. },
  20607. enumerable: true,
  20608. configurable: true
  20609. });
  20610. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20611. /**
  20612. * gets a boolean indicating if facetData is enabled
  20613. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20614. */
  20615. get: function () {
  20616. return this._facetData.facetDataEnabled;
  20617. },
  20618. enumerable: true,
  20619. configurable: true
  20620. });
  20621. /** @hidden */
  20622. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20623. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20624. return false;
  20625. }
  20626. this._markSubMeshesAsMiscDirty();
  20627. return true;
  20628. };
  20629. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20630. /** Set a function to call when this mesh collides with another one */
  20631. set: function (callback) {
  20632. if (this._onCollideObserver) {
  20633. this.onCollideObservable.remove(this._onCollideObserver);
  20634. }
  20635. this._onCollideObserver = this.onCollideObservable.add(callback);
  20636. },
  20637. enumerable: true,
  20638. configurable: true
  20639. });
  20640. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20641. /** Set a function to call when the collision's position changes */
  20642. set: function (callback) {
  20643. if (this._onCollisionPositionChangeObserver) {
  20644. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20645. }
  20646. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20647. },
  20648. enumerable: true,
  20649. configurable: true
  20650. });
  20651. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20652. /**
  20653. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20654. */
  20655. get: function () {
  20656. return this._visibility;
  20657. },
  20658. /**
  20659. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20660. */
  20661. set: function (value) {
  20662. if (this._visibility === value) {
  20663. return;
  20664. }
  20665. this._visibility = value;
  20666. this._markSubMeshesAsMiscDirty();
  20667. },
  20668. enumerable: true,
  20669. configurable: true
  20670. });
  20671. Object.defineProperty(AbstractMesh.prototype, "material", {
  20672. /** Gets or sets current material */
  20673. get: function () {
  20674. return this._material;
  20675. },
  20676. set: function (value) {
  20677. if (this._material === value) {
  20678. return;
  20679. }
  20680. this._material = value;
  20681. if (this.onMaterialChangedObservable.hasObservers) {
  20682. this.onMaterialChangedObservable.notifyObservers(this);
  20683. }
  20684. if (!this.subMeshes) {
  20685. return;
  20686. }
  20687. this._unBindEffect();
  20688. },
  20689. enumerable: true,
  20690. configurable: true
  20691. });
  20692. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20693. /**
  20694. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20695. * @see http://doc.babylonjs.com/babylon101/shadows
  20696. */
  20697. get: function () {
  20698. return this._receiveShadows;
  20699. },
  20700. set: function (value) {
  20701. if (this._receiveShadows === value) {
  20702. return;
  20703. }
  20704. this._receiveShadows = value;
  20705. this._markSubMeshesAsLightDirty();
  20706. },
  20707. enumerable: true,
  20708. configurable: true
  20709. });
  20710. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20711. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20712. get: function () {
  20713. return this._hasVertexAlpha;
  20714. },
  20715. set: function (value) {
  20716. if (this._hasVertexAlpha === value) {
  20717. return;
  20718. }
  20719. this._hasVertexAlpha = value;
  20720. this._markSubMeshesAsAttributesDirty();
  20721. this._markSubMeshesAsMiscDirty();
  20722. },
  20723. enumerable: true,
  20724. configurable: true
  20725. });
  20726. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20727. /** 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) */
  20728. get: function () {
  20729. return this._useVertexColors;
  20730. },
  20731. set: function (value) {
  20732. if (this._useVertexColors === value) {
  20733. return;
  20734. }
  20735. this._useVertexColors = value;
  20736. this._markSubMeshesAsAttributesDirty();
  20737. },
  20738. enumerable: true,
  20739. configurable: true
  20740. });
  20741. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20742. /**
  20743. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20744. */
  20745. get: function () {
  20746. return this._computeBonesUsingShaders;
  20747. },
  20748. set: function (value) {
  20749. if (this._computeBonesUsingShaders === value) {
  20750. return;
  20751. }
  20752. this._computeBonesUsingShaders = value;
  20753. this._markSubMeshesAsAttributesDirty();
  20754. },
  20755. enumerable: true,
  20756. configurable: true
  20757. });
  20758. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20759. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20760. get: function () {
  20761. return this._numBoneInfluencers;
  20762. },
  20763. set: function (value) {
  20764. if (this._numBoneInfluencers === value) {
  20765. return;
  20766. }
  20767. this._numBoneInfluencers = value;
  20768. this._markSubMeshesAsAttributesDirty();
  20769. },
  20770. enumerable: true,
  20771. configurable: true
  20772. });
  20773. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20774. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20775. get: function () {
  20776. return this._applyFog;
  20777. },
  20778. set: function (value) {
  20779. if (this._applyFog === value) {
  20780. return;
  20781. }
  20782. this._applyFog = value;
  20783. this._markSubMeshesAsMiscDirty();
  20784. },
  20785. enumerable: true,
  20786. configurable: true
  20787. });
  20788. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20789. /**
  20790. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20791. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20792. */
  20793. get: function () {
  20794. return this._layerMask;
  20795. },
  20796. set: function (value) {
  20797. if (value === this._layerMask) {
  20798. return;
  20799. }
  20800. this._layerMask = value;
  20801. this._resyncLightSources();
  20802. },
  20803. enumerable: true,
  20804. configurable: true
  20805. });
  20806. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20807. /**
  20808. * Gets or sets a collision mask used to mask collisions (default is -1).
  20809. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20810. */
  20811. get: function () {
  20812. return this._collisionMask;
  20813. },
  20814. set: function (mask) {
  20815. this._collisionMask = !isNaN(mask) ? mask : -1;
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20821. /**
  20822. * Gets or sets the current collision group mask (-1 by default).
  20823. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20824. */
  20825. get: function () {
  20826. return this._collisionGroup;
  20827. },
  20828. set: function (mask) {
  20829. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20830. },
  20831. enumerable: true,
  20832. configurable: true
  20833. });
  20834. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20835. /** @hidden */
  20836. get: function () {
  20837. return null;
  20838. },
  20839. enumerable: true,
  20840. configurable: true
  20841. });
  20842. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20843. get: function () {
  20844. return this._skeleton;
  20845. },
  20846. /**
  20847. * Gets or sets a skeleton to apply skining transformations
  20848. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20849. */
  20850. set: function (value) {
  20851. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20852. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20853. }
  20854. if (value && value.needInitialSkinMatrix) {
  20855. value._registerMeshWithPoseMatrix(this);
  20856. }
  20857. this._skeleton = value;
  20858. if (!this._skeleton) {
  20859. this._bonesTransformMatrices = null;
  20860. }
  20861. this._markSubMeshesAsAttributesDirty();
  20862. },
  20863. enumerable: true,
  20864. configurable: true
  20865. });
  20866. /**
  20867. * Returns the string "AbstractMesh"
  20868. * @returns "AbstractMesh"
  20869. */
  20870. AbstractMesh.prototype.getClassName = function () {
  20871. return "AbstractMesh";
  20872. };
  20873. /**
  20874. * Gets a string representation of the current mesh
  20875. * @param fullDetails defines a boolean indicating if full details must be included
  20876. * @returns a string representation of the current mesh
  20877. */
  20878. AbstractMesh.prototype.toString = function (fullDetails) {
  20879. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20880. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20881. if (this._skeleton) {
  20882. ret += ", skeleton: " + this._skeleton.name;
  20883. }
  20884. if (fullDetails) {
  20885. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20886. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20887. }
  20888. return ret;
  20889. };
  20890. /** @hidden */
  20891. AbstractMesh.prototype._rebuild = function () {
  20892. this.onRebuildObservable.notifyObservers(this);
  20893. if (this._occlusionQuery) {
  20894. this._occlusionQuery = null;
  20895. }
  20896. if (!this.subMeshes) {
  20897. return;
  20898. }
  20899. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20900. var subMesh = _a[_i];
  20901. subMesh._rebuild();
  20902. }
  20903. };
  20904. /** @hidden */
  20905. AbstractMesh.prototype._resyncLightSources = function () {
  20906. this._lightSources.length = 0;
  20907. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20908. var light = _a[_i];
  20909. if (!light.isEnabled()) {
  20910. continue;
  20911. }
  20912. if (light.canAffectMesh(this)) {
  20913. this._lightSources.push(light);
  20914. }
  20915. }
  20916. this._markSubMeshesAsLightDirty();
  20917. };
  20918. /** @hidden */
  20919. AbstractMesh.prototype._resyncLighSource = function (light) {
  20920. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20921. var index = this._lightSources.indexOf(light);
  20922. if (index === -1) {
  20923. if (!isIn) {
  20924. return;
  20925. }
  20926. this._lightSources.push(light);
  20927. }
  20928. else {
  20929. if (isIn) {
  20930. return;
  20931. }
  20932. this._lightSources.splice(index, 1);
  20933. }
  20934. this._markSubMeshesAsLightDirty();
  20935. };
  20936. /** @hidden */
  20937. AbstractMesh.prototype._unBindEffect = function () {
  20938. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20939. var subMesh = _a[_i];
  20940. subMesh.setEffect(null);
  20941. }
  20942. };
  20943. /** @hidden */
  20944. AbstractMesh.prototype._removeLightSource = function (light) {
  20945. var index = this._lightSources.indexOf(light);
  20946. if (index === -1) {
  20947. return;
  20948. }
  20949. this._lightSources.splice(index, 1);
  20950. this._markSubMeshesAsLightDirty();
  20951. };
  20952. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20953. if (!this.subMeshes) {
  20954. return;
  20955. }
  20956. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20957. var subMesh = _a[_i];
  20958. if (subMesh._materialDefines) {
  20959. func(subMesh._materialDefines);
  20960. }
  20961. }
  20962. };
  20963. /** @hidden */
  20964. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20965. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20966. };
  20967. /** @hidden */
  20968. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20969. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20970. };
  20971. /** @hidden */
  20972. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20973. if (!this.subMeshes) {
  20974. return;
  20975. }
  20976. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20977. var subMesh = _a[_i];
  20978. var material = subMesh.getMaterial();
  20979. if (material) {
  20980. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20981. }
  20982. }
  20983. };
  20984. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20985. /**
  20986. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20987. */
  20988. get: function () {
  20989. return this._scaling;
  20990. },
  20991. set: function (newScaling) {
  20992. this._scaling = newScaling;
  20993. if (this.physicsImpostor) {
  20994. this.physicsImpostor.forceUpdate();
  20995. }
  20996. },
  20997. enumerable: true,
  20998. configurable: true
  20999. });
  21000. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21001. // Methods
  21002. /**
  21003. * Returns true if the mesh is blocked. Implemented by child classes
  21004. */
  21005. get: function () {
  21006. return false;
  21007. },
  21008. enumerable: true,
  21009. configurable: true
  21010. });
  21011. /**
  21012. * Returns the mesh itself by default. Implemented by child classes
  21013. * @param camera defines the camera to use to pick the right LOD level
  21014. * @returns the currentAbstractMesh
  21015. */
  21016. AbstractMesh.prototype.getLOD = function (camera) {
  21017. return this;
  21018. };
  21019. /**
  21020. * Returns 0 by default. Implemented by child classes
  21021. * @returns an integer
  21022. */
  21023. AbstractMesh.prototype.getTotalVertices = function () {
  21024. return 0;
  21025. };
  21026. /**
  21027. * Returns null by default. Implemented by child classes
  21028. * @returns null
  21029. */
  21030. AbstractMesh.prototype.getIndices = function () {
  21031. return null;
  21032. };
  21033. /**
  21034. * Returns the array of the requested vertex data kind. Implemented by child classes
  21035. * @param kind defines the vertex data kind to use
  21036. * @returns null
  21037. */
  21038. AbstractMesh.prototype.getVerticesData = function (kind) {
  21039. return null;
  21040. };
  21041. /**
  21042. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21043. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21044. * Note that a new underlying VertexBuffer object is created each call.
  21045. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21046. * @param kind defines vertex data kind:
  21047. * * BABYLON.VertexBuffer.PositionKind
  21048. * * BABYLON.VertexBuffer.UVKind
  21049. * * BABYLON.VertexBuffer.UV2Kind
  21050. * * BABYLON.VertexBuffer.UV3Kind
  21051. * * BABYLON.VertexBuffer.UV4Kind
  21052. * * BABYLON.VertexBuffer.UV5Kind
  21053. * * BABYLON.VertexBuffer.UV6Kind
  21054. * * BABYLON.VertexBuffer.ColorKind
  21055. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21056. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21057. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21058. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21059. * @param data defines the data source
  21060. * @param updatable defines if the data must be flagged as updatable (or static)
  21061. * @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
  21062. * @returns the current mesh
  21063. */
  21064. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21065. return this;
  21066. };
  21067. /**
  21068. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21069. * If the mesh has no geometry, it is simply returned as it is.
  21070. * @param kind defines vertex data kind:
  21071. * * BABYLON.VertexBuffer.PositionKind
  21072. * * BABYLON.VertexBuffer.UVKind
  21073. * * BABYLON.VertexBuffer.UV2Kind
  21074. * * BABYLON.VertexBuffer.UV3Kind
  21075. * * BABYLON.VertexBuffer.UV4Kind
  21076. * * BABYLON.VertexBuffer.UV5Kind
  21077. * * BABYLON.VertexBuffer.UV6Kind
  21078. * * BABYLON.VertexBuffer.ColorKind
  21079. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21080. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21081. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21082. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21083. * @param data defines the data source
  21084. * @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
  21085. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21086. * @returns the current mesh
  21087. */
  21088. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21089. return this;
  21090. };
  21091. /**
  21092. * Sets the mesh indices,
  21093. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21094. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21095. * @param totalVertices Defines the total number of vertices
  21096. * @returns the current mesh
  21097. */
  21098. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21099. return this;
  21100. };
  21101. /**
  21102. * Gets a boolean indicating if specific vertex data is present
  21103. * @param kind defines the vertex data kind to use
  21104. * @returns true is data kind is present
  21105. */
  21106. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21107. return false;
  21108. };
  21109. /**
  21110. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21111. * @returns a BoundingInfo
  21112. */
  21113. AbstractMesh.prototype.getBoundingInfo = function () {
  21114. if (this._masterMesh) {
  21115. return this._masterMesh.getBoundingInfo();
  21116. }
  21117. if (!this._boundingInfo) {
  21118. // this._boundingInfo is being created here
  21119. this._updateBoundingInfo();
  21120. }
  21121. // cannot be null.
  21122. return this._boundingInfo;
  21123. };
  21124. /**
  21125. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21126. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21127. * @returns the current mesh
  21128. */
  21129. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21130. if (includeDescendants === void 0) { includeDescendants = true; }
  21131. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21132. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21133. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21134. if (maxDimension === 0) {
  21135. return this;
  21136. }
  21137. var scale = 1 / maxDimension;
  21138. this.scaling.scaleInPlace(scale);
  21139. return this;
  21140. };
  21141. /**
  21142. * Overwrite the current bounding info
  21143. * @param boundingInfo defines the new bounding info
  21144. * @returns the current mesh
  21145. */
  21146. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21147. this._boundingInfo = boundingInfo;
  21148. return this;
  21149. };
  21150. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21151. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21152. get: function () {
  21153. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21154. },
  21155. enumerable: true,
  21156. configurable: true
  21157. });
  21158. /** @hidden */
  21159. AbstractMesh.prototype._preActivate = function () {
  21160. };
  21161. /** @hidden */
  21162. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21163. };
  21164. /** @hidden */
  21165. AbstractMesh.prototype._activate = function (renderId) {
  21166. this._renderId = renderId;
  21167. };
  21168. /**
  21169. * Gets the current world matrix
  21170. * @returns a Matrix
  21171. */
  21172. AbstractMesh.prototype.getWorldMatrix = function () {
  21173. if (this._masterMesh) {
  21174. return this._masterMesh.getWorldMatrix();
  21175. }
  21176. return _super.prototype.getWorldMatrix.call(this);
  21177. };
  21178. /** @hidden */
  21179. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21180. if (this._masterMesh) {
  21181. return this._masterMesh._getWorldMatrixDeterminant();
  21182. }
  21183. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21184. };
  21185. // ================================== Point of View Movement =================================
  21186. /**
  21187. * Perform relative position change from the point of view of behind the front of the mesh.
  21188. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21189. * Supports definition of mesh facing forward or backward
  21190. * @param amountRight defines the distance on the right axis
  21191. * @param amountUp defines the distance on the up axis
  21192. * @param amountForward defines the distance on the forward axis
  21193. * @returns the current mesh
  21194. */
  21195. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21196. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21197. return this;
  21198. };
  21199. /**
  21200. * Calculate relative position change from the point of view of behind the front of the mesh.
  21201. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21202. * Supports definition of mesh facing forward or backward
  21203. * @param amountRight defines the distance on the right axis
  21204. * @param amountUp defines the distance on the up axis
  21205. * @param amountForward defines the distance on the forward axis
  21206. * @returns the new displacement vector
  21207. */
  21208. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21209. var rotMatrix = new BABYLON.Matrix();
  21210. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21211. rotQuaternion.toRotationMatrix(rotMatrix);
  21212. var translationDelta = BABYLON.Vector3.Zero();
  21213. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21214. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21215. return translationDelta;
  21216. };
  21217. // ================================== Point of View Rotation =================================
  21218. /**
  21219. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21220. * Supports definition of mesh facing forward or backward
  21221. * @param flipBack defines the flip
  21222. * @param twirlClockwise defines the twirl
  21223. * @param tiltRight defines the tilt
  21224. * @returns the current mesh
  21225. */
  21226. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21227. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21228. return this;
  21229. };
  21230. /**
  21231. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21232. * Supports definition of mesh facing forward or backward.
  21233. * @param flipBack defines the flip
  21234. * @param twirlClockwise defines the twirl
  21235. * @param tiltRight defines the tilt
  21236. * @returns the new rotation vector
  21237. */
  21238. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21239. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21240. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21241. };
  21242. /**
  21243. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21244. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21245. * @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
  21246. * @returns the new bounding vectors
  21247. */
  21248. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21249. if (includeDescendants === void 0) { includeDescendants = true; }
  21250. if (predicate === void 0) { predicate = null; }
  21251. // Ensures that all world matrix will be recomputed.
  21252. this.getScene().incrementRenderId();
  21253. this.computeWorldMatrix(true);
  21254. var min;
  21255. var max;
  21256. var boundingInfo = this.getBoundingInfo();
  21257. if (!this.subMeshes) {
  21258. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21259. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21260. }
  21261. else {
  21262. min = boundingInfo.boundingBox.minimumWorld;
  21263. max = boundingInfo.boundingBox.maximumWorld;
  21264. }
  21265. if (includeDescendants) {
  21266. var descendants = this.getDescendants(false);
  21267. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21268. var descendant = descendants_1[_i];
  21269. var childMesh = descendant;
  21270. childMesh.computeWorldMatrix(true);
  21271. // Filters meshes based on custom predicate function.
  21272. if (predicate && !predicate(childMesh)) {
  21273. continue;
  21274. }
  21275. //make sure we have the needed params to get mix and max
  21276. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21277. continue;
  21278. }
  21279. var childBoundingInfo = childMesh.getBoundingInfo();
  21280. var boundingBox = childBoundingInfo.boundingBox;
  21281. var minBox = boundingBox.minimumWorld;
  21282. var maxBox = boundingBox.maximumWorld;
  21283. BABYLON.Tools.CheckExtends(minBox, min, max);
  21284. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21285. }
  21286. }
  21287. return {
  21288. min: min,
  21289. max: max
  21290. };
  21291. };
  21292. /** @hidden */
  21293. AbstractMesh.prototype._updateBoundingInfo = function () {
  21294. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21295. this._boundingInfo.update(this.worldMatrixFromCache);
  21296. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21297. return this;
  21298. };
  21299. /** @hidden */
  21300. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21301. if (!this.subMeshes) {
  21302. return this;
  21303. }
  21304. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21305. var subMesh = this.subMeshes[subIndex];
  21306. if (!subMesh.IsGlobal) {
  21307. subMesh.updateBoundingInfo(matrix);
  21308. }
  21309. }
  21310. return this;
  21311. };
  21312. /** @hidden */
  21313. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21314. // Bounding info
  21315. this._updateBoundingInfo();
  21316. };
  21317. /**
  21318. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21319. * A mesh is in the frustum if its bounding box intersects the frustum
  21320. * @param frustumPlanes defines the frustum to test
  21321. * @returns true if the mesh is in the frustum planes
  21322. */
  21323. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21324. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21325. };
  21326. /**
  21327. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21328. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21329. * @param frustumPlanes defines the frustum to test
  21330. * @returns true if the mesh is completely in the frustum planes
  21331. */
  21332. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21333. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21334. };
  21335. /**
  21336. * True if the mesh intersects another mesh or a SolidParticle object
  21337. * @param mesh defines a target mesh or SolidParticle to test
  21338. * @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)
  21339. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21340. * @returns true if there is an intersection
  21341. */
  21342. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21343. if (precise === void 0) { precise = false; }
  21344. if (!this._boundingInfo || !mesh._boundingInfo) {
  21345. return false;
  21346. }
  21347. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21348. return true;
  21349. }
  21350. if (includeDescendants) {
  21351. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21352. var child = _a[_i];
  21353. if (child.intersectsMesh(mesh, precise, true)) {
  21354. return true;
  21355. }
  21356. }
  21357. }
  21358. return false;
  21359. };
  21360. /**
  21361. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21362. * @param point defines the point to test
  21363. * @returns true if there is an intersection
  21364. */
  21365. AbstractMesh.prototype.intersectsPoint = function (point) {
  21366. if (!this._boundingInfo) {
  21367. return false;
  21368. }
  21369. return this._boundingInfo.intersectsPoint(point);
  21370. };
  21371. /**
  21372. * Gets the position of the current mesh in camera space
  21373. * @param camera defines the camera to use
  21374. * @returns a position
  21375. */
  21376. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21377. if (camera === void 0) { camera = null; }
  21378. if (!camera) {
  21379. camera = this.getScene().activeCamera;
  21380. }
  21381. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21382. };
  21383. /**
  21384. * Returns the distance from the mesh to the active camera
  21385. * @param camera defines the camera to use
  21386. * @returns the distance
  21387. */
  21388. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21389. if (camera === void 0) { camera = null; }
  21390. if (!camera) {
  21391. camera = this.getScene().activeCamera;
  21392. }
  21393. return this.absolutePosition.subtract(camera.position).length();
  21394. };
  21395. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21396. // Collisions
  21397. /**
  21398. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21399. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21400. */
  21401. get: function () {
  21402. return this._checkCollisions;
  21403. },
  21404. set: function (collisionEnabled) {
  21405. this._checkCollisions = collisionEnabled;
  21406. if (this.getScene().workerCollisions) {
  21407. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21408. }
  21409. },
  21410. enumerable: true,
  21411. configurable: true
  21412. });
  21413. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21414. /**
  21415. * Gets Collider object used to compute collisions (not physics)
  21416. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21417. */
  21418. get: function () {
  21419. return this._collider;
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. /**
  21425. * Move the mesh using collision engine
  21426. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21427. * @param displacement defines the requested displacement vector
  21428. * @returns the current mesh
  21429. */
  21430. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21431. var globalPosition = this.getAbsolutePosition();
  21432. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21433. if (!this._collider) {
  21434. this._collider = new BABYLON.Collider();
  21435. }
  21436. this._collider._radius = this.ellipsoid;
  21437. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21438. return this;
  21439. };
  21440. // Collisions
  21441. /** @hidden */
  21442. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21443. this._generatePointsArray();
  21444. if (!this._positions) {
  21445. return this;
  21446. }
  21447. // Transformation
  21448. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21449. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21450. subMesh._lastColliderWorldVertices = [];
  21451. subMesh._trianglePlanes = [];
  21452. var start = subMesh.verticesStart;
  21453. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21454. for (var i = start; i < end; i++) {
  21455. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21456. }
  21457. }
  21458. // Collide
  21459. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21460. if (collider.collisionFound) {
  21461. collider.collidedMesh = this;
  21462. }
  21463. return this;
  21464. };
  21465. /** @hidden */
  21466. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21467. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21468. var len = subMeshes.length;
  21469. for (var index = 0; index < len; index++) {
  21470. var subMesh = subMeshes.data[index];
  21471. // Bounding test
  21472. if (len > 1 && !subMesh._checkCollision(collider))
  21473. continue;
  21474. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21475. }
  21476. return this;
  21477. };
  21478. /** @hidden */
  21479. AbstractMesh.prototype._checkCollision = function (collider) {
  21480. // Bounding box test
  21481. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21482. return this;
  21483. // Transformation matrix
  21484. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21485. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21486. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21487. return this;
  21488. };
  21489. // Picking
  21490. /** @hidden */
  21491. AbstractMesh.prototype._generatePointsArray = function () {
  21492. return false;
  21493. };
  21494. /**
  21495. * Checks if the passed Ray intersects with the mesh
  21496. * @param ray defines the ray to use
  21497. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21498. * @returns the picking info
  21499. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21500. */
  21501. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21502. var pickingInfo = new BABYLON.PickingInfo();
  21503. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21504. return pickingInfo;
  21505. }
  21506. if (!this._generatePointsArray()) {
  21507. return pickingInfo;
  21508. }
  21509. var intersectInfo = null;
  21510. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21511. var len = subMeshes.length;
  21512. for (var index = 0; index < len; index++) {
  21513. var subMesh = subMeshes.data[index];
  21514. // Bounding test
  21515. if (len > 1 && !subMesh.canIntersects(ray))
  21516. continue;
  21517. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21518. if (currentIntersectInfo) {
  21519. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21520. intersectInfo = currentIntersectInfo;
  21521. intersectInfo.subMeshId = index;
  21522. if (fastCheck) {
  21523. break;
  21524. }
  21525. }
  21526. }
  21527. }
  21528. if (intersectInfo) {
  21529. // Get picked point
  21530. var world = this.getWorldMatrix();
  21531. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21532. var direction = ray.direction.clone();
  21533. direction = direction.scale(intersectInfo.distance);
  21534. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21535. var pickedPoint = worldOrigin.add(worldDirection);
  21536. // Return result
  21537. pickingInfo.hit = true;
  21538. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21539. pickingInfo.pickedPoint = pickedPoint;
  21540. pickingInfo.pickedMesh = this;
  21541. pickingInfo.bu = intersectInfo.bu || 0;
  21542. pickingInfo.bv = intersectInfo.bv || 0;
  21543. pickingInfo.faceId = intersectInfo.faceId;
  21544. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21545. return pickingInfo;
  21546. }
  21547. return pickingInfo;
  21548. };
  21549. /**
  21550. * Clones the current mesh
  21551. * @param name defines the mesh name
  21552. * @param newParent defines the new mesh parent
  21553. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21554. * @returns the new mesh
  21555. */
  21556. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21557. return null;
  21558. };
  21559. /**
  21560. * Disposes all the submeshes of the current meshnp
  21561. * @returns the current mesh
  21562. */
  21563. AbstractMesh.prototype.releaseSubMeshes = function () {
  21564. if (this.subMeshes) {
  21565. while (this.subMeshes.length) {
  21566. this.subMeshes[0].dispose();
  21567. }
  21568. }
  21569. else {
  21570. this.subMeshes = new Array();
  21571. }
  21572. return this;
  21573. };
  21574. /**
  21575. * Releases resources associated with this abstract mesh.
  21576. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21577. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21578. */
  21579. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21580. var _this = this;
  21581. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21582. var index;
  21583. // Smart Array Retainers.
  21584. this.getScene().freeActiveMeshes();
  21585. this.getScene().freeRenderingGroups();
  21586. // Action manager
  21587. if (this.actionManager !== undefined && this.actionManager !== null) {
  21588. this.actionManager.dispose();
  21589. this.actionManager = null;
  21590. }
  21591. // Skeleton
  21592. this._skeleton = null;
  21593. // Intersections in progress
  21594. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21595. var other = this._intersectionsInProgress[index];
  21596. var pos = other._intersectionsInProgress.indexOf(this);
  21597. other._intersectionsInProgress.splice(pos, 1);
  21598. }
  21599. this._intersectionsInProgress = [];
  21600. // Lights
  21601. var lights = this.getScene().lights;
  21602. lights.forEach(function (light) {
  21603. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21604. if (meshIndex !== -1) {
  21605. light.includedOnlyMeshes.splice(meshIndex, 1);
  21606. }
  21607. meshIndex = light.excludedMeshes.indexOf(_this);
  21608. if (meshIndex !== -1) {
  21609. light.excludedMeshes.splice(meshIndex, 1);
  21610. }
  21611. // Shadow generators
  21612. var generator = light.getShadowGenerator();
  21613. if (generator) {
  21614. var shadowMap = generator.getShadowMap();
  21615. if (shadowMap && shadowMap.renderList) {
  21616. meshIndex = shadowMap.renderList.indexOf(_this);
  21617. if (meshIndex !== -1) {
  21618. shadowMap.renderList.splice(meshIndex, 1);
  21619. }
  21620. }
  21621. }
  21622. });
  21623. // SubMeshes
  21624. if (this.getClassName() !== "InstancedMesh") {
  21625. this.releaseSubMeshes();
  21626. }
  21627. // Query
  21628. var engine = this.getScene().getEngine();
  21629. if (this._occlusionQuery) {
  21630. this.isOcclusionQueryInProgress = false;
  21631. engine.deleteQuery(this._occlusionQuery);
  21632. this._occlusionQuery = null;
  21633. }
  21634. // Engine
  21635. engine.wipeCaches();
  21636. // Remove from scene
  21637. this.getScene().removeMesh(this);
  21638. if (disposeMaterialAndTextures) {
  21639. if (this.material) {
  21640. this.material.dispose(false, true);
  21641. }
  21642. }
  21643. if (!doNotRecurse) {
  21644. // Particles
  21645. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21646. if (this.getScene().particleSystems[index].emitter === this) {
  21647. this.getScene().particleSystems[index].dispose();
  21648. index--;
  21649. }
  21650. }
  21651. }
  21652. // facet data
  21653. if (this._facetData.facetDataEnabled) {
  21654. this.disableFacetData();
  21655. }
  21656. this.onAfterWorldMatrixUpdateObservable.clear();
  21657. this.onCollideObservable.clear();
  21658. this.onCollisionPositionChangeObservable.clear();
  21659. this.onRebuildObservable.clear();
  21660. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21661. };
  21662. /**
  21663. * Adds the passed mesh as a child to the current mesh
  21664. * @param mesh defines the child mesh
  21665. * @returns the current mesh
  21666. */
  21667. AbstractMesh.prototype.addChild = function (mesh) {
  21668. mesh.setParent(this);
  21669. return this;
  21670. };
  21671. /**
  21672. * Removes the passed mesh from the current mesh children list
  21673. * @param mesh defines the child mesh
  21674. * @returns the current mesh
  21675. */
  21676. AbstractMesh.prototype.removeChild = function (mesh) {
  21677. mesh.setParent(null);
  21678. return this;
  21679. };
  21680. // Facet data
  21681. /** @hidden */
  21682. AbstractMesh.prototype._initFacetData = function () {
  21683. var data = this._facetData;
  21684. if (!data.facetNormals) {
  21685. data.facetNormals = new Array();
  21686. }
  21687. if (!data.facetPositions) {
  21688. data.facetPositions = new Array();
  21689. }
  21690. if (!data.facetPartitioning) {
  21691. data.facetPartitioning = new Array();
  21692. }
  21693. data.facetNb = (this.getIndices().length / 3) | 0;
  21694. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21695. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21696. for (var f = 0; f < data.facetNb; f++) {
  21697. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21698. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21699. }
  21700. data.facetDataEnabled = true;
  21701. return this;
  21702. };
  21703. /**
  21704. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21705. * This method can be called within the render loop.
  21706. * 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
  21707. * @returns the current mesh
  21708. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21709. */
  21710. AbstractMesh.prototype.updateFacetData = function () {
  21711. var data = this._facetData;
  21712. if (!data.facetDataEnabled) {
  21713. this._initFacetData();
  21714. }
  21715. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21716. var indices = this.getIndices();
  21717. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21718. var bInfo = this.getBoundingInfo();
  21719. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21720. // init arrays, matrix and sort function on first call
  21721. data.facetDepthSortEnabled = true;
  21722. if (indices instanceof Uint16Array) {
  21723. data.depthSortedIndices = new Uint16Array(indices);
  21724. }
  21725. else if (indices instanceof Uint32Array) {
  21726. data.depthSortedIndices = new Uint32Array(indices);
  21727. }
  21728. else {
  21729. var needs32bits = false;
  21730. for (var i = 0; i < indices.length; i++) {
  21731. if (indices[i] > 65535) {
  21732. needs32bits = true;
  21733. break;
  21734. }
  21735. }
  21736. if (needs32bits) {
  21737. data.depthSortedIndices = new Uint32Array(indices);
  21738. }
  21739. else {
  21740. data.depthSortedIndices = new Uint16Array(indices);
  21741. }
  21742. }
  21743. data.facetDepthSortFunction = function (f1, f2) {
  21744. return (f2.sqDistance - f1.sqDistance);
  21745. };
  21746. if (!data.facetDepthSortFrom) {
  21747. var camera = this.getScene().activeCamera;
  21748. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21749. }
  21750. data.depthSortedFacets = [];
  21751. for (var f = 0; f < data.facetNb; f++) {
  21752. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21753. data.depthSortedFacets.push(depthSortedFacet);
  21754. }
  21755. data.invertedMatrix = BABYLON.Matrix.Identity();
  21756. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21757. }
  21758. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21759. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21760. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21761. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21762. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21763. data.subDiv.max = data.partitioningSubdivisions;
  21764. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21765. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21766. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21767. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21768. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21769. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21770. // set the parameters for ComputeNormals()
  21771. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21772. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21773. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21774. data.facetParameters.bInfo = bInfo;
  21775. data.facetParameters.bbSize = data.bbSize;
  21776. data.facetParameters.subDiv = data.subDiv;
  21777. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21778. data.facetParameters.depthSort = data.facetDepthSort;
  21779. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21780. this.computeWorldMatrix(true);
  21781. this._worldMatrix.invertToRef(data.invertedMatrix);
  21782. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21783. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21784. }
  21785. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21786. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21787. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21788. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21789. var l = (data.depthSortedIndices.length / 3) | 0;
  21790. for (var f = 0; f < l; f++) {
  21791. var sind = data.depthSortedFacets[f].ind;
  21792. data.depthSortedIndices[f * 3] = indices[sind];
  21793. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21794. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21795. }
  21796. this.updateIndices(data.depthSortedIndices);
  21797. }
  21798. return this;
  21799. };
  21800. /**
  21801. * Returns the facetLocalNormals array.
  21802. * The normals are expressed in the mesh local spac
  21803. * @returns an array of Vector3
  21804. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21805. */
  21806. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21807. if (!this._facetData.facetNormals) {
  21808. this.updateFacetData();
  21809. }
  21810. return this._facetData.facetNormals;
  21811. };
  21812. /**
  21813. * Returns the facetLocalPositions array.
  21814. * The facet positions are expressed in the mesh local space
  21815. * @returns an array of Vector3
  21816. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21817. */
  21818. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21819. if (!this._facetData.facetPositions) {
  21820. this.updateFacetData();
  21821. }
  21822. return this._facetData.facetPositions;
  21823. };
  21824. /**
  21825. * Returns the facetLocalPartioning array
  21826. * @returns an array of array of numbers
  21827. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21828. */
  21829. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21830. if (!this._facetData.facetPartitioning) {
  21831. this.updateFacetData();
  21832. }
  21833. return this._facetData.facetPartitioning;
  21834. };
  21835. /**
  21836. * Returns the i-th facet position in the world system.
  21837. * This method allocates a new Vector3 per call
  21838. * @param i defines the facet index
  21839. * @returns a new Vector3
  21840. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21841. */
  21842. AbstractMesh.prototype.getFacetPosition = function (i) {
  21843. var pos = BABYLON.Vector3.Zero();
  21844. this.getFacetPositionToRef(i, pos);
  21845. return pos;
  21846. };
  21847. /**
  21848. * Sets the reference Vector3 with the i-th facet position in the world system
  21849. * @param i defines the facet index
  21850. * @param ref defines the target vector
  21851. * @returns the current mesh
  21852. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21853. */
  21854. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21855. var localPos = (this.getFacetLocalPositions())[i];
  21856. var world = this.getWorldMatrix();
  21857. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21858. return this;
  21859. };
  21860. /**
  21861. * Returns the i-th facet normal in the world system.
  21862. * This method allocates a new Vector3 per call
  21863. * @param i defines the facet index
  21864. * @returns a new Vector3
  21865. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21866. */
  21867. AbstractMesh.prototype.getFacetNormal = function (i) {
  21868. var norm = BABYLON.Vector3.Zero();
  21869. this.getFacetNormalToRef(i, norm);
  21870. return norm;
  21871. };
  21872. /**
  21873. * Sets the reference Vector3 with the i-th facet normal in the world system
  21874. * @param i defines the facet index
  21875. * @param ref defines the target vector
  21876. * @returns the current mesh
  21877. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21878. */
  21879. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21880. var localNorm = (this.getFacetLocalNormals())[i];
  21881. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21882. return this;
  21883. };
  21884. /**
  21885. * 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)
  21886. * @param x defines x coordinate
  21887. * @param y defines y coordinate
  21888. * @param z defines z coordinate
  21889. * @returns the array of facet indexes
  21890. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21891. */
  21892. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21893. var bInfo = this.getBoundingInfo();
  21894. var data = this._facetData;
  21895. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  21896. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  21897. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  21898. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  21899. return null;
  21900. }
  21901. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  21902. };
  21903. /**
  21904. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21905. * @param projected sets as the (x,y,z) world projection on the facet
  21906. * @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
  21907. * @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
  21908. * @param x defines x coordinate
  21909. * @param y defines y coordinate
  21910. * @param z defines z coordinate
  21911. * @returns the face index if found (or null instead)
  21912. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21913. */
  21914. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21915. if (checkFace === void 0) { checkFace = false; }
  21916. if (facing === void 0) { facing = true; }
  21917. var world = this.getWorldMatrix();
  21918. var invMat = BABYLON.Tmp.Matrix[5];
  21919. world.invertToRef(invMat);
  21920. var invVect = BABYLON.Tmp.Vector3[8];
  21921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21922. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21923. if (projected) {
  21924. // tranform the local computed projected vector to world coordinates
  21925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21926. }
  21927. return closest;
  21928. };
  21929. /**
  21930. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21931. * @param projected sets as the (x,y,z) local projection on the facet
  21932. * @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
  21933. * @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
  21934. * @param x defines x coordinate
  21935. * @param y defines y coordinate
  21936. * @param z defines z coordinate
  21937. * @returns the face index if found (or null instead)
  21938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21939. */
  21940. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21941. if (checkFace === void 0) { checkFace = false; }
  21942. if (facing === void 0) { facing = true; }
  21943. var closest = null;
  21944. var tmpx = 0.0;
  21945. var tmpy = 0.0;
  21946. var tmpz = 0.0;
  21947. var d = 0.0; // tmp dot facet normal * facet position
  21948. var t0 = 0.0;
  21949. var projx = 0.0;
  21950. var projy = 0.0;
  21951. var projz = 0.0;
  21952. // Get all the facets in the same partitioning block than (x, y, z)
  21953. var facetPositions = this.getFacetLocalPositions();
  21954. var facetNormals = this.getFacetLocalNormals();
  21955. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21956. if (!facetsInBlock) {
  21957. return null;
  21958. }
  21959. // Get the closest facet to (x, y, z)
  21960. var shortest = Number.MAX_VALUE; // init distance vars
  21961. var tmpDistance = shortest;
  21962. var fib; // current facet in the block
  21963. var norm; // current facet normal
  21964. var p0; // current facet barycenter position
  21965. // loop on all the facets in the current partitioning block
  21966. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21967. fib = facetsInBlock[idx];
  21968. norm = facetNormals[fib];
  21969. p0 = facetPositions[fib];
  21970. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21971. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21972. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21973. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21974. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21975. projx = x + norm.x * t0;
  21976. projy = y + norm.y * t0;
  21977. projz = z + norm.z * t0;
  21978. tmpx = projx - x;
  21979. tmpy = projy - y;
  21980. tmpz = projz - z;
  21981. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21982. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21983. shortest = tmpDistance;
  21984. closest = fib;
  21985. if (projected) {
  21986. projected.x = projx;
  21987. projected.y = projy;
  21988. projected.z = projz;
  21989. }
  21990. }
  21991. }
  21992. }
  21993. return closest;
  21994. };
  21995. /**
  21996. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21997. * @returns the parameters
  21998. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21999. */
  22000. AbstractMesh.prototype.getFacetDataParameters = function () {
  22001. return this._facetData.facetParameters;
  22002. };
  22003. /**
  22004. * Disables the feature FacetData and frees the related memory
  22005. * @returns the current mesh
  22006. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22007. */
  22008. AbstractMesh.prototype.disableFacetData = function () {
  22009. if (this._facetData.facetDataEnabled) {
  22010. this._facetData.facetDataEnabled = false;
  22011. this._facetData.facetPositions = new Array();
  22012. this._facetData.facetNormals = new Array();
  22013. this._facetData.facetPartitioning = new Array();
  22014. this._facetData.facetParameters = null;
  22015. this._facetData.depthSortedIndices = new Uint32Array(0);
  22016. }
  22017. return this;
  22018. };
  22019. /**
  22020. * Updates the AbstractMesh indices array
  22021. * @param indices defines the data source
  22022. * @returns the current mesh
  22023. */
  22024. AbstractMesh.prototype.updateIndices = function (indices) {
  22025. return this;
  22026. };
  22027. /**
  22028. * Creates new normals data for the mesh
  22029. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22030. * @returns the current mesh
  22031. */
  22032. AbstractMesh.prototype.createNormals = function (updatable) {
  22033. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22034. var indices = this.getIndices();
  22035. var normals;
  22036. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22037. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22038. }
  22039. else {
  22040. normals = [];
  22041. }
  22042. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22043. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22044. return this;
  22045. };
  22046. /**
  22047. * Align the mesh with a normal
  22048. * @param normal defines the normal to use
  22049. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22050. * @returns the current mesh
  22051. */
  22052. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22053. if (!upDirection) {
  22054. upDirection = BABYLON.Axis.Y;
  22055. }
  22056. var axisX = BABYLON.Tmp.Vector3[0];
  22057. var axisZ = BABYLON.Tmp.Vector3[1];
  22058. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22059. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22060. if (this.rotationQuaternion) {
  22061. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22062. }
  22063. else {
  22064. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22065. }
  22066. return this;
  22067. };
  22068. /** @hidden */
  22069. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22070. return false;
  22071. };
  22072. /** No occlusion */
  22073. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22074. /** Occlusion set to optimisitic */
  22075. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22076. /** Occlusion set to strict */
  22077. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22078. /** Use an accurante occlusion algorithm */
  22079. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22080. /** Use a conservative occlusion algorithm */
  22081. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22082. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22083. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22084. /** Culling strategy with bounding sphere only and then frustum culling */
  22085. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22086. return AbstractMesh;
  22087. }(BABYLON.TransformNode));
  22088. BABYLON.AbstractMesh = AbstractMesh;
  22089. })(BABYLON || (BABYLON = {}));
  22090. //# sourceMappingURL=babylon.abstractMesh.js.map
  22091. var BABYLON;
  22092. (function (BABYLON) {
  22093. /**
  22094. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22095. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22096. * 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.
  22097. */
  22098. var Light = /** @class */ (function (_super) {
  22099. __extends(Light, _super);
  22100. /**
  22101. * Creates a Light object in the scene.
  22102. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22103. * @param name The firendly name of the light
  22104. * @param scene The scene the light belongs too
  22105. */
  22106. function Light(name, scene) {
  22107. var _this = _super.call(this, name, scene) || this;
  22108. /**
  22109. * Diffuse gives the basic color to an object.
  22110. */
  22111. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22112. /**
  22113. * Specular produces a highlight color on an object.
  22114. * Note: This is note affecting PBR materials.
  22115. */
  22116. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22117. /**
  22118. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22119. * falling off base on range or angle.
  22120. * This can be set to any values in Light.FALLOFF_x.
  22121. *
  22122. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22123. * other types of materials.
  22124. */
  22125. _this.falloffType = Light.FALLOFF_DEFAULT;
  22126. /**
  22127. * Strength of the light.
  22128. * Note: By default it is define in the framework own unit.
  22129. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22130. */
  22131. _this.intensity = 1.0;
  22132. _this._range = Number.MAX_VALUE;
  22133. _this._inverseSquaredRange = 0;
  22134. /**
  22135. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22136. * of light.
  22137. */
  22138. _this._photometricScale = 1.0;
  22139. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22140. _this._radius = 0.00001;
  22141. /**
  22142. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22143. * exceeding the number allowed of the materials.
  22144. */
  22145. _this.renderPriority = 0;
  22146. _this._shadowEnabled = true;
  22147. _this._excludeWithLayerMask = 0;
  22148. _this._includeOnlyWithLayerMask = 0;
  22149. _this._lightmapMode = 0;
  22150. /**
  22151. * @hidden Internal use only.
  22152. */
  22153. _this._excludedMeshesIds = new Array();
  22154. /**
  22155. * @hidden Internal use only.
  22156. */
  22157. _this._includedOnlyMeshesIds = new Array();
  22158. _this.getScene().addLight(_this);
  22159. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22160. _this._buildUniformLayout();
  22161. _this.includedOnlyMeshes = new Array();
  22162. _this.excludedMeshes = new Array();
  22163. _this._resyncMeshes();
  22164. return _this;
  22165. }
  22166. Object.defineProperty(Light.prototype, "range", {
  22167. /**
  22168. * Defines how far from the source the light is impacting in scene units.
  22169. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22170. */
  22171. get: function () {
  22172. return this._range;
  22173. },
  22174. /**
  22175. * Defines how far from the source the light is impacting in scene units.
  22176. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22177. */
  22178. set: function (value) {
  22179. this._range = value;
  22180. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22181. },
  22182. enumerable: true,
  22183. configurable: true
  22184. });
  22185. Object.defineProperty(Light.prototype, "intensityMode", {
  22186. /**
  22187. * Gets the photometric scale used to interpret the intensity.
  22188. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22189. */
  22190. get: function () {
  22191. return this._intensityMode;
  22192. },
  22193. /**
  22194. * Sets the photometric scale used to interpret the intensity.
  22195. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22196. */
  22197. set: function (value) {
  22198. this._intensityMode = value;
  22199. this._computePhotometricScale();
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. ;
  22205. ;
  22206. Object.defineProperty(Light.prototype, "radius", {
  22207. /**
  22208. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22209. */
  22210. get: function () {
  22211. return this._radius;
  22212. },
  22213. /**
  22214. * sets the light radius used by PBR Materials to simulate soft area lights.
  22215. */
  22216. set: function (value) {
  22217. this._radius = value;
  22218. this._computePhotometricScale();
  22219. },
  22220. enumerable: true,
  22221. configurable: true
  22222. });
  22223. ;
  22224. ;
  22225. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22226. /**
  22227. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22228. * the current shadow generator.
  22229. */
  22230. get: function () {
  22231. return this._shadowEnabled;
  22232. },
  22233. /**
  22234. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22235. * the current shadow generator.
  22236. */
  22237. set: function (value) {
  22238. if (this._shadowEnabled === value) {
  22239. return;
  22240. }
  22241. this._shadowEnabled = value;
  22242. this._markMeshesAsLightDirty();
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22248. /**
  22249. * Gets the only meshes impacted by this light.
  22250. */
  22251. get: function () {
  22252. return this._includedOnlyMeshes;
  22253. },
  22254. /**
  22255. * Sets the only meshes impacted by this light.
  22256. */
  22257. set: function (value) {
  22258. this._includedOnlyMeshes = value;
  22259. this._hookArrayForIncludedOnly(value);
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22265. /**
  22266. * Gets the meshes not impacted by this light.
  22267. */
  22268. get: function () {
  22269. return this._excludedMeshes;
  22270. },
  22271. /**
  22272. * Sets the meshes not impacted by this light.
  22273. */
  22274. set: function (value) {
  22275. this._excludedMeshes = value;
  22276. this._hookArrayForExcluded(value);
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22282. /**
  22283. * Gets the layer id use to find what meshes are not impacted by the light.
  22284. * Inactive if 0
  22285. */
  22286. get: function () {
  22287. return this._excludeWithLayerMask;
  22288. },
  22289. /**
  22290. * Sets the layer id use to find what meshes are not impacted by the light.
  22291. * Inactive if 0
  22292. */
  22293. set: function (value) {
  22294. this._excludeWithLayerMask = value;
  22295. this._resyncMeshes();
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22301. /**
  22302. * Gets the layer id use to find what meshes are impacted by the light.
  22303. * Inactive if 0
  22304. */
  22305. get: function () {
  22306. return this._includeOnlyWithLayerMask;
  22307. },
  22308. /**
  22309. * Sets the layer id use to find what meshes are impacted by the light.
  22310. * Inactive if 0
  22311. */
  22312. set: function (value) {
  22313. this._includeOnlyWithLayerMask = value;
  22314. this._resyncMeshes();
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Light.prototype, "lightmapMode", {
  22320. /**
  22321. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22322. */
  22323. get: function () {
  22324. return this._lightmapMode;
  22325. },
  22326. /**
  22327. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22328. */
  22329. set: function (value) {
  22330. if (this._lightmapMode === value) {
  22331. return;
  22332. }
  22333. this._lightmapMode = value;
  22334. this._markMeshesAsLightDirty();
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. /**
  22340. * Returns the string "Light".
  22341. * @returns the class name
  22342. */
  22343. Light.prototype.getClassName = function () {
  22344. return "Light";
  22345. };
  22346. /**
  22347. * Converts the light information to a readable string for debug purpose.
  22348. * @param fullDetails Supports for multiple levels of logging within scene loading
  22349. * @returns the human readable light info
  22350. */
  22351. Light.prototype.toString = function (fullDetails) {
  22352. var ret = "Name: " + this.name;
  22353. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22354. if (this.animations) {
  22355. for (var i = 0; i < this.animations.length; i++) {
  22356. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22357. }
  22358. }
  22359. if (fullDetails) {
  22360. }
  22361. return ret;
  22362. };
  22363. /** @hidden */
  22364. Light.prototype._syncParentEnabledState = function () {
  22365. _super.prototype._syncParentEnabledState.call(this);
  22366. this._resyncMeshes();
  22367. };
  22368. /**
  22369. * Set the enabled state of this node.
  22370. * @param value - the new enabled state
  22371. */
  22372. Light.prototype.setEnabled = function (value) {
  22373. _super.prototype.setEnabled.call(this, value);
  22374. this._resyncMeshes();
  22375. };
  22376. /**
  22377. * Returns the Light associated shadow generator if any.
  22378. * @return the associated shadow generator.
  22379. */
  22380. Light.prototype.getShadowGenerator = function () {
  22381. return this._shadowGenerator;
  22382. };
  22383. /**
  22384. * Returns a Vector3, the absolute light position in the World.
  22385. * @returns the world space position of the light
  22386. */
  22387. Light.prototype.getAbsolutePosition = function () {
  22388. return BABYLON.Vector3.Zero();
  22389. };
  22390. /**
  22391. * Specifies if the light will affect the passed mesh.
  22392. * @param mesh The mesh to test against the light
  22393. * @return true the mesh is affected otherwise, false.
  22394. */
  22395. Light.prototype.canAffectMesh = function (mesh) {
  22396. if (!mesh) {
  22397. return true;
  22398. }
  22399. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22400. return false;
  22401. }
  22402. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22403. return false;
  22404. }
  22405. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22406. return false;
  22407. }
  22408. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22409. return false;
  22410. }
  22411. return true;
  22412. };
  22413. /**
  22414. * Sort function to order lights for rendering.
  22415. * @param a First Light object to compare to second.
  22416. * @param b Second Light object to compare first.
  22417. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22418. */
  22419. Light.CompareLightsPriority = function (a, b) {
  22420. //shadow-casting lights have priority over non-shadow-casting lights
  22421. //the renderPrioirty is a secondary sort criterion
  22422. if (a.shadowEnabled !== b.shadowEnabled) {
  22423. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22424. }
  22425. return b.renderPriority - a.renderPriority;
  22426. };
  22427. /**
  22428. * Releases resources associated with this node.
  22429. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22430. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22431. */
  22432. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22433. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22434. if (this._shadowGenerator) {
  22435. this._shadowGenerator.dispose();
  22436. this._shadowGenerator = null;
  22437. }
  22438. // Animations
  22439. this.getScene().stopAnimation(this);
  22440. // Remove from meshes
  22441. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22442. var mesh = _a[_i];
  22443. mesh._removeLightSource(this);
  22444. }
  22445. this._uniformBuffer.dispose();
  22446. // Remove from scene
  22447. this.getScene().removeLight(this);
  22448. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22449. };
  22450. /**
  22451. * Returns the light type ID (integer).
  22452. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22453. */
  22454. Light.prototype.getTypeID = function () {
  22455. return 0;
  22456. };
  22457. /**
  22458. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22459. * @returns the scaled intensity in intensity mode unit
  22460. */
  22461. Light.prototype.getScaledIntensity = function () {
  22462. return this._photometricScale * this.intensity;
  22463. };
  22464. /**
  22465. * Returns a new Light object, named "name", from the current one.
  22466. * @param name The name of the cloned light
  22467. * @returns the new created light
  22468. */
  22469. Light.prototype.clone = function (name) {
  22470. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22471. if (!constructor) {
  22472. return null;
  22473. }
  22474. return BABYLON.SerializationHelper.Clone(constructor, this);
  22475. };
  22476. /**
  22477. * Serializes the current light into a Serialization object.
  22478. * @returns the serialized object.
  22479. */
  22480. Light.prototype.serialize = function () {
  22481. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22482. // Type
  22483. serializationObject.type = this.getTypeID();
  22484. // Parent
  22485. if (this.parent) {
  22486. serializationObject.parentId = this.parent.id;
  22487. }
  22488. // Inclusion / exclusions
  22489. if (this.excludedMeshes.length > 0) {
  22490. serializationObject.excludedMeshesIds = [];
  22491. this.excludedMeshes.forEach(function (mesh) {
  22492. serializationObject.excludedMeshesIds.push(mesh.id);
  22493. });
  22494. }
  22495. if (this.includedOnlyMeshes.length > 0) {
  22496. serializationObject.includedOnlyMeshesIds = [];
  22497. this.includedOnlyMeshes.forEach(function (mesh) {
  22498. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22499. });
  22500. }
  22501. // Animations
  22502. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22503. serializationObject.ranges = this.serializeAnimationRanges();
  22504. return serializationObject;
  22505. };
  22506. /**
  22507. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22508. * This new light is named "name" and added to the passed scene.
  22509. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22510. * @param name The friendly name of the light
  22511. * @param scene The scene the new light will belong to
  22512. * @returns the constructor function
  22513. */
  22514. Light.GetConstructorFromName = function (type, name, scene) {
  22515. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22516. if (constructorFunc) {
  22517. return constructorFunc;
  22518. }
  22519. // Default to no light for none present once.
  22520. return null;
  22521. };
  22522. /**
  22523. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22524. * @param parsedLight The JSON representation of the light
  22525. * @param scene The scene to create the parsed light in
  22526. * @returns the created light after parsing
  22527. */
  22528. Light.Parse = function (parsedLight, scene) {
  22529. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22530. if (!constructor) {
  22531. return null;
  22532. }
  22533. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22534. // Inclusion / exclusions
  22535. if (parsedLight.excludedMeshesIds) {
  22536. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22537. }
  22538. if (parsedLight.includedOnlyMeshesIds) {
  22539. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22540. }
  22541. // Parent
  22542. if (parsedLight.parentId) {
  22543. light._waitingParentId = parsedLight.parentId;
  22544. }
  22545. // Animations
  22546. if (parsedLight.animations) {
  22547. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22548. var parsedAnimation = parsedLight.animations[animationIndex];
  22549. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22550. }
  22551. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22552. }
  22553. if (parsedLight.autoAnimate) {
  22554. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22555. }
  22556. return light;
  22557. };
  22558. Light.prototype._hookArrayForExcluded = function (array) {
  22559. var _this = this;
  22560. var oldPush = array.push;
  22561. array.push = function () {
  22562. var items = [];
  22563. for (var _i = 0; _i < arguments.length; _i++) {
  22564. items[_i] = arguments[_i];
  22565. }
  22566. var result = oldPush.apply(array, items);
  22567. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22568. var item = items_1[_a];
  22569. item._resyncLighSource(_this);
  22570. }
  22571. return result;
  22572. };
  22573. var oldSplice = array.splice;
  22574. array.splice = function (index, deleteCount) {
  22575. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22576. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22577. var item = deleted_1[_i];
  22578. item._resyncLighSource(_this);
  22579. }
  22580. return deleted;
  22581. };
  22582. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22583. var item = array_1[_i];
  22584. item._resyncLighSource(this);
  22585. }
  22586. };
  22587. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22588. var _this = this;
  22589. var oldPush = array.push;
  22590. array.push = function () {
  22591. var items = [];
  22592. for (var _i = 0; _i < arguments.length; _i++) {
  22593. items[_i] = arguments[_i];
  22594. }
  22595. var result = oldPush.apply(array, items);
  22596. _this._resyncMeshes();
  22597. return result;
  22598. };
  22599. var oldSplice = array.splice;
  22600. array.splice = function (index, deleteCount) {
  22601. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22602. _this._resyncMeshes();
  22603. return deleted;
  22604. };
  22605. this._resyncMeshes();
  22606. };
  22607. Light.prototype._resyncMeshes = function () {
  22608. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22609. var mesh = _a[_i];
  22610. mesh._resyncLighSource(this);
  22611. }
  22612. };
  22613. /**
  22614. * Forces the meshes to update their light related information in their rendering used effects
  22615. * @hidden Internal Use Only
  22616. */
  22617. Light.prototype._markMeshesAsLightDirty = function () {
  22618. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22619. var mesh = _a[_i];
  22620. if (mesh._lightSources.indexOf(this) !== -1) {
  22621. mesh._markSubMeshesAsLightDirty();
  22622. }
  22623. }
  22624. };
  22625. /**
  22626. * Recomputes the cached photometric scale if needed.
  22627. */
  22628. Light.prototype._computePhotometricScale = function () {
  22629. this._photometricScale = this._getPhotometricScale();
  22630. this.getScene().resetCachedMaterial();
  22631. };
  22632. /**
  22633. * Returns the Photometric Scale according to the light type and intensity mode.
  22634. */
  22635. Light.prototype._getPhotometricScale = function () {
  22636. var photometricScale = 0.0;
  22637. var lightTypeID = this.getTypeID();
  22638. //get photometric mode
  22639. var photometricMode = this.intensityMode;
  22640. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22641. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22642. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22643. }
  22644. else {
  22645. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22646. }
  22647. }
  22648. //compute photometric scale
  22649. switch (lightTypeID) {
  22650. case Light.LIGHTTYPEID_POINTLIGHT:
  22651. case Light.LIGHTTYPEID_SPOTLIGHT:
  22652. switch (photometricMode) {
  22653. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22654. photometricScale = 1.0 / (4.0 * Math.PI);
  22655. break;
  22656. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22657. photometricScale = 1.0;
  22658. break;
  22659. case Light.INTENSITYMODE_LUMINANCE:
  22660. photometricScale = this.radius * this.radius;
  22661. break;
  22662. }
  22663. break;
  22664. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22665. switch (photometricMode) {
  22666. case Light.INTENSITYMODE_ILLUMINANCE:
  22667. photometricScale = 1.0;
  22668. break;
  22669. case Light.INTENSITYMODE_LUMINANCE:
  22670. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22671. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22672. var apexAngleRadians = this.radius;
  22673. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22674. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22675. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22676. photometricScale = solidAngle;
  22677. break;
  22678. }
  22679. break;
  22680. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22681. // No fall off in hemisperic light.
  22682. photometricScale = 1.0;
  22683. break;
  22684. }
  22685. return photometricScale;
  22686. };
  22687. /**
  22688. * Reorder the light in the scene according to their defined priority.
  22689. * @hidden Internal Use Only
  22690. */
  22691. Light.prototype._reorderLightsInScene = function () {
  22692. var scene = this.getScene();
  22693. if (this._renderPriority != 0) {
  22694. scene.requireLightSorting = true;
  22695. }
  22696. this.getScene().sortLightsByPriority();
  22697. };
  22698. /**
  22699. * Falloff Default: light is falling off following the material specification:
  22700. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22701. */
  22702. Light.FALLOFF_DEFAULT = 0;
  22703. /**
  22704. * Falloff Physical: light is falling off following the inverse squared distance law.
  22705. */
  22706. Light.FALLOFF_PHYSICAL = 1;
  22707. /**
  22708. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22709. * to enhance interoperability with other engines.
  22710. */
  22711. Light.FALLOFF_GLTF = 2;
  22712. /**
  22713. * Falloff Standard: light is falling off like in the standard material
  22714. * to enhance interoperability with other materials.
  22715. */
  22716. Light.FALLOFF_STANDARD = 3;
  22717. //lightmapMode Consts
  22718. /**
  22719. * If every light affecting the material is in this lightmapMode,
  22720. * material.lightmapTexture adds or multiplies
  22721. * (depends on material.useLightmapAsShadowmap)
  22722. * after every other light calculations.
  22723. */
  22724. Light.LIGHTMAP_DEFAULT = 0;
  22725. /**
  22726. * material.lightmapTexture as only diffuse lighting from this light
  22727. * adds only specular lighting from this light
  22728. * adds dynamic shadows
  22729. */
  22730. Light.LIGHTMAP_SPECULAR = 1;
  22731. /**
  22732. * material.lightmapTexture as only lighting
  22733. * no light calculation from this light
  22734. * only adds dynamic shadows from this light
  22735. */
  22736. Light.LIGHTMAP_SHADOWSONLY = 2;
  22737. // Intensity Mode Consts
  22738. /**
  22739. * Each light type uses the default quantity according to its type:
  22740. * point/spot lights use luminous intensity
  22741. * directional lights use illuminance
  22742. */
  22743. Light.INTENSITYMODE_AUTOMATIC = 0;
  22744. /**
  22745. * lumen (lm)
  22746. */
  22747. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22748. /**
  22749. * candela (lm/sr)
  22750. */
  22751. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22752. /**
  22753. * lux (lm/m^2)
  22754. */
  22755. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22756. /**
  22757. * nit (cd/m^2)
  22758. */
  22759. Light.INTENSITYMODE_LUMINANCE = 4;
  22760. // Light types ids const.
  22761. /**
  22762. * Light type const id of the point light.
  22763. */
  22764. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22765. /**
  22766. * Light type const id of the directional light.
  22767. */
  22768. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22769. /**
  22770. * Light type const id of the spot light.
  22771. */
  22772. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22773. /**
  22774. * Light type const id of the hemispheric light.
  22775. */
  22776. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22777. __decorate([
  22778. BABYLON.serializeAsColor3()
  22779. ], Light.prototype, "diffuse", void 0);
  22780. __decorate([
  22781. BABYLON.serializeAsColor3()
  22782. ], Light.prototype, "specular", void 0);
  22783. __decorate([
  22784. BABYLON.serialize()
  22785. ], Light.prototype, "falloffType", void 0);
  22786. __decorate([
  22787. BABYLON.serialize()
  22788. ], Light.prototype, "intensity", void 0);
  22789. __decorate([
  22790. BABYLON.serialize()
  22791. ], Light.prototype, "range", null);
  22792. __decorate([
  22793. BABYLON.serialize()
  22794. ], Light.prototype, "intensityMode", null);
  22795. __decorate([
  22796. BABYLON.serialize()
  22797. ], Light.prototype, "radius", null);
  22798. __decorate([
  22799. BABYLON.serialize()
  22800. ], Light.prototype, "_renderPriority", void 0);
  22801. __decorate([
  22802. BABYLON.expandToProperty("_reorderLightsInScene")
  22803. ], Light.prototype, "renderPriority", void 0);
  22804. __decorate([
  22805. BABYLON.serialize("shadowEnabled")
  22806. ], Light.prototype, "_shadowEnabled", void 0);
  22807. __decorate([
  22808. BABYLON.serialize("excludeWithLayerMask")
  22809. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22810. __decorate([
  22811. BABYLON.serialize("includeOnlyWithLayerMask")
  22812. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22813. __decorate([
  22814. BABYLON.serialize("lightmapMode")
  22815. ], Light.prototype, "_lightmapMode", void 0);
  22816. return Light;
  22817. }(BABYLON.Node));
  22818. BABYLON.Light = Light;
  22819. })(BABYLON || (BABYLON = {}));
  22820. //# sourceMappingURL=babylon.light.js.map
  22821. var BABYLON;
  22822. (function (BABYLON) {
  22823. /**
  22824. * This is the base class of all the camera used in the application.
  22825. * @see http://doc.babylonjs.com/features/cameras
  22826. */
  22827. var Camera = /** @class */ (function (_super) {
  22828. __extends(Camera, _super);
  22829. /**
  22830. * Instantiates a new camera object.
  22831. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22832. * @see http://doc.babylonjs.com/features/cameras
  22833. * @param name Defines the name of the camera in the scene
  22834. * @param position Defines the position of the camera
  22835. * @param scene Defines the scene the camera belongs too
  22836. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22837. */
  22838. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22839. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22840. var _this = _super.call(this, name, scene) || this;
  22841. /**
  22842. * The vector the camera should consider as up.
  22843. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22844. */
  22845. _this.upVector = BABYLON.Vector3.Up();
  22846. /**
  22847. * Define the current limit on the left side for an orthographic camera
  22848. * In scene unit
  22849. */
  22850. _this.orthoLeft = null;
  22851. /**
  22852. * Define the current limit on the right side for an orthographic camera
  22853. * In scene unit
  22854. */
  22855. _this.orthoRight = null;
  22856. /**
  22857. * Define the current limit on the bottom side for an orthographic camera
  22858. * In scene unit
  22859. */
  22860. _this.orthoBottom = null;
  22861. /**
  22862. * Define the current limit on the top side for an orthographic camera
  22863. * In scene unit
  22864. */
  22865. _this.orthoTop = null;
  22866. /**
  22867. * Field Of View is set in Radians. (default is 0.8)
  22868. */
  22869. _this.fov = 0.8;
  22870. /**
  22871. * Define the minimum distance the camera can see from.
  22872. * This is important to note that the depth buffer are not infinite and the closer it starts
  22873. * the more your scene might encounter depth fighting issue.
  22874. */
  22875. _this.minZ = 1;
  22876. /**
  22877. * Define the maximum distance the camera can see to.
  22878. * This is important to note that the depth buffer are not infinite and the further it end
  22879. * the more your scene might encounter depth fighting issue.
  22880. */
  22881. _this.maxZ = 10000.0;
  22882. /**
  22883. * Define the default inertia of the camera.
  22884. * This helps giving a smooth feeling to the camera movement.
  22885. */
  22886. _this.inertia = 0.9;
  22887. /**
  22888. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22889. */
  22890. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22891. /**
  22892. * Define wether the camera is intermediate.
  22893. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22894. */
  22895. _this.isIntermediate = false;
  22896. /**
  22897. * Define the viewport of the camera.
  22898. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22899. */
  22900. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22901. /**
  22902. * Restricts the camera to viewing objects with the same layerMask.
  22903. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22904. */
  22905. _this.layerMask = 0x0FFFFFFF;
  22906. /**
  22907. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22908. */
  22909. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22910. /**
  22911. * Rig mode of the camera.
  22912. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22913. * This is normally controlled byt the camera themselves as internal use.
  22914. */
  22915. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22916. /**
  22917. * Defines the list of custom render target the camera should render to.
  22918. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22919. * else in the scene.
  22920. */
  22921. _this.customRenderTargets = new Array();
  22922. /**
  22923. * Observable triggered when the camera view matrix has changed.
  22924. */
  22925. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22926. /**
  22927. * Observable triggered when the camera Projection matrix has changed.
  22928. */
  22929. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22930. /**
  22931. * Observable triggered when the inputs have been processed.
  22932. */
  22933. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22934. /**
  22935. * Observable triggered when reset has been called and applied to the camera.
  22936. */
  22937. _this.onRestoreStateObservable = new BABYLON.Observable();
  22938. /** @hidden */
  22939. _this._rigCameras = new Array();
  22940. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22941. /** @hidden */
  22942. _this._skipRendering = false;
  22943. /** @hidden */
  22944. _this._projectionMatrix = new BABYLON.Matrix();
  22945. /** @hidden */
  22946. _this._postProcesses = new Array();
  22947. /** @hidden */
  22948. _this._activeMeshes = new BABYLON.SmartArray(256);
  22949. _this._globalPosition = BABYLON.Vector3.Zero();
  22950. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22951. _this._doNotComputeProjectionMatrix = false;
  22952. _this._transformMatrix = BABYLON.Matrix.Zero();
  22953. _this._refreshFrustumPlanes = true;
  22954. _this.getScene().addCamera(_this);
  22955. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22956. _this.getScene().activeCamera = _this;
  22957. }
  22958. _this.position = position;
  22959. return _this;
  22960. }
  22961. /**
  22962. * Store current camera state (fov, position, etc..)
  22963. * @returns the camera
  22964. */
  22965. Camera.prototype.storeState = function () {
  22966. this._stateStored = true;
  22967. this._storedFov = this.fov;
  22968. return this;
  22969. };
  22970. /**
  22971. * Restores the camera state values if it has been stored. You must call storeState() first
  22972. */
  22973. Camera.prototype._restoreStateValues = function () {
  22974. if (!this._stateStored) {
  22975. return false;
  22976. }
  22977. this.fov = this._storedFov;
  22978. return true;
  22979. };
  22980. /**
  22981. * Restored camera state. You must call storeState() first.
  22982. * @returns true if restored and false otherwise
  22983. */
  22984. Camera.prototype.restoreState = function () {
  22985. if (this._restoreStateValues()) {
  22986. this.onRestoreStateObservable.notifyObservers(this);
  22987. return true;
  22988. }
  22989. return false;
  22990. };
  22991. /**
  22992. * Gets the class name of the camera.
  22993. * @returns the class name
  22994. */
  22995. Camera.prototype.getClassName = function () {
  22996. return "Camera";
  22997. };
  22998. /**
  22999. * Gets a string representation of the camera usefull for debug purpose.
  23000. * @param fullDetails Defines that a more verboe level of logging is required
  23001. * @returns the string representation
  23002. */
  23003. Camera.prototype.toString = function (fullDetails) {
  23004. var ret = "Name: " + this.name;
  23005. ret += ", type: " + this.getClassName();
  23006. if (this.animations) {
  23007. for (var i = 0; i < this.animations.length; i++) {
  23008. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23009. }
  23010. }
  23011. if (fullDetails) {
  23012. }
  23013. return ret;
  23014. };
  23015. Object.defineProperty(Camera.prototype, "globalPosition", {
  23016. /**
  23017. * Gets the current world space position of the camera.
  23018. */
  23019. get: function () {
  23020. return this._globalPosition;
  23021. },
  23022. enumerable: true,
  23023. configurable: true
  23024. });
  23025. /**
  23026. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23027. * @returns the active meshe list
  23028. */
  23029. Camera.prototype.getActiveMeshes = function () {
  23030. return this._activeMeshes;
  23031. };
  23032. /**
  23033. * Check wether a mesh is part of the current active mesh list of the camera
  23034. * @param mesh Defines the mesh to check
  23035. * @returns true if active, false otherwise
  23036. */
  23037. Camera.prototype.isActiveMesh = function (mesh) {
  23038. return (this._activeMeshes.indexOf(mesh) !== -1);
  23039. };
  23040. /**
  23041. * Is this camera ready to be used/rendered
  23042. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23043. * @return true if the camera is ready
  23044. */
  23045. Camera.prototype.isReady = function (completeCheck) {
  23046. if (completeCheck === void 0) { completeCheck = false; }
  23047. if (completeCheck) {
  23048. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23049. var pp = _a[_i];
  23050. if (pp && !pp.isReady()) {
  23051. return false;
  23052. }
  23053. }
  23054. }
  23055. return _super.prototype.isReady.call(this, completeCheck);
  23056. };
  23057. /** @hidden */
  23058. Camera.prototype._initCache = function () {
  23059. _super.prototype._initCache.call(this);
  23060. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23061. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23062. this._cache.mode = undefined;
  23063. this._cache.minZ = undefined;
  23064. this._cache.maxZ = undefined;
  23065. this._cache.fov = undefined;
  23066. this._cache.fovMode = undefined;
  23067. this._cache.aspectRatio = undefined;
  23068. this._cache.orthoLeft = undefined;
  23069. this._cache.orthoRight = undefined;
  23070. this._cache.orthoBottom = undefined;
  23071. this._cache.orthoTop = undefined;
  23072. this._cache.renderWidth = undefined;
  23073. this._cache.renderHeight = undefined;
  23074. };
  23075. /** @hidden */
  23076. Camera.prototype._updateCache = function (ignoreParentClass) {
  23077. if (!ignoreParentClass) {
  23078. _super.prototype._updateCache.call(this);
  23079. }
  23080. this._cache.position.copyFrom(this.position);
  23081. this._cache.upVector.copyFrom(this.upVector);
  23082. };
  23083. /** @hidden */
  23084. Camera.prototype._isSynchronized = function () {
  23085. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23086. };
  23087. /** @hidden */
  23088. Camera.prototype._isSynchronizedViewMatrix = function () {
  23089. if (!_super.prototype._isSynchronized.call(this))
  23090. return false;
  23091. return this._cache.position.equals(this.position)
  23092. && this._cache.upVector.equals(this.upVector)
  23093. && this.isSynchronizedWithParent();
  23094. };
  23095. /** @hidden */
  23096. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23097. var check = this._cache.mode === this.mode
  23098. && this._cache.minZ === this.minZ
  23099. && this._cache.maxZ === this.maxZ;
  23100. if (!check) {
  23101. return false;
  23102. }
  23103. var engine = this.getEngine();
  23104. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23105. check = this._cache.fov === this.fov
  23106. && this._cache.fovMode === this.fovMode
  23107. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23108. }
  23109. else {
  23110. check = this._cache.orthoLeft === this.orthoLeft
  23111. && this._cache.orthoRight === this.orthoRight
  23112. && this._cache.orthoBottom === this.orthoBottom
  23113. && this._cache.orthoTop === this.orthoTop
  23114. && this._cache.renderWidth === engine.getRenderWidth()
  23115. && this._cache.renderHeight === engine.getRenderHeight();
  23116. }
  23117. return check;
  23118. };
  23119. /**
  23120. * Attach the input controls to a specific dom element to get the input from.
  23121. * @param element Defines the element the controls should be listened from
  23122. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23123. */
  23124. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23125. };
  23126. /**
  23127. * Detach the current controls from the specified dom element.
  23128. * @param element Defines the element to stop listening the inputs from
  23129. */
  23130. Camera.prototype.detachControl = function (element) {
  23131. };
  23132. /**
  23133. * Update the camera state according to the different inputs gathered during the frame.
  23134. */
  23135. Camera.prototype.update = function () {
  23136. this._checkInputs();
  23137. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23138. this._updateRigCameras();
  23139. }
  23140. };
  23141. /** @hidden */
  23142. Camera.prototype._checkInputs = function () {
  23143. this.onAfterCheckInputsObservable.notifyObservers(this);
  23144. };
  23145. Object.defineProperty(Camera.prototype, "rigCameras", {
  23146. /** @hidden */
  23147. get: function () {
  23148. return this._rigCameras;
  23149. },
  23150. enumerable: true,
  23151. configurable: true
  23152. });
  23153. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23154. /**
  23155. * Gets the post process used by the rig cameras
  23156. */
  23157. get: function () {
  23158. return this._rigPostProcess;
  23159. },
  23160. enumerable: true,
  23161. configurable: true
  23162. });
  23163. /**
  23164. * Internal, gets the first post proces.
  23165. * @returns the first post process to be run on this camera.
  23166. */
  23167. Camera.prototype._getFirstPostProcess = function () {
  23168. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23169. if (this._postProcesses[ppIndex] !== null) {
  23170. return this._postProcesses[ppIndex];
  23171. }
  23172. }
  23173. return null;
  23174. };
  23175. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23176. // invalidate framebuffer
  23177. var firstPostProcess = this._getFirstPostProcess();
  23178. if (firstPostProcess) {
  23179. firstPostProcess.markTextureDirty();
  23180. }
  23181. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23182. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23183. var cam = this._rigCameras[i];
  23184. var rigPostProcess = cam._rigPostProcess;
  23185. // for VR rig, there does not have to be a post process
  23186. if (rigPostProcess) {
  23187. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23188. if (isPass) {
  23189. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23190. cam.isIntermediate = this._postProcesses.length === 0;
  23191. }
  23192. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23193. rigPostProcess.markTextureDirty();
  23194. }
  23195. else {
  23196. cam._postProcesses = this._postProcesses.slice(0);
  23197. }
  23198. }
  23199. };
  23200. /**
  23201. * Attach a post process to the camera.
  23202. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23203. * @param postProcess The post process to attach to the camera
  23204. * @param insertAt The position of the post process in case several of them are in use in the scene
  23205. * @returns the position the post process has been inserted at
  23206. */
  23207. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23208. if (insertAt === void 0) { insertAt = null; }
  23209. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23210. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23211. return 0;
  23212. }
  23213. if (insertAt == null || insertAt < 0) {
  23214. this._postProcesses.push(postProcess);
  23215. }
  23216. else if (this._postProcesses[insertAt] === null) {
  23217. this._postProcesses[insertAt] = postProcess;
  23218. }
  23219. else {
  23220. this._postProcesses.splice(insertAt, 0, postProcess);
  23221. }
  23222. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23223. return this._postProcesses.indexOf(postProcess);
  23224. };
  23225. /**
  23226. * Detach a post process to the camera.
  23227. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23228. * @param postProcess The post process to detach from the camera
  23229. */
  23230. Camera.prototype.detachPostProcess = function (postProcess) {
  23231. var idx = this._postProcesses.indexOf(postProcess);
  23232. if (idx !== -1) {
  23233. this._postProcesses[idx] = null;
  23234. }
  23235. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23236. };
  23237. /**
  23238. * Gets the current world matrix of the camera
  23239. */
  23240. Camera.prototype.getWorldMatrix = function () {
  23241. if (this._isSynchronizedViewMatrix()) {
  23242. return this._worldMatrix;
  23243. }
  23244. // Getting the the view matrix will also compute the world matrix.
  23245. this.getViewMatrix();
  23246. return this._worldMatrix;
  23247. };
  23248. /** @hidden */
  23249. Camera.prototype._getViewMatrix = function () {
  23250. return BABYLON.Matrix.Identity();
  23251. };
  23252. /**
  23253. * Gets the current view matrix of the camera.
  23254. * @param force forces the camera to recompute the matrix without looking at the cached state
  23255. * @returns the view matrix
  23256. */
  23257. Camera.prototype.getViewMatrix = function (force) {
  23258. if (!force && this._isSynchronizedViewMatrix()) {
  23259. return this._computedViewMatrix;
  23260. }
  23261. this.updateCache();
  23262. this._computedViewMatrix = this._getViewMatrix();
  23263. this._currentRenderId = this.getScene().getRenderId();
  23264. this._childRenderId = this._currentRenderId;
  23265. this._refreshFrustumPlanes = true;
  23266. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23267. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23268. }
  23269. this.onViewMatrixChangedObservable.notifyObservers(this);
  23270. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23271. return this._computedViewMatrix;
  23272. };
  23273. /**
  23274. * Freeze the projection matrix.
  23275. * It will prevent the cache check of the camera projection compute and can speed up perf
  23276. * if no parameter of the camera are meant to change
  23277. * @param projection Defines manually a projection if necessary
  23278. */
  23279. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23280. this._doNotComputeProjectionMatrix = true;
  23281. if (projection !== undefined) {
  23282. this._projectionMatrix = projection;
  23283. }
  23284. };
  23285. ;
  23286. /**
  23287. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23288. */
  23289. Camera.prototype.unfreezeProjectionMatrix = function () {
  23290. this._doNotComputeProjectionMatrix = false;
  23291. };
  23292. ;
  23293. /**
  23294. * Gets the current projection matrix of the camera.
  23295. * @param force forces the camera to recompute the matrix without looking at the cached state
  23296. * @returns the projection matrix
  23297. */
  23298. Camera.prototype.getProjectionMatrix = function (force) {
  23299. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23300. return this._projectionMatrix;
  23301. }
  23302. // Cache
  23303. this._cache.mode = this.mode;
  23304. this._cache.minZ = this.minZ;
  23305. this._cache.maxZ = this.maxZ;
  23306. // Matrix
  23307. this._refreshFrustumPlanes = true;
  23308. var engine = this.getEngine();
  23309. var scene = this.getScene();
  23310. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23311. this._cache.fov = this.fov;
  23312. this._cache.fovMode = this.fovMode;
  23313. this._cache.aspectRatio = engine.getAspectRatio(this);
  23314. if (this.minZ <= 0) {
  23315. this.minZ = 0.1;
  23316. }
  23317. if (scene.useRightHandedSystem) {
  23318. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23319. }
  23320. else {
  23321. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23322. }
  23323. }
  23324. else {
  23325. var halfWidth = engine.getRenderWidth() / 2.0;
  23326. var halfHeight = engine.getRenderHeight() / 2.0;
  23327. if (scene.useRightHandedSystem) {
  23328. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23329. }
  23330. else {
  23331. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23332. }
  23333. this._cache.orthoLeft = this.orthoLeft;
  23334. this._cache.orthoRight = this.orthoRight;
  23335. this._cache.orthoBottom = this.orthoBottom;
  23336. this._cache.orthoTop = this.orthoTop;
  23337. this._cache.renderWidth = engine.getRenderWidth();
  23338. this._cache.renderHeight = engine.getRenderHeight();
  23339. }
  23340. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23341. return this._projectionMatrix;
  23342. };
  23343. /**
  23344. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23345. * @returns a Matrix
  23346. */
  23347. Camera.prototype.getTransformationMatrix = function () {
  23348. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23349. return this._transformMatrix;
  23350. };
  23351. Camera.prototype._updateFrustumPlanes = function () {
  23352. if (!this._refreshFrustumPlanes) {
  23353. return;
  23354. }
  23355. this.getTransformationMatrix();
  23356. if (!this._frustumPlanes) {
  23357. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23358. }
  23359. else {
  23360. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23361. }
  23362. this._refreshFrustumPlanes = false;
  23363. };
  23364. /**
  23365. * Checks if a cullable object (mesh...) is in the camera frustum
  23366. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23367. * @param target The object to check
  23368. * @returns true if the object is in frustum otherwise false
  23369. */
  23370. Camera.prototype.isInFrustum = function (target) {
  23371. this._updateFrustumPlanes();
  23372. return target.isInFrustum(this._frustumPlanes);
  23373. };
  23374. /**
  23375. * Checks if a cullable object (mesh...) is in the camera frustum
  23376. * Unlike isInFrustum this cheks the full bounding box
  23377. * @param target The object to check
  23378. * @returns true if the object is in frustum otherwise false
  23379. */
  23380. Camera.prototype.isCompletelyInFrustum = function (target) {
  23381. this._updateFrustumPlanes();
  23382. return target.isCompletelyInFrustum(this._frustumPlanes);
  23383. };
  23384. /**
  23385. * Gets a ray in the forward direction from the camera.
  23386. * @param length Defines the length of the ray to create
  23387. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23388. * @param origin Defines the start point of the ray which defaults to the camera position
  23389. * @returns the forward ray
  23390. */
  23391. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23392. if (length === void 0) { length = 100; }
  23393. if (!transform) {
  23394. transform = this.getWorldMatrix();
  23395. }
  23396. if (!origin) {
  23397. origin = this.position;
  23398. }
  23399. var forward = new BABYLON.Vector3(0, 0, 1);
  23400. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23401. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23402. return new BABYLON.Ray(origin, direction, length);
  23403. };
  23404. /**
  23405. * Releases resources associated with this node.
  23406. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23407. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23408. */
  23409. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23410. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23411. // Observables
  23412. this.onViewMatrixChangedObservable.clear();
  23413. this.onProjectionMatrixChangedObservable.clear();
  23414. this.onAfterCheckInputsObservable.clear();
  23415. this.onRestoreStateObservable.clear();
  23416. // Inputs
  23417. if (this.inputs) {
  23418. this.inputs.clear();
  23419. }
  23420. // Animations
  23421. this.getScene().stopAnimation(this);
  23422. // Remove from scene
  23423. this.getScene().removeCamera(this);
  23424. while (this._rigCameras.length > 0) {
  23425. var camera = this._rigCameras.pop();
  23426. if (camera) {
  23427. camera.dispose();
  23428. }
  23429. }
  23430. // Postprocesses
  23431. if (this._rigPostProcess) {
  23432. this._rigPostProcess.dispose(this);
  23433. this._rigPostProcess = null;
  23434. this._postProcesses = [];
  23435. }
  23436. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23437. this._rigPostProcess = null;
  23438. this._postProcesses = [];
  23439. }
  23440. else {
  23441. var i = this._postProcesses.length;
  23442. while (--i >= 0) {
  23443. var postProcess = this._postProcesses[i];
  23444. if (postProcess) {
  23445. postProcess.dispose(this);
  23446. }
  23447. }
  23448. }
  23449. // Render targets
  23450. var i = this.customRenderTargets.length;
  23451. while (--i >= 0) {
  23452. this.customRenderTargets[i].dispose();
  23453. }
  23454. this.customRenderTargets = [];
  23455. // Active Meshes
  23456. this._activeMeshes.dispose();
  23457. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23458. };
  23459. Object.defineProperty(Camera.prototype, "leftCamera", {
  23460. /**
  23461. * Gets the left camera of a rig setup in case of Rigged Camera
  23462. */
  23463. get: function () {
  23464. if (this._rigCameras.length < 1) {
  23465. return null;
  23466. }
  23467. return this._rigCameras[0];
  23468. },
  23469. enumerable: true,
  23470. configurable: true
  23471. });
  23472. Object.defineProperty(Camera.prototype, "rightCamera", {
  23473. /**
  23474. * Gets the right camera of a rig setup in case of Rigged Camera
  23475. */
  23476. get: function () {
  23477. if (this._rigCameras.length < 2) {
  23478. return null;
  23479. }
  23480. return this._rigCameras[1];
  23481. },
  23482. enumerable: true,
  23483. configurable: true
  23484. });
  23485. /**
  23486. * Gets the left camera target of a rig setup in case of Rigged Camera
  23487. * @returns the target position
  23488. */
  23489. Camera.prototype.getLeftTarget = function () {
  23490. if (this._rigCameras.length < 1) {
  23491. return null;
  23492. }
  23493. return this._rigCameras[0].getTarget();
  23494. };
  23495. /**
  23496. * Gets the right camera target of a rig setup in case of Rigged Camera
  23497. * @returns the target position
  23498. */
  23499. Camera.prototype.getRightTarget = function () {
  23500. if (this._rigCameras.length < 2) {
  23501. return null;
  23502. }
  23503. return this._rigCameras[1].getTarget();
  23504. };
  23505. /**
  23506. * @hidden
  23507. */
  23508. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23509. if (this.cameraRigMode === mode) {
  23510. return;
  23511. }
  23512. while (this._rigCameras.length > 0) {
  23513. var camera = this._rigCameras.pop();
  23514. if (camera) {
  23515. camera.dispose();
  23516. }
  23517. }
  23518. this.cameraRigMode = mode;
  23519. this._cameraRigParams = {};
  23520. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23521. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23522. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23523. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23524. // create the rig cameras, unless none
  23525. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23526. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23527. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23528. if (leftCamera && rightCamera) {
  23529. this._rigCameras.push(leftCamera);
  23530. this._rigCameras.push(rightCamera);
  23531. }
  23532. }
  23533. switch (this.cameraRigMode) {
  23534. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23535. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23536. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23537. break;
  23538. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23539. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23540. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23541. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23542. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23543. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23544. break;
  23545. case Camera.RIG_MODE_VR:
  23546. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23547. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23548. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23549. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23550. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23551. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23552. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23553. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23554. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23555. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23556. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23557. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23558. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23559. if (metrics.compensateDistortion) {
  23560. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23561. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23562. }
  23563. break;
  23564. case Camera.RIG_MODE_WEBVR:
  23565. if (rigParams.vrDisplay) {
  23566. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23567. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23568. //Left eye
  23569. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23570. this._rigCameras[0].setCameraRigParameter("left", true);
  23571. //leaving this for future reference
  23572. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23573. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23574. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23575. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23576. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23577. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23578. this._rigCameras[0].parent = this;
  23579. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23580. //Right eye
  23581. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23582. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23583. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23584. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23585. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23586. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23587. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23588. this._rigCameras[1].parent = this;
  23589. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23590. if (Camera.UseAlternateWebVRRendering) {
  23591. this._rigCameras[1]._skipRendering = true;
  23592. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23593. }
  23594. }
  23595. break;
  23596. }
  23597. this._cascadePostProcessesToRigCams();
  23598. this.update();
  23599. };
  23600. Camera.prototype._getVRProjectionMatrix = function () {
  23601. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23602. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23603. return this._projectionMatrix;
  23604. };
  23605. Camera.prototype._updateCameraRotationMatrix = function () {
  23606. //Here for WebVR
  23607. };
  23608. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23609. //Here for WebVR
  23610. };
  23611. /**
  23612. * This function MUST be overwritten by the different WebVR cameras available.
  23613. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23614. */
  23615. Camera.prototype._getWebVRProjectionMatrix = function () {
  23616. return BABYLON.Matrix.Identity();
  23617. };
  23618. /**
  23619. * This function MUST be overwritten by the different WebVR cameras available.
  23620. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23621. */
  23622. Camera.prototype._getWebVRViewMatrix = function () {
  23623. return BABYLON.Matrix.Identity();
  23624. };
  23625. /** @hidden */
  23626. Camera.prototype.setCameraRigParameter = function (name, value) {
  23627. if (!this._cameraRigParams) {
  23628. this._cameraRigParams = {};
  23629. }
  23630. this._cameraRigParams[name] = value;
  23631. //provisionnally:
  23632. if (name === "interaxialDistance") {
  23633. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23634. }
  23635. };
  23636. /**
  23637. * needs to be overridden by children so sub has required properties to be copied
  23638. * @hidden
  23639. */
  23640. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23641. return null;
  23642. };
  23643. /**
  23644. * May need to be overridden by children
  23645. * @hidden
  23646. */
  23647. Camera.prototype._updateRigCameras = function () {
  23648. for (var i = 0; i < this._rigCameras.length; i++) {
  23649. this._rigCameras[i].minZ = this.minZ;
  23650. this._rigCameras[i].maxZ = this.maxZ;
  23651. this._rigCameras[i].fov = this.fov;
  23652. }
  23653. // only update viewport when ANAGLYPH
  23654. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23655. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23656. }
  23657. };
  23658. /** @hidden */
  23659. Camera.prototype._setupInputs = function () {
  23660. };
  23661. /**
  23662. * Serialiaze the camera setup to a json represention
  23663. * @returns the JSON representation
  23664. */
  23665. Camera.prototype.serialize = function () {
  23666. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23667. // Type
  23668. serializationObject.type = this.getClassName();
  23669. // Parent
  23670. if (this.parent) {
  23671. serializationObject.parentId = this.parent.id;
  23672. }
  23673. if (this.inputs) {
  23674. this.inputs.serialize(serializationObject);
  23675. }
  23676. // Animations
  23677. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23678. serializationObject.ranges = this.serializeAnimationRanges();
  23679. return serializationObject;
  23680. };
  23681. /**
  23682. * Clones the current camera.
  23683. * @param name The cloned camera name
  23684. * @returns the cloned camera
  23685. */
  23686. Camera.prototype.clone = function (name) {
  23687. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23688. };
  23689. /**
  23690. * Gets the direction of the camera relative to a given local axis.
  23691. * @param localAxis Defines the reference axis to provide a relative direction.
  23692. * @return the direction
  23693. */
  23694. Camera.prototype.getDirection = function (localAxis) {
  23695. var result = BABYLON.Vector3.Zero();
  23696. this.getDirectionToRef(localAxis, result);
  23697. return result;
  23698. };
  23699. /**
  23700. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23701. * @param localAxis Defines the reference axis to provide a relative direction.
  23702. * @param result Defines the vector to store the result in
  23703. */
  23704. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23705. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23706. };
  23707. /**
  23708. * Gets a camera constructor for a given camera type
  23709. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23710. * @param name The name of the camera the result will be able to instantiate
  23711. * @param scene The scene the result will construct the camera in
  23712. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23713. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23714. * @returns a factory method to construc the camera
  23715. */
  23716. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23717. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23718. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23719. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23720. interaxial_distance: interaxial_distance,
  23721. isStereoscopicSideBySide: isStereoscopicSideBySide
  23722. });
  23723. if (constructorFunc) {
  23724. return constructorFunc;
  23725. }
  23726. // Default to universal camera
  23727. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23728. };
  23729. /**
  23730. * Compute the world matrix of the camera.
  23731. * @returns the camera workd matrix
  23732. */
  23733. Camera.prototype.computeWorldMatrix = function () {
  23734. return this.getWorldMatrix();
  23735. };
  23736. /**
  23737. * Parse a JSON and creates the camera from the parsed information
  23738. * @param parsedCamera The JSON to parse
  23739. * @param scene The scene to instantiate the camera in
  23740. * @returns the newly constructed camera
  23741. */
  23742. Camera.Parse = function (parsedCamera, scene) {
  23743. var type = parsedCamera.type;
  23744. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23745. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23746. // Parent
  23747. if (parsedCamera.parentId) {
  23748. camera._waitingParentId = parsedCamera.parentId;
  23749. }
  23750. //If camera has an input manager, let it parse inputs settings
  23751. if (camera.inputs) {
  23752. camera.inputs.parse(parsedCamera);
  23753. camera._setupInputs();
  23754. }
  23755. if (camera.setPosition) { // need to force position
  23756. camera.position.copyFromFloats(0, 0, 0);
  23757. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23758. }
  23759. // Target
  23760. if (parsedCamera.target) {
  23761. if (camera.setTarget) {
  23762. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23763. }
  23764. }
  23765. // Apply 3d rig, when found
  23766. if (parsedCamera.cameraRigMode) {
  23767. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23768. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23769. }
  23770. // Animations
  23771. if (parsedCamera.animations) {
  23772. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23773. var parsedAnimation = parsedCamera.animations[animationIndex];
  23774. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23775. }
  23776. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23777. }
  23778. if (parsedCamera.autoAnimate) {
  23779. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23780. }
  23781. return camera;
  23782. };
  23783. /**
  23784. * This is the default projection mode used by the cameras.
  23785. * It helps recreating a feeling of perspective and better appreciate depth.
  23786. * This is the best way to simulate real life cameras.
  23787. */
  23788. Camera.PERSPECTIVE_CAMERA = 0;
  23789. /**
  23790. * This helps creating camera with an orthographic mode.
  23791. * 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.
  23792. */
  23793. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23794. /**
  23795. * This is the default FOV mode for perspective cameras.
  23796. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23797. */
  23798. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23799. /**
  23800. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23801. */
  23802. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23803. /**
  23804. * This specifies ther is no need for a camera rig.
  23805. * Basically only one eye is rendered corresponding to the camera.
  23806. */
  23807. Camera.RIG_MODE_NONE = 0;
  23808. /**
  23809. * Simulates a camera Rig with one blue eye and one red eye.
  23810. * This can be use with 3d blue and red glasses.
  23811. */
  23812. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23813. /**
  23814. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23815. */
  23816. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23817. /**
  23818. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23819. */
  23820. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23821. /**
  23822. * Defines that both eyes of the camera will be rendered over under each other.
  23823. */
  23824. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23825. /**
  23826. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23827. */
  23828. Camera.RIG_MODE_VR = 20;
  23829. /**
  23830. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23831. */
  23832. Camera.RIG_MODE_WEBVR = 21;
  23833. /**
  23834. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23835. */
  23836. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23837. /**
  23838. * @hidden
  23839. * Might be removed once multiview will be a thing
  23840. */
  23841. Camera.UseAlternateWebVRRendering = false;
  23842. __decorate([
  23843. BABYLON.serializeAsVector3()
  23844. ], Camera.prototype, "position", void 0);
  23845. __decorate([
  23846. BABYLON.serializeAsVector3()
  23847. ], Camera.prototype, "upVector", void 0);
  23848. __decorate([
  23849. BABYLON.serialize()
  23850. ], Camera.prototype, "orthoLeft", void 0);
  23851. __decorate([
  23852. BABYLON.serialize()
  23853. ], Camera.prototype, "orthoRight", void 0);
  23854. __decorate([
  23855. BABYLON.serialize()
  23856. ], Camera.prototype, "orthoBottom", void 0);
  23857. __decorate([
  23858. BABYLON.serialize()
  23859. ], Camera.prototype, "orthoTop", void 0);
  23860. __decorate([
  23861. BABYLON.serialize()
  23862. ], Camera.prototype, "fov", void 0);
  23863. __decorate([
  23864. BABYLON.serialize()
  23865. ], Camera.prototype, "minZ", void 0);
  23866. __decorate([
  23867. BABYLON.serialize()
  23868. ], Camera.prototype, "maxZ", void 0);
  23869. __decorate([
  23870. BABYLON.serialize()
  23871. ], Camera.prototype, "inertia", void 0);
  23872. __decorate([
  23873. BABYLON.serialize()
  23874. ], Camera.prototype, "mode", void 0);
  23875. __decorate([
  23876. BABYLON.serialize()
  23877. ], Camera.prototype, "layerMask", void 0);
  23878. __decorate([
  23879. BABYLON.serialize()
  23880. ], Camera.prototype, "fovMode", void 0);
  23881. __decorate([
  23882. BABYLON.serialize()
  23883. ], Camera.prototype, "cameraRigMode", void 0);
  23884. __decorate([
  23885. BABYLON.serialize()
  23886. ], Camera.prototype, "interaxialDistance", void 0);
  23887. __decorate([
  23888. BABYLON.serialize()
  23889. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23890. return Camera;
  23891. }(BABYLON.Node));
  23892. BABYLON.Camera = Camera;
  23893. })(BABYLON || (BABYLON = {}));
  23894. //# sourceMappingURL=babylon.camera.js.map
  23895. var BABYLON;
  23896. (function (BABYLON) {
  23897. /**
  23898. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23899. * It is enable to manage the different groups as well as the different necessary sort functions.
  23900. * This should not be used directly aside of the few static configurations
  23901. */
  23902. var RenderingManager = /** @class */ (function () {
  23903. /**
  23904. * Instantiates a new rendering group for a particular scene
  23905. * @param scene Defines the scene the groups belongs to
  23906. */
  23907. function RenderingManager(scene) {
  23908. /**
  23909. * @hidden
  23910. */
  23911. this._useSceneAutoClearSetup = false;
  23912. this._renderingGroups = new Array();
  23913. this._autoClearDepthStencil = {};
  23914. this._customOpaqueSortCompareFn = {};
  23915. this._customAlphaTestSortCompareFn = {};
  23916. this._customTransparentSortCompareFn = {};
  23917. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23918. this._scene = scene;
  23919. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23920. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23921. }
  23922. }
  23923. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23924. if (depth === void 0) { depth = true; }
  23925. if (stencil === void 0) { stencil = true; }
  23926. if (this._depthStencilBufferAlreadyCleaned) {
  23927. return;
  23928. }
  23929. this._scene.getEngine().clear(null, false, depth, stencil);
  23930. this._depthStencilBufferAlreadyCleaned = true;
  23931. };
  23932. /**
  23933. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23934. * @hidden
  23935. */
  23936. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23937. // Update the observable context (not null as it only goes away on dispose)
  23938. var info = this._renderingGroupInfo;
  23939. info.scene = this._scene;
  23940. info.camera = this._scene.activeCamera;
  23941. // Dispatch sprites
  23942. if (this._scene.spriteManagers && renderSprites) {
  23943. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23944. var manager = this._scene.spriteManagers[index];
  23945. this.dispatchSprites(manager);
  23946. }
  23947. }
  23948. // Render
  23949. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23950. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23951. var renderingGroup = this._renderingGroups[index];
  23952. if (!renderingGroup)
  23953. continue;
  23954. var renderingGroupMask = Math.pow(2, index);
  23955. info.renderingGroupId = index;
  23956. // Before Observable
  23957. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23958. // Clear depth/stencil if needed
  23959. if (RenderingManager.AUTOCLEAR) {
  23960. var autoClear = this._useSceneAutoClearSetup ?
  23961. this._scene.getAutoClearDepthStencilSetup(index) :
  23962. this._autoClearDepthStencil[index];
  23963. if (autoClear && autoClear.autoClear) {
  23964. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23965. }
  23966. }
  23967. // Render
  23968. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23969. var step = _a[_i];
  23970. step.action(index);
  23971. }
  23972. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23973. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23974. var step = _c[_b];
  23975. step.action(index);
  23976. }
  23977. // After Observable
  23978. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23979. }
  23980. };
  23981. /**
  23982. * Resets the different information of the group to prepare a new frame
  23983. * @hidden
  23984. */
  23985. RenderingManager.prototype.reset = function () {
  23986. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23987. var renderingGroup = this._renderingGroups[index];
  23988. if (renderingGroup) {
  23989. renderingGroup.prepare();
  23990. }
  23991. }
  23992. };
  23993. /**
  23994. * Dispose and release the group and its associated resources.
  23995. * @hidden
  23996. */
  23997. RenderingManager.prototype.dispose = function () {
  23998. this.freeRenderingGroups();
  23999. this._renderingGroups.length = 0;
  24000. this._renderingGroupInfo = null;
  24001. };
  24002. /**
  24003. * Clear the info related to rendering groups preventing retention points during dispose.
  24004. */
  24005. RenderingManager.prototype.freeRenderingGroups = function () {
  24006. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24007. var renderingGroup = this._renderingGroups[index];
  24008. if (renderingGroup) {
  24009. renderingGroup.dispose();
  24010. }
  24011. }
  24012. };
  24013. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24014. if (this._renderingGroups[renderingGroupId] === undefined) {
  24015. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24016. }
  24017. };
  24018. /**
  24019. * Add a sprite manager to the rendering manager in order to render it this frame.
  24020. * @param spriteManager Define the sprite manager to render
  24021. */
  24022. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24023. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24024. this._prepareRenderingGroup(renderingGroupId);
  24025. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24026. };
  24027. /**
  24028. * Add a particle system to the rendering manager in order to render it this frame.
  24029. * @param particleSystem Define the particle system to render
  24030. */
  24031. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24032. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24033. this._prepareRenderingGroup(renderingGroupId);
  24034. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24035. };
  24036. /**
  24037. * Add a submesh to the manager in order to render it this frame
  24038. * @param subMesh The submesh to dispatch
  24039. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24040. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24041. */
  24042. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24043. if (mesh === undefined) {
  24044. mesh = subMesh.getMesh();
  24045. }
  24046. var renderingGroupId = mesh.renderingGroupId || 0;
  24047. this._prepareRenderingGroup(renderingGroupId);
  24048. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24049. };
  24050. /**
  24051. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24052. * This allowed control for front to back rendering or reversly depending of the special needs.
  24053. *
  24054. * @param renderingGroupId The rendering group id corresponding to its index
  24055. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24056. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24057. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24058. */
  24059. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24060. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24061. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24062. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24063. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24064. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24065. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24066. if (this._renderingGroups[renderingGroupId]) {
  24067. var group = this._renderingGroups[renderingGroupId];
  24068. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24069. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24070. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24071. }
  24072. };
  24073. /**
  24074. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24075. *
  24076. * @param renderingGroupId The rendering group id corresponding to its index
  24077. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24078. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24079. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24080. */
  24081. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24082. if (depth === void 0) { depth = true; }
  24083. if (stencil === void 0) { stencil = true; }
  24084. this._autoClearDepthStencil[renderingGroupId] = {
  24085. autoClear: autoClearDepthStencil,
  24086. depth: depth,
  24087. stencil: stencil
  24088. };
  24089. };
  24090. /**
  24091. * Gets the current auto clear configuration for one rendering group of the rendering
  24092. * manager.
  24093. * @param index the rendering group index to get the information for
  24094. * @returns The auto clear setup for the requested rendering group
  24095. */
  24096. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24097. return this._autoClearDepthStencil[index];
  24098. };
  24099. /**
  24100. * The max id used for rendering groups (not included)
  24101. */
  24102. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24103. /**
  24104. * The min id used for rendering groups (included)
  24105. */
  24106. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24107. /**
  24108. * Used to globally prevent autoclearing scenes.
  24109. */
  24110. RenderingManager.AUTOCLEAR = true;
  24111. return RenderingManager;
  24112. }());
  24113. BABYLON.RenderingManager = RenderingManager;
  24114. })(BABYLON || (BABYLON = {}));
  24115. //# sourceMappingURL=babylon.renderingManager.js.map
  24116. var BABYLON;
  24117. (function (BABYLON) {
  24118. /**
  24119. * This represents the object necessary to create a rendering group.
  24120. * This is exclusively used and created by the rendering manager.
  24121. * To modify the behavior, you use the available helpers in your scene or meshes.
  24122. * @hidden
  24123. */
  24124. var RenderingGroup = /** @class */ (function () {
  24125. /**
  24126. * Creates a new rendering group.
  24127. * @param index The rendering group index
  24128. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24129. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24130. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24131. */
  24132. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24133. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24134. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24135. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24136. this.index = index;
  24137. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24138. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24139. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24140. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24141. this._particleSystems = new BABYLON.SmartArray(256);
  24142. this._spriteManagers = new BABYLON.SmartArray(256);
  24143. this._edgesRenderers = new BABYLON.SmartArray(16);
  24144. this._scene = scene;
  24145. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24146. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24147. this.transparentSortCompareFn = transparentSortCompareFn;
  24148. }
  24149. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24150. /**
  24151. * Set the opaque sort comparison function.
  24152. * If null the sub meshes will be render in the order they were created
  24153. */
  24154. set: function (value) {
  24155. this._opaqueSortCompareFn = value;
  24156. if (value) {
  24157. this._renderOpaque = this.renderOpaqueSorted;
  24158. }
  24159. else {
  24160. this._renderOpaque = RenderingGroup.renderUnsorted;
  24161. }
  24162. },
  24163. enumerable: true,
  24164. configurable: true
  24165. });
  24166. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24167. /**
  24168. * Set the alpha test sort comparison function.
  24169. * If null the sub meshes will be render in the order they were created
  24170. */
  24171. set: function (value) {
  24172. this._alphaTestSortCompareFn = value;
  24173. if (value) {
  24174. this._renderAlphaTest = this.renderAlphaTestSorted;
  24175. }
  24176. else {
  24177. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24178. }
  24179. },
  24180. enumerable: true,
  24181. configurable: true
  24182. });
  24183. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24184. /**
  24185. * Set the transparent sort comparison function.
  24186. * If null the sub meshes will be render in the order they were created
  24187. */
  24188. set: function (value) {
  24189. if (value) {
  24190. this._transparentSortCompareFn = value;
  24191. }
  24192. else {
  24193. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24194. }
  24195. this._renderTransparent = this.renderTransparentSorted;
  24196. },
  24197. enumerable: true,
  24198. configurable: true
  24199. });
  24200. /**
  24201. * Render all the sub meshes contained in the group.
  24202. * @param customRenderFunction Used to override the default render behaviour of the group.
  24203. * @returns true if rendered some submeshes.
  24204. */
  24205. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24206. if (customRenderFunction) {
  24207. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24208. return;
  24209. }
  24210. var engine = this._scene.getEngine();
  24211. // Depth only
  24212. if (this._depthOnlySubMeshes.length !== 0) {
  24213. engine.setColorWrite(false);
  24214. this._renderAlphaTest(this._depthOnlySubMeshes);
  24215. engine.setColorWrite(true);
  24216. }
  24217. // Opaque
  24218. if (this._opaqueSubMeshes.length !== 0) {
  24219. this._renderOpaque(this._opaqueSubMeshes);
  24220. }
  24221. // Alpha test
  24222. if (this._alphaTestSubMeshes.length !== 0) {
  24223. this._renderAlphaTest(this._alphaTestSubMeshes);
  24224. }
  24225. var stencilState = engine.getStencilBuffer();
  24226. engine.setStencilBuffer(false);
  24227. // Sprites
  24228. if (renderSprites) {
  24229. this._renderSprites();
  24230. }
  24231. // Particles
  24232. if (renderParticles) {
  24233. this._renderParticles(activeMeshes);
  24234. }
  24235. if (this.onBeforeTransparentRendering) {
  24236. this.onBeforeTransparentRendering();
  24237. }
  24238. // Transparent
  24239. if (this._transparentSubMeshes.length !== 0) {
  24240. this._renderTransparent(this._transparentSubMeshes);
  24241. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24242. }
  24243. // Set back stencil to false in case it changes before the edge renderer.
  24244. engine.setStencilBuffer(false);
  24245. // Edges
  24246. if (this._edgesRenderers.length) {
  24247. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24248. this._edgesRenderers.data[edgesRendererIndex].render();
  24249. }
  24250. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24251. }
  24252. // Restore Stencil state.
  24253. engine.setStencilBuffer(stencilState);
  24254. };
  24255. /**
  24256. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24257. * @param subMeshes The submeshes to render
  24258. */
  24259. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24260. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24261. };
  24262. /**
  24263. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24264. * @param subMeshes The submeshes to render
  24265. */
  24266. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24267. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24268. };
  24269. /**
  24270. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24271. * @param subMeshes The submeshes to render
  24272. */
  24273. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24274. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24275. };
  24276. /**
  24277. * Renders the submeshes in a specified order.
  24278. * @param subMeshes The submeshes to sort before render
  24279. * @param sortCompareFn The comparison function use to sort
  24280. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24281. * @param transparent Specifies to activate blending if true
  24282. */
  24283. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24284. var subIndex = 0;
  24285. var subMesh;
  24286. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24287. for (; subIndex < subMeshes.length; subIndex++) {
  24288. subMesh = subMeshes.data[subIndex];
  24289. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24290. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24291. }
  24292. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24293. if (sortCompareFn) {
  24294. sortedArray.sort(sortCompareFn);
  24295. }
  24296. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24297. subMesh = sortedArray[subIndex];
  24298. if (transparent) {
  24299. var material = subMesh.getMaterial();
  24300. if (material && material.needDepthPrePass) {
  24301. var engine = material.getScene().getEngine();
  24302. engine.setColorWrite(false);
  24303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24304. subMesh.render(false);
  24305. engine.setColorWrite(true);
  24306. }
  24307. }
  24308. subMesh.render(transparent);
  24309. }
  24310. };
  24311. /**
  24312. * Renders the submeshes in the order they were dispatched (no sort applied).
  24313. * @param subMeshes The submeshes to render
  24314. */
  24315. RenderingGroup.renderUnsorted = function (subMeshes) {
  24316. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24317. var submesh = subMeshes.data[subIndex];
  24318. submesh.render(false);
  24319. }
  24320. };
  24321. /**
  24322. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24323. * are rendered back to front if in the same alpha index.
  24324. *
  24325. * @param a The first submesh
  24326. * @param b The second submesh
  24327. * @returns The result of the comparison
  24328. */
  24329. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24330. // Alpha index first
  24331. if (a._alphaIndex > b._alphaIndex) {
  24332. return 1;
  24333. }
  24334. if (a._alphaIndex < b._alphaIndex) {
  24335. return -1;
  24336. }
  24337. // Then distance to camera
  24338. return RenderingGroup.backToFrontSortCompare(a, b);
  24339. };
  24340. /**
  24341. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24342. * are rendered back to front.
  24343. *
  24344. * @param a The first submesh
  24345. * @param b The second submesh
  24346. * @returns The result of the comparison
  24347. */
  24348. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24349. // Then distance to camera
  24350. if (a._distanceToCamera < b._distanceToCamera) {
  24351. return 1;
  24352. }
  24353. if (a._distanceToCamera > b._distanceToCamera) {
  24354. return -1;
  24355. }
  24356. return 0;
  24357. };
  24358. /**
  24359. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24360. * are rendered front to back (prevent overdraw).
  24361. *
  24362. * @param a The first submesh
  24363. * @param b The second submesh
  24364. * @returns The result of the comparison
  24365. */
  24366. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24367. // Then distance to camera
  24368. if (a._distanceToCamera < b._distanceToCamera) {
  24369. return -1;
  24370. }
  24371. if (a._distanceToCamera > b._distanceToCamera) {
  24372. return 1;
  24373. }
  24374. return 0;
  24375. };
  24376. /**
  24377. * Resets the different lists of submeshes to prepare a new frame.
  24378. */
  24379. RenderingGroup.prototype.prepare = function () {
  24380. this._opaqueSubMeshes.reset();
  24381. this._transparentSubMeshes.reset();
  24382. this._alphaTestSubMeshes.reset();
  24383. this._depthOnlySubMeshes.reset();
  24384. this._particleSystems.reset();
  24385. this._spriteManagers.reset();
  24386. this._edgesRenderers.reset();
  24387. };
  24388. RenderingGroup.prototype.dispose = function () {
  24389. this._opaqueSubMeshes.dispose();
  24390. this._transparentSubMeshes.dispose();
  24391. this._alphaTestSubMeshes.dispose();
  24392. this._depthOnlySubMeshes.dispose();
  24393. this._particleSystems.dispose();
  24394. this._spriteManagers.dispose();
  24395. this._edgesRenderers.dispose();
  24396. };
  24397. /**
  24398. * Inserts the submesh in its correct queue depending on its material.
  24399. * @param subMesh The submesh to dispatch
  24400. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24401. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24402. */
  24403. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24404. // Get mesh and materials if not provided
  24405. if (mesh === undefined) {
  24406. mesh = subMesh.getMesh();
  24407. }
  24408. if (material === undefined) {
  24409. material = subMesh.getMaterial();
  24410. }
  24411. if (material === null || material === undefined) {
  24412. return;
  24413. }
  24414. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24415. this._transparentSubMeshes.push(subMesh);
  24416. }
  24417. else if (material.needAlphaTesting()) { // Alpha test
  24418. if (material.needDepthPrePass) {
  24419. this._depthOnlySubMeshes.push(subMesh);
  24420. }
  24421. this._alphaTestSubMeshes.push(subMesh);
  24422. }
  24423. else {
  24424. if (material.needDepthPrePass) {
  24425. this._depthOnlySubMeshes.push(subMesh);
  24426. }
  24427. this._opaqueSubMeshes.push(subMesh); // Opaque
  24428. }
  24429. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24430. this._edgesRenderers.push(mesh._edgesRenderer);
  24431. }
  24432. };
  24433. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24434. this._spriteManagers.push(spriteManager);
  24435. };
  24436. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24437. this._particleSystems.push(particleSystem);
  24438. };
  24439. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24440. if (this._particleSystems.length === 0) {
  24441. return;
  24442. }
  24443. // Particles
  24444. var activeCamera = this._scene.activeCamera;
  24445. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24446. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24447. var particleSystem = this._particleSystems.data[particleIndex];
  24448. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24449. continue;
  24450. }
  24451. var emitter = particleSystem.emitter;
  24452. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24453. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24454. }
  24455. }
  24456. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24457. };
  24458. RenderingGroup.prototype._renderSprites = function () {
  24459. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24460. return;
  24461. }
  24462. // Sprites
  24463. var activeCamera = this._scene.activeCamera;
  24464. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24465. for (var id = 0; id < this._spriteManagers.length; id++) {
  24466. var spriteManager = this._spriteManagers.data[id];
  24467. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24468. spriteManager.render();
  24469. }
  24470. }
  24471. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24472. };
  24473. return RenderingGroup;
  24474. }());
  24475. BABYLON.RenderingGroup = RenderingGroup;
  24476. })(BABYLON || (BABYLON = {}));
  24477. //# sourceMappingURL=babylon.renderingGroup.js.map
  24478. var BABYLON;
  24479. (function (BABYLON) {
  24480. /**
  24481. * Groups all the scene component constants in one place to ease maintenance.
  24482. * @hidden
  24483. */
  24484. var SceneComponentConstants = /** @class */ (function () {
  24485. function SceneComponentConstants() {
  24486. }
  24487. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24488. SceneComponentConstants.NAME_LAYER = "Layer";
  24489. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24490. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24491. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24492. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24493. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24494. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24495. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24496. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24497. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24498. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24499. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24500. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24501. SceneComponentConstants.NAME_OCTREE = "Octree";
  24502. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24503. SceneComponentConstants.NAME_AUDIO = "Audio";
  24504. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24505. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24506. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24507. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24508. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24509. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24510. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24511. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24512. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24513. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24514. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24515. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24516. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24517. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24518. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24519. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24520. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24521. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24522. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24523. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24524. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24525. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24526. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24527. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24528. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24529. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24530. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24531. return SceneComponentConstants;
  24532. }());
  24533. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24534. /**
  24535. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24536. * @hidden
  24537. */
  24538. var Stage = /** @class */ (function (_super) {
  24539. __extends(Stage, _super);
  24540. /**
  24541. * Hide ctor from the rest of the world.
  24542. * @param items The items to add.
  24543. */
  24544. function Stage(items) {
  24545. return _super.apply(this, items) || this;
  24546. }
  24547. /**
  24548. * Creates a new Stage.
  24549. * @returns A new instance of a Stage
  24550. */
  24551. Stage.Create = function () {
  24552. return Object.create(Stage.prototype);
  24553. };
  24554. /**
  24555. * Registers a step in an ordered way in the targeted stage.
  24556. * @param index Defines the position to register the step in
  24557. * @param component Defines the component attached to the step
  24558. * @param action Defines the action to launch during the step
  24559. */
  24560. Stage.prototype.registerStep = function (index, component, action) {
  24561. var i = 0;
  24562. var maxIndex = Number.MAX_VALUE;
  24563. for (; i < this.length && i < maxIndex; i++) {
  24564. var step = this[i];
  24565. maxIndex = step.index;
  24566. }
  24567. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24568. };
  24569. /**
  24570. * Clears all the steps from the stage.
  24571. */
  24572. Stage.prototype.clear = function () {
  24573. this.length = 0;
  24574. };
  24575. return Stage;
  24576. }(Array));
  24577. BABYLON.Stage = Stage;
  24578. })(BABYLON || (BABYLON = {}));
  24579. //# sourceMappingURL=babylon.sceneComponent.js.map
  24580. var BABYLON;
  24581. (function (BABYLON) {
  24582. /**
  24583. * Base class of the scene acting as a container for the different elements composing a scene.
  24584. * This class is dynamically extended by the different components of the scene increasing
  24585. * flexibility and reducing coupling
  24586. */
  24587. var AbstractScene = /** @class */ (function () {
  24588. function AbstractScene() {
  24589. /**
  24590. * Gets the list of root nodes (ie. nodes with no parent)
  24591. */
  24592. this.rootNodes = new Array();
  24593. /** All of the cameras added to this scene
  24594. * @see http://doc.babylonjs.com/babylon101/cameras
  24595. */
  24596. this.cameras = new Array();
  24597. /**
  24598. * All of the lights added to this scene
  24599. * @see http://doc.babylonjs.com/babylon101/lights
  24600. */
  24601. this.lights = new Array();
  24602. /**
  24603. * All of the (abstract) meshes added to this scene
  24604. */
  24605. this.meshes = new Array();
  24606. /**
  24607. * The list of skeletons added to the scene
  24608. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24609. */
  24610. this.skeletons = new Array();
  24611. /**
  24612. * All of the particle systems added to this scene
  24613. * @see http://doc.babylonjs.com/babylon101/particles
  24614. */
  24615. this.particleSystems = new Array();
  24616. /**
  24617. * Gets a list of Animations associated with the scene
  24618. */
  24619. this.animations = [];
  24620. /**
  24621. * All of the animation groups added to this scene
  24622. * @see http://doc.babylonjs.com/how_to/group
  24623. */
  24624. this.animationGroups = new Array();
  24625. /**
  24626. * All of the multi-materials added to this scene
  24627. * @see http://doc.babylonjs.com/how_to/multi_materials
  24628. */
  24629. this.multiMaterials = new Array();
  24630. /**
  24631. * All of the materials added to this scene
  24632. * @see http://doc.babylonjs.com/babylon101/materials
  24633. */
  24634. this.materials = new Array();
  24635. /**
  24636. * The list of morph target managers added to the scene
  24637. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24638. */
  24639. this.morphTargetManagers = new Array();
  24640. /**
  24641. * The list of geometries used in the scene.
  24642. */
  24643. this.geometries = new Array();
  24644. /**
  24645. * All of the tranform nodes added to this scene
  24646. * @see http://doc.babylonjs.com/how_to/transformnode
  24647. */
  24648. this.transformNodes = new Array();
  24649. /**
  24650. * ActionManagers available on the scene.
  24651. */
  24652. this.actionManagers = new Array();
  24653. /**
  24654. * Textures to keep.
  24655. */
  24656. this.textures = new Array();
  24657. }
  24658. /**
  24659. * Adds a parser in the list of available ones
  24660. * @param name Defines the name of the parser
  24661. * @param parser Defines the parser to add
  24662. */
  24663. AbstractScene.AddParser = function (name, parser) {
  24664. this._BabylonFileParsers[name] = parser;
  24665. };
  24666. /**
  24667. * Gets a general parser from the list of avaialble ones
  24668. * @param name Defines the name of the parser
  24669. * @returns the requested parser or null
  24670. */
  24671. AbstractScene.GetParser = function (name) {
  24672. if (this._BabylonFileParsers[name]) {
  24673. return this._BabylonFileParsers[name];
  24674. }
  24675. return null;
  24676. };
  24677. /**
  24678. * Adds n individual parser in the list of available ones
  24679. * @param name Defines the name of the parser
  24680. * @param parser Defines the parser to add
  24681. */
  24682. AbstractScene.AddIndividualParser = function (name, parser) {
  24683. this._IndividualBabylonFileParsers[name] = parser;
  24684. };
  24685. /**
  24686. * Gets an individual parser from the list of avaialble ones
  24687. * @param name Defines the name of the parser
  24688. * @returns the requested parser or null
  24689. */
  24690. AbstractScene.GetIndividualParser = function (name) {
  24691. if (this._IndividualBabylonFileParsers[name]) {
  24692. return this._IndividualBabylonFileParsers[name];
  24693. }
  24694. return null;
  24695. };
  24696. /**
  24697. * Parser json data and populate both a scene and its associated container object
  24698. * @param jsonData Defines the data to parse
  24699. * @param scene Defines the scene to parse the data for
  24700. * @param container Defines the container attached to the parsing sequence
  24701. * @param rootUrl Defines the root url of the data
  24702. */
  24703. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24704. for (var parserName in this._BabylonFileParsers) {
  24705. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24706. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24707. }
  24708. }
  24709. };
  24710. /**
  24711. * Stores the list of available parsers in the application.
  24712. */
  24713. AbstractScene._BabylonFileParsers = {};
  24714. /**
  24715. * Stores the list of available individual parsers in the application.
  24716. */
  24717. AbstractScene._IndividualBabylonFileParsers = {};
  24718. return AbstractScene;
  24719. }());
  24720. BABYLON.AbstractScene = AbstractScene;
  24721. })(BABYLON || (BABYLON = {}));
  24722. //# sourceMappingURL=babylon.abstractScene.js.map
  24723. var BABYLON;
  24724. (function (BABYLON) {
  24725. /** @hidden */
  24726. var ClickInfo = /** @class */ (function () {
  24727. function ClickInfo() {
  24728. this._singleClick = false;
  24729. this._doubleClick = false;
  24730. this._hasSwiped = false;
  24731. this._ignore = false;
  24732. }
  24733. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24734. get: function () {
  24735. return this._singleClick;
  24736. },
  24737. set: function (b) {
  24738. this._singleClick = b;
  24739. },
  24740. enumerable: true,
  24741. configurable: true
  24742. });
  24743. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24744. get: function () {
  24745. return this._doubleClick;
  24746. },
  24747. set: function (b) {
  24748. this._doubleClick = b;
  24749. },
  24750. enumerable: true,
  24751. configurable: true
  24752. });
  24753. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24754. get: function () {
  24755. return this._hasSwiped;
  24756. },
  24757. set: function (b) {
  24758. this._hasSwiped = b;
  24759. },
  24760. enumerable: true,
  24761. configurable: true
  24762. });
  24763. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24764. get: function () {
  24765. return this._ignore;
  24766. },
  24767. set: function (b) {
  24768. this._ignore = b;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. return ClickInfo;
  24774. }());
  24775. /**
  24776. * This class is used by the onRenderingGroupObservable
  24777. */
  24778. var RenderingGroupInfo = /** @class */ (function () {
  24779. function RenderingGroupInfo() {
  24780. }
  24781. return RenderingGroupInfo;
  24782. }());
  24783. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24784. /**
  24785. * Represents a scene to be rendered by the engine.
  24786. * @see http://doc.babylonjs.com/features/scene
  24787. */
  24788. var Scene = /** @class */ (function (_super) {
  24789. __extends(Scene, _super);
  24790. /**
  24791. * Creates a new Scene
  24792. * @param engine defines the engine to use to render this scene
  24793. */
  24794. function Scene(engine) {
  24795. var _this = _super.call(this) || this;
  24796. // Members
  24797. /**
  24798. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24799. */
  24800. _this.autoClear = true;
  24801. /**
  24802. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24803. */
  24804. _this.autoClearDepthAndStencil = true;
  24805. /**
  24806. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24807. */
  24808. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24809. /**
  24810. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24811. */
  24812. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24813. _this._forceWireframe = false;
  24814. _this._forcePointsCloud = false;
  24815. /**
  24816. * Gets or sets a boolean indicating if animations are enabled
  24817. */
  24818. _this.animationsEnabled = true;
  24819. _this._animationPropertiesOverride = null;
  24820. /**
  24821. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24822. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24823. */
  24824. _this.useConstantAnimationDeltaTime = false;
  24825. /**
  24826. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24827. * Please note that it requires to run a ray cast through the scene on every frame
  24828. */
  24829. _this.constantlyUpdateMeshUnderPointer = false;
  24830. /**
  24831. * Defines the HTML cursor to use when hovering over interactive elements
  24832. */
  24833. _this.hoverCursor = "pointer";
  24834. /**
  24835. * Defines the HTML default cursor to use (empty by default)
  24836. */
  24837. _this.defaultCursor = "";
  24838. /**
  24839. * This is used to call preventDefault() on pointer down
  24840. * in order to block unwanted artifacts like system double clicks
  24841. */
  24842. _this.preventDefaultOnPointerDown = true;
  24843. // Metadata
  24844. /**
  24845. * Gets or sets user defined metadata
  24846. */
  24847. _this.metadata = null;
  24848. /**
  24849. * Use this array to add regular expressions used to disable offline support for specific urls
  24850. */
  24851. _this.disableOfflineSupportExceptionRules = new Array();
  24852. /**
  24853. * An event triggered when the scene is disposed.
  24854. */
  24855. _this.onDisposeObservable = new BABYLON.Observable();
  24856. _this._onDisposeObserver = null;
  24857. /**
  24858. * An event triggered before rendering the scene (right after animations and physics)
  24859. */
  24860. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24861. _this._onBeforeRenderObserver = null;
  24862. /**
  24863. * An event triggered after rendering the scene
  24864. */
  24865. _this.onAfterRenderObservable = new BABYLON.Observable();
  24866. _this._onAfterRenderObserver = null;
  24867. /**
  24868. * An event triggered before animating the scene
  24869. */
  24870. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24871. /**
  24872. * An event triggered after animations processing
  24873. */
  24874. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24875. /**
  24876. * An event triggered before draw calls are ready to be sent
  24877. */
  24878. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24879. /**
  24880. * An event triggered after draw calls have been sent
  24881. */
  24882. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24883. /**
  24884. * An event triggered when the scene is ready
  24885. */
  24886. _this.onReadyObservable = new BABYLON.Observable();
  24887. /**
  24888. * An event triggered before rendering a camera
  24889. */
  24890. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24891. _this._onBeforeCameraRenderObserver = null;
  24892. /**
  24893. * An event triggered after rendering a camera
  24894. */
  24895. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24896. _this._onAfterCameraRenderObserver = null;
  24897. /**
  24898. * An event triggered when active meshes evaluation is about to start
  24899. */
  24900. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24901. /**
  24902. * An event triggered when active meshes evaluation is done
  24903. */
  24904. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24905. /**
  24906. * An event triggered when particles rendering is about to start
  24907. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24908. */
  24909. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24910. /**
  24911. * An event triggered when particles rendering is done
  24912. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24913. */
  24914. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24915. /**
  24916. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24917. */
  24918. _this.onDataLoadedObservable = new BABYLON.Observable();
  24919. /**
  24920. * An event triggered when a camera is created
  24921. */
  24922. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24923. /**
  24924. * An event triggered when a camera is removed
  24925. */
  24926. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24927. /**
  24928. * An event triggered when a light is created
  24929. */
  24930. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24931. /**
  24932. * An event triggered when a light is removed
  24933. */
  24934. _this.onLightRemovedObservable = new BABYLON.Observable();
  24935. /**
  24936. * An event triggered when a geometry is created
  24937. */
  24938. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24939. /**
  24940. * An event triggered when a geometry is removed
  24941. */
  24942. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24943. /**
  24944. * An event triggered when a transform node is created
  24945. */
  24946. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24947. /**
  24948. * An event triggered when a transform node is removed
  24949. */
  24950. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24951. /**
  24952. * An event triggered when a mesh is created
  24953. */
  24954. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24955. /**
  24956. * An event triggered when a mesh is removed
  24957. */
  24958. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24959. /**
  24960. * An event triggered when a material is created
  24961. */
  24962. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24963. /**
  24964. * An event triggered when a material is removed
  24965. */
  24966. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24967. /**
  24968. * An event triggered when a texture is created
  24969. */
  24970. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24971. /**
  24972. * An event triggered when a texture is removed
  24973. */
  24974. _this.onTextureRemovedObservable = new BABYLON.Observable();
  24975. /**
  24976. * An event triggered when render targets are about to be rendered
  24977. * Can happen multiple times per frame.
  24978. */
  24979. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24980. /**
  24981. * An event triggered when render targets were rendered.
  24982. * Can happen multiple times per frame.
  24983. */
  24984. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24985. /**
  24986. * An event triggered before calculating deterministic simulation step
  24987. */
  24988. _this.onBeforeStepObservable = new BABYLON.Observable();
  24989. /**
  24990. * An event triggered after calculating deterministic simulation step
  24991. */
  24992. _this.onAfterStepObservable = new BABYLON.Observable();
  24993. /**
  24994. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24995. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24996. * 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)
  24997. */
  24998. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24999. /**
  25000. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25001. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25002. * 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)
  25003. */
  25004. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25005. /**
  25006. * This Observable will when a mesh has been imported into the scene.
  25007. */
  25008. _this.onMeshImportedObservable = new BABYLON.Observable();
  25009. // Animations
  25010. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25011. /**
  25012. * 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).
  25013. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25014. */
  25015. _this.onPrePointerObservable = new BABYLON.Observable();
  25016. /**
  25017. * Observable event triggered each time an input event is received from the rendering canvas
  25018. */
  25019. _this.onPointerObservable = new BABYLON.Observable();
  25020. _this._meshPickProceed = false;
  25021. _this._currentPickResult = null;
  25022. _this._previousPickResult = null;
  25023. _this._totalPointersPressed = 0;
  25024. _this._doubleClickOccured = false;
  25025. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25026. _this.cameraToUseForPointers = null;
  25027. _this._pointerX = 0;
  25028. _this._pointerY = 0;
  25029. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25030. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25031. _this._startingPointerTime = 0;
  25032. _this._previousStartingPointerTime = 0;
  25033. _this._pointerCaptures = {};
  25034. // Deterministic lockstep
  25035. _this._timeAccumulator = 0;
  25036. _this._currentStepId = 0;
  25037. _this._currentInternalStep = 0;
  25038. // Keyboard
  25039. /**
  25040. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25041. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25042. */
  25043. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25044. /**
  25045. * Observable event triggered each time an keyboard event is received from the hosting window
  25046. */
  25047. _this.onKeyboardObservable = new BABYLON.Observable();
  25048. // Coordinates system
  25049. _this._useRightHandedSystem = false;
  25050. // Fog
  25051. _this._fogEnabled = true;
  25052. _this._fogMode = Scene.FOGMODE_NONE;
  25053. /**
  25054. * Gets or sets the fog color to use
  25055. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25056. * (Default is Color3(0.2, 0.2, 0.3))
  25057. */
  25058. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25059. /**
  25060. * Gets or sets the fog density to use
  25061. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25062. * (Default is 0.1)
  25063. */
  25064. _this.fogDensity = 0.1;
  25065. /**
  25066. * Gets or sets the fog start distance to use
  25067. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25068. * (Default is 0)
  25069. */
  25070. _this.fogStart = 0;
  25071. /**
  25072. * Gets or sets the fog end distance to use
  25073. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25074. * (Default is 1000)
  25075. */
  25076. _this.fogEnd = 1000.0;
  25077. // Lights
  25078. _this._shadowsEnabled = true;
  25079. _this._lightsEnabled = true;
  25080. /** All of the active cameras added to this scene. */
  25081. _this.activeCameras = new Array();
  25082. // Textures
  25083. _this._texturesEnabled = true;
  25084. // Particles
  25085. /**
  25086. * Gets or sets a boolean indicating if particles are enabled on this scene
  25087. */
  25088. _this.particlesEnabled = true;
  25089. // Sprites
  25090. /**
  25091. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25092. */
  25093. _this.spritesEnabled = true;
  25094. // Skeletons
  25095. _this._skeletonsEnabled = true;
  25096. // Lens flares
  25097. /**
  25098. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25099. */
  25100. _this.lensFlaresEnabled = true;
  25101. // Collisions
  25102. /**
  25103. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25104. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25105. */
  25106. _this.collisionsEnabled = true;
  25107. /**
  25108. * Defines the gravity applied to this scene (used only for collisions)
  25109. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25110. */
  25111. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25112. // Postprocesses
  25113. /**
  25114. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25115. */
  25116. _this.postProcessesEnabled = true;
  25117. /**
  25118. * The list of postprocesses added to the scene
  25119. */
  25120. _this.postProcesses = new Array();
  25121. // Customs render targets
  25122. /**
  25123. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25124. */
  25125. _this.renderTargetsEnabled = true;
  25126. /**
  25127. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25128. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25129. */
  25130. _this.dumpNextRenderTargets = false;
  25131. /**
  25132. * The list of user defined render targets added to the scene
  25133. */
  25134. _this.customRenderTargets = new Array();
  25135. /**
  25136. * Gets the list of meshes imported to the scene through SceneLoader
  25137. */
  25138. _this.importedMeshesFiles = new Array();
  25139. // Probes
  25140. /**
  25141. * Gets or sets a boolean indicating if probes are enabled on this scene
  25142. */
  25143. _this.probesEnabled = true;
  25144. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25145. // Procedural textures
  25146. /**
  25147. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25148. */
  25149. _this.proceduralTexturesEnabled = true;
  25150. // Performance counters
  25151. _this._totalVertices = new BABYLON.PerfCounter();
  25152. /** @hidden */
  25153. _this._activeIndices = new BABYLON.PerfCounter();
  25154. /** @hidden */
  25155. _this._activeParticles = new BABYLON.PerfCounter();
  25156. /** @hidden */
  25157. _this._activeBones = new BABYLON.PerfCounter();
  25158. _this._animationTime = 0;
  25159. /**
  25160. * Gets or sets a general scale for animation speed
  25161. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25162. */
  25163. _this.animationTimeScale = 1;
  25164. _this._renderId = 0;
  25165. _this._frameId = 0;
  25166. _this._executeWhenReadyTimeoutId = -1;
  25167. _this._intermediateRendering = false;
  25168. _this._viewUpdateFlag = -1;
  25169. _this._projectionUpdateFlag = -1;
  25170. _this._alternateViewUpdateFlag = -1;
  25171. _this._alternateProjectionUpdateFlag = -1;
  25172. /** @hidden */
  25173. _this._toBeDisposed = new Array(256);
  25174. _this._activeRequests = new Array();
  25175. _this._pendingData = new Array();
  25176. _this._isDisposed = false;
  25177. /**
  25178. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25179. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25180. */
  25181. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25182. _this._activeMeshes = new BABYLON.SmartArray(256);
  25183. _this._processedMaterials = new BABYLON.SmartArray(256);
  25184. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25185. /** @hidden */
  25186. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25187. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25188. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25189. /** @hidden */
  25190. _this._activeAnimatables = new Array();
  25191. _this._transformMatrix = BABYLON.Matrix.Zero();
  25192. _this._useAlternateCameraConfiguration = false;
  25193. _this._alternateRendering = false;
  25194. /**
  25195. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25196. * This is useful if there are more lights that the maximum simulteanous authorized
  25197. */
  25198. _this.requireLightSorting = false;
  25199. /**
  25200. * @hidden
  25201. * Backing store of defined scene components.
  25202. */
  25203. _this._components = [];
  25204. /**
  25205. * @hidden
  25206. * Backing store of defined scene components.
  25207. */
  25208. _this._serializableComponents = [];
  25209. /**
  25210. * List of components to register on the next registration step.
  25211. */
  25212. _this._transientComponents = [];
  25213. /**
  25214. * @hidden
  25215. * Defines the actions happening before camera updates.
  25216. */
  25217. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25218. /**
  25219. * @hidden
  25220. * Defines the actions happening before clear the canvas.
  25221. */
  25222. _this._beforeClearStage = BABYLON.Stage.Create();
  25223. /**
  25224. * @hidden
  25225. * Defines the actions when collecting render targets for the frame.
  25226. */
  25227. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25228. /**
  25229. * @hidden
  25230. * Defines the actions happening for one camera in the frame.
  25231. */
  25232. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25233. /**
  25234. * @hidden
  25235. * Defines the actions happening during the per mesh ready checks.
  25236. */
  25237. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25238. /**
  25239. * @hidden
  25240. * Defines the actions happening before evaluate active mesh checks.
  25241. */
  25242. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25243. /**
  25244. * @hidden
  25245. * Defines the actions happening during the evaluate sub mesh checks.
  25246. */
  25247. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25248. /**
  25249. * @hidden
  25250. * Defines the actions happening during the active mesh stage.
  25251. */
  25252. _this._activeMeshStage = BABYLON.Stage.Create();
  25253. /**
  25254. * @hidden
  25255. * Defines the actions happening during the per camera render target step.
  25256. */
  25257. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25258. /**
  25259. * @hidden
  25260. * Defines the actions happening just before the active camera is drawing.
  25261. */
  25262. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25263. /**
  25264. * @hidden
  25265. * Defines the actions happening just before a rendering group is drawing.
  25266. */
  25267. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25268. /**
  25269. * @hidden
  25270. * Defines the actions happening just before a mesh is drawing.
  25271. */
  25272. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25273. /**
  25274. * @hidden
  25275. * Defines the actions happening just after a mesh has been drawn.
  25276. */
  25277. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25278. /**
  25279. * @hidden
  25280. * Defines the actions happening just after a rendering group has been drawn.
  25281. */
  25282. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25283. /**
  25284. * @hidden
  25285. * Defines the actions happening just after the active camera has been drawn.
  25286. */
  25287. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25288. /**
  25289. * @hidden
  25290. * Defines the actions happening just after rendering all cameras and computing intersections.
  25291. */
  25292. _this._afterRenderStage = BABYLON.Stage.Create();
  25293. /**
  25294. * @hidden
  25295. * Defines the actions happening when a pointer move event happens.
  25296. */
  25297. _this._pointerMoveStage = BABYLON.Stage.Create();
  25298. /**
  25299. * @hidden
  25300. * Defines the actions happening when a pointer down event happens.
  25301. */
  25302. _this._pointerDownStage = BABYLON.Stage.Create();
  25303. /**
  25304. * @hidden
  25305. * Defines the actions happening when a pointer up event happens.
  25306. */
  25307. _this._pointerUpStage = BABYLON.Stage.Create();
  25308. _this._defaultMeshCandidates = {
  25309. data: [],
  25310. length: 0
  25311. };
  25312. _this._defaultSubMeshCandidates = {
  25313. data: [],
  25314. length: 0
  25315. };
  25316. _this._activeMeshesFrozen = false;
  25317. /** @hidden */
  25318. _this._allowPostProcessClearColor = true;
  25319. /**
  25320. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25321. */
  25322. _this.getDeterministicFrameTime = function () {
  25323. return 1000.0 / 60.0; // frame time in ms
  25324. };
  25325. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25326. _this._blockMaterialDirtyMechanism = false;
  25327. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25328. _this._engine.scenes.push(_this);
  25329. _this._uid = null;
  25330. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25331. if (BABYLON.PostProcessManager) {
  25332. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25333. }
  25334. if (BABYLON.Tools.IsWindowObjectExist()) {
  25335. _this.attachControl();
  25336. }
  25337. //collision coordinator initialization. For now legacy per default.
  25338. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25339. // Uniform Buffer
  25340. _this._createUbo();
  25341. // Default Image processing definition
  25342. if (BABYLON.ImageProcessingConfiguration) {
  25343. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25344. }
  25345. _this.setDefaultCandidateProviders();
  25346. return _this;
  25347. }
  25348. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25349. /**
  25350. * Texture used in all pbr material as the reflection texture.
  25351. * As in the majority of the scene they are the same (exception for multi room and so on),
  25352. * this is easier to reference from here than from all the materials.
  25353. */
  25354. get: function () {
  25355. return this._environmentTexture;
  25356. },
  25357. /**
  25358. * Texture used in all pbr material as the reflection texture.
  25359. * As in the majority of the scene they are the same (exception for multi room and so on),
  25360. * this is easier to set here than in all the materials.
  25361. */
  25362. set: function (value) {
  25363. if (this._environmentTexture === value) {
  25364. return;
  25365. }
  25366. this._environmentTexture = value;
  25367. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25368. },
  25369. enumerable: true,
  25370. configurable: true
  25371. });
  25372. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25373. /**
  25374. * Default image processing configuration used either in the rendering
  25375. * Forward main pass or through the imageProcessingPostProcess if present.
  25376. * As in the majority of the scene they are the same (exception for multi camera),
  25377. * this is easier to reference from here than from all the materials and post process.
  25378. *
  25379. * No setter as we it is a shared configuration, you can set the values instead.
  25380. */
  25381. get: function () {
  25382. return this._imageProcessingConfiguration;
  25383. },
  25384. enumerable: true,
  25385. configurable: true
  25386. });
  25387. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25388. get: function () {
  25389. return this._forceWireframe;
  25390. },
  25391. /**
  25392. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25393. */
  25394. set: function (value) {
  25395. if (this._forceWireframe === value) {
  25396. return;
  25397. }
  25398. this._forceWireframe = value;
  25399. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25400. },
  25401. enumerable: true,
  25402. configurable: true
  25403. });
  25404. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25405. get: function () {
  25406. return this._forcePointsCloud;
  25407. },
  25408. /**
  25409. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25410. */
  25411. set: function (value) {
  25412. if (this._forcePointsCloud === value) {
  25413. return;
  25414. }
  25415. this._forcePointsCloud = value;
  25416. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25422. /**
  25423. * Gets or sets the animation properties override
  25424. */
  25425. get: function () {
  25426. return this._animationPropertiesOverride;
  25427. },
  25428. set: function (value) {
  25429. this._animationPropertiesOverride = value;
  25430. },
  25431. enumerable: true,
  25432. configurable: true
  25433. });
  25434. Object.defineProperty(Scene.prototype, "onDispose", {
  25435. /** Sets a function to be executed when this scene is disposed. */
  25436. set: function (callback) {
  25437. if (this._onDisposeObserver) {
  25438. this.onDisposeObservable.remove(this._onDisposeObserver);
  25439. }
  25440. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25441. },
  25442. enumerable: true,
  25443. configurable: true
  25444. });
  25445. Object.defineProperty(Scene.prototype, "beforeRender", {
  25446. /** Sets a function to be executed before rendering this scene */
  25447. set: function (callback) {
  25448. if (this._onBeforeRenderObserver) {
  25449. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25450. }
  25451. if (callback) {
  25452. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25453. }
  25454. },
  25455. enumerable: true,
  25456. configurable: true
  25457. });
  25458. Object.defineProperty(Scene.prototype, "afterRender", {
  25459. /** Sets a function to be executed after rendering this scene */
  25460. set: function (callback) {
  25461. if (this._onAfterRenderObserver) {
  25462. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25463. }
  25464. if (callback) {
  25465. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25466. }
  25467. },
  25468. enumerable: true,
  25469. configurable: true
  25470. });
  25471. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25472. /** Sets a function to be executed before rendering a camera*/
  25473. set: function (callback) {
  25474. if (this._onBeforeCameraRenderObserver) {
  25475. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25476. }
  25477. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25478. },
  25479. enumerable: true,
  25480. configurable: true
  25481. });
  25482. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25483. /** Sets a function to be executed after rendering a camera*/
  25484. set: function (callback) {
  25485. if (this._onAfterCameraRenderObserver) {
  25486. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25487. }
  25488. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25489. },
  25490. enumerable: true,
  25491. configurable: true
  25492. });
  25493. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25494. /**
  25495. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25496. */
  25497. get: function () {
  25498. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25499. },
  25500. enumerable: true,
  25501. configurable: true
  25502. });
  25503. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25504. get: function () {
  25505. return this._useRightHandedSystem;
  25506. },
  25507. /**
  25508. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25509. */
  25510. set: function (value) {
  25511. if (this._useRightHandedSystem === value) {
  25512. return;
  25513. }
  25514. this._useRightHandedSystem = value;
  25515. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25516. },
  25517. enumerable: true,
  25518. configurable: true
  25519. });
  25520. /**
  25521. * Sets the step Id used by deterministic lock step
  25522. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25523. * @param newStepId defines the step Id
  25524. */
  25525. Scene.prototype.setStepId = function (newStepId) {
  25526. this._currentStepId = newStepId;
  25527. };
  25528. ;
  25529. /**
  25530. * Gets the step Id used by deterministic lock step
  25531. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25532. * @returns the step Id
  25533. */
  25534. Scene.prototype.getStepId = function () {
  25535. return this._currentStepId;
  25536. };
  25537. ;
  25538. /**
  25539. * Gets the internal step used by deterministic lock step
  25540. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25541. * @returns the internal step
  25542. */
  25543. Scene.prototype.getInternalStep = function () {
  25544. return this._currentInternalStep;
  25545. };
  25546. ;
  25547. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25548. get: function () {
  25549. return this._fogEnabled;
  25550. },
  25551. /**
  25552. * Gets or sets a boolean indicating if fog is enabled on this scene
  25553. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25554. * (Default is true)
  25555. */
  25556. set: function (value) {
  25557. if (this._fogEnabled === value) {
  25558. return;
  25559. }
  25560. this._fogEnabled = value;
  25561. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25562. },
  25563. enumerable: true,
  25564. configurable: true
  25565. });
  25566. Object.defineProperty(Scene.prototype, "fogMode", {
  25567. get: function () {
  25568. return this._fogMode;
  25569. },
  25570. /**
  25571. * Gets or sets the fog mode to use
  25572. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25573. * | mode | value |
  25574. * | --- | --- |
  25575. * | FOGMODE_NONE | 0 |
  25576. * | FOGMODE_EXP | 1 |
  25577. * | FOGMODE_EXP2 | 2 |
  25578. * | FOGMODE_LINEAR | 3 |
  25579. */
  25580. set: function (value) {
  25581. if (this._fogMode === value) {
  25582. return;
  25583. }
  25584. this._fogMode = value;
  25585. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25586. },
  25587. enumerable: true,
  25588. configurable: true
  25589. });
  25590. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25591. get: function () {
  25592. return this._shadowsEnabled;
  25593. },
  25594. /**
  25595. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25596. */
  25597. set: function (value) {
  25598. if (this._shadowsEnabled === value) {
  25599. return;
  25600. }
  25601. this._shadowsEnabled = value;
  25602. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25603. },
  25604. enumerable: true,
  25605. configurable: true
  25606. });
  25607. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25608. get: function () {
  25609. return this._lightsEnabled;
  25610. },
  25611. /**
  25612. * Gets or sets a boolean indicating if lights are enabled on this scene
  25613. */
  25614. set: function (value) {
  25615. if (this._lightsEnabled === value) {
  25616. return;
  25617. }
  25618. this._lightsEnabled = value;
  25619. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25620. },
  25621. enumerable: true,
  25622. configurable: true
  25623. });
  25624. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25625. /** The default material used on meshes when no material is affected */
  25626. get: function () {
  25627. if (!this._defaultMaterial) {
  25628. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25629. }
  25630. return this._defaultMaterial;
  25631. },
  25632. /** The default material used on meshes when no material is affected */
  25633. set: function (value) {
  25634. this._defaultMaterial = value;
  25635. },
  25636. enumerable: true,
  25637. configurable: true
  25638. });
  25639. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25640. get: function () {
  25641. return this._texturesEnabled;
  25642. },
  25643. /**
  25644. * Gets or sets a boolean indicating if textures are enabled on this scene
  25645. */
  25646. set: function (value) {
  25647. if (this._texturesEnabled === value) {
  25648. return;
  25649. }
  25650. this._texturesEnabled = value;
  25651. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25652. },
  25653. enumerable: true,
  25654. configurable: true
  25655. });
  25656. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25657. get: function () {
  25658. return this._skeletonsEnabled;
  25659. },
  25660. /**
  25661. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25662. */
  25663. set: function (value) {
  25664. if (this._skeletonsEnabled === value) {
  25665. return;
  25666. }
  25667. this._skeletonsEnabled = value;
  25668. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25669. },
  25670. enumerable: true,
  25671. configurable: true
  25672. });
  25673. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25674. /** @hidden */
  25675. get: function () {
  25676. return this._alternateRendering;
  25677. },
  25678. enumerable: true,
  25679. configurable: true
  25680. });
  25681. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25682. /**
  25683. * Gets the list of frustum planes (built from the active camera)
  25684. */
  25685. get: function () {
  25686. return this._frustumPlanes;
  25687. },
  25688. enumerable: true,
  25689. configurable: true
  25690. });
  25691. /**
  25692. * Registers the transient components if needed.
  25693. */
  25694. Scene.prototype._registerTransientComponents = function () {
  25695. // Register components that have been associated lately to the scene.
  25696. if (this._transientComponents.length > 0) {
  25697. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25698. var component = _a[_i];
  25699. component.register();
  25700. }
  25701. this._transientComponents = [];
  25702. }
  25703. };
  25704. /**
  25705. * @hidden
  25706. * Add a component to the scene.
  25707. * Note that the ccomponent could be registered on th next frame if this is called after
  25708. * the register component stage.
  25709. * @param component Defines the component to add to the scene
  25710. */
  25711. Scene.prototype._addComponent = function (component) {
  25712. this._components.push(component);
  25713. this._transientComponents.push(component);
  25714. var serializableComponent = component;
  25715. if (serializableComponent.addFromContainer) {
  25716. this._serializableComponents.push(serializableComponent);
  25717. }
  25718. };
  25719. /**
  25720. * @hidden
  25721. * Gets a component from the scene.
  25722. * @param name defines the name of the component to retrieve
  25723. * @returns the component or null if not present
  25724. */
  25725. Scene.prototype._getComponent = function (name) {
  25726. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25727. var component = _a[_i];
  25728. if (component.name === name) {
  25729. return component;
  25730. }
  25731. }
  25732. return null;
  25733. };
  25734. /**
  25735. * @hidden
  25736. */
  25737. Scene.prototype._getDefaultMeshCandidates = function () {
  25738. this._defaultMeshCandidates.data = this.meshes;
  25739. this._defaultMeshCandidates.length = this.meshes.length;
  25740. return this._defaultMeshCandidates;
  25741. };
  25742. /**
  25743. * @hidden
  25744. */
  25745. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25746. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25747. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25748. return this._defaultSubMeshCandidates;
  25749. };
  25750. /**
  25751. * Sets the default candidate providers for the scene.
  25752. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25753. * and getCollidingSubMeshCandidates to their default function
  25754. */
  25755. Scene.prototype.setDefaultCandidateProviders = function () {
  25756. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25757. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25758. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25759. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25760. };
  25761. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25762. /**
  25763. * Gets a boolean indicating if collisions are processed on a web worker
  25764. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25765. */
  25766. get: function () {
  25767. return this._workerCollisions;
  25768. },
  25769. set: function (enabled) {
  25770. if (!BABYLON.CollisionCoordinatorLegacy) {
  25771. return;
  25772. }
  25773. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25774. this._workerCollisions = enabled;
  25775. if (this.collisionCoordinator) {
  25776. this.collisionCoordinator.destroy();
  25777. }
  25778. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25779. this.collisionCoordinator.init(this);
  25780. },
  25781. enumerable: true,
  25782. configurable: true
  25783. });
  25784. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25785. /**
  25786. * Gets the mesh that is currently under the pointer
  25787. */
  25788. get: function () {
  25789. return this._pointerOverMesh;
  25790. },
  25791. enumerable: true,
  25792. configurable: true
  25793. });
  25794. Object.defineProperty(Scene.prototype, "pointerX", {
  25795. /**
  25796. * Gets the current on-screen X position of the pointer
  25797. */
  25798. get: function () {
  25799. return this._pointerX;
  25800. },
  25801. enumerable: true,
  25802. configurable: true
  25803. });
  25804. Object.defineProperty(Scene.prototype, "pointerY", {
  25805. /**
  25806. * Gets the current on-screen Y position of the pointer
  25807. */
  25808. get: function () {
  25809. return this._pointerY;
  25810. },
  25811. enumerable: true,
  25812. configurable: true
  25813. });
  25814. /**
  25815. * Gets the cached material (ie. the latest rendered one)
  25816. * @returns the cached material
  25817. */
  25818. Scene.prototype.getCachedMaterial = function () {
  25819. return this._cachedMaterial;
  25820. };
  25821. /**
  25822. * Gets the cached effect (ie. the latest rendered one)
  25823. * @returns the cached effect
  25824. */
  25825. Scene.prototype.getCachedEffect = function () {
  25826. return this._cachedEffect;
  25827. };
  25828. /**
  25829. * Gets the cached visibility state (ie. the latest rendered one)
  25830. * @returns the cached visibility state
  25831. */
  25832. Scene.prototype.getCachedVisibility = function () {
  25833. return this._cachedVisibility;
  25834. };
  25835. /**
  25836. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25837. * @param material defines the current material
  25838. * @param effect defines the current effect
  25839. * @param visibility defines the current visibility state
  25840. * @returns true if one parameter is not cached
  25841. */
  25842. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25843. if (visibility === void 0) { visibility = 1; }
  25844. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25845. };
  25846. /**
  25847. * Gets the engine associated with the scene
  25848. * @returns an Engine
  25849. */
  25850. Scene.prototype.getEngine = function () {
  25851. return this._engine;
  25852. };
  25853. /**
  25854. * Gets the total number of vertices rendered per frame
  25855. * @returns the total number of vertices rendered per frame
  25856. */
  25857. Scene.prototype.getTotalVertices = function () {
  25858. return this._totalVertices.current;
  25859. };
  25860. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25861. /**
  25862. * Gets the performance counter for total vertices
  25863. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25864. */
  25865. get: function () {
  25866. return this._totalVertices;
  25867. },
  25868. enumerable: true,
  25869. configurable: true
  25870. });
  25871. /**
  25872. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25873. * @returns the total number of active indices rendered per frame
  25874. */
  25875. Scene.prototype.getActiveIndices = function () {
  25876. return this._activeIndices.current;
  25877. };
  25878. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25879. /**
  25880. * Gets the performance counter for active indices
  25881. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25882. */
  25883. get: function () {
  25884. return this._activeIndices;
  25885. },
  25886. enumerable: true,
  25887. configurable: true
  25888. });
  25889. /**
  25890. * Gets the total number of active particles rendered per frame
  25891. * @returns the total number of active particles rendered per frame
  25892. */
  25893. Scene.prototype.getActiveParticles = function () {
  25894. return this._activeParticles.current;
  25895. };
  25896. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25897. /**
  25898. * Gets the performance counter for active particles
  25899. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25900. */
  25901. get: function () {
  25902. return this._activeParticles;
  25903. },
  25904. enumerable: true,
  25905. configurable: true
  25906. });
  25907. /**
  25908. * Gets the total number of active bones rendered per frame
  25909. * @returns the total number of active bones rendered per frame
  25910. */
  25911. Scene.prototype.getActiveBones = function () {
  25912. return this._activeBones.current;
  25913. };
  25914. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25915. /**
  25916. * Gets the performance counter for active bones
  25917. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25918. */
  25919. get: function () {
  25920. return this._activeBones;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. /** @hidden */
  25926. Scene.prototype.getInterFramePerfCounter = function () {
  25927. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25928. return 0;
  25929. };
  25930. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25931. /** @hidden */
  25932. get: function () {
  25933. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25934. return null;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. /** @hidden */
  25940. Scene.prototype.getLastFrameDuration = function () {
  25941. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25942. return 0;
  25943. };
  25944. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25945. /** @hidden */
  25946. get: function () {
  25947. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25948. return null;
  25949. },
  25950. enumerable: true,
  25951. configurable: true
  25952. });
  25953. /** @hidden */
  25954. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25955. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25956. return 0;
  25957. };
  25958. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25959. /** @hidden */
  25960. get: function () {
  25961. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25962. return null;
  25963. },
  25964. enumerable: true,
  25965. configurable: true
  25966. });
  25967. /**
  25968. * Gets the array of active meshes
  25969. * @returns an array of AbstractMesh
  25970. */
  25971. Scene.prototype.getActiveMeshes = function () {
  25972. return this._activeMeshes;
  25973. };
  25974. /** @hidden */
  25975. Scene.prototype.getRenderTargetsDuration = function () {
  25976. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25977. return 0;
  25978. };
  25979. /** @hidden */
  25980. Scene.prototype.getRenderDuration = function () {
  25981. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25982. return 0;
  25983. };
  25984. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25985. /** @hidden */
  25986. get: function () {
  25987. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25988. return null;
  25989. },
  25990. enumerable: true,
  25991. configurable: true
  25992. });
  25993. /** @hidden */
  25994. Scene.prototype.getParticlesDuration = function () {
  25995. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25996. return 0;
  25997. };
  25998. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25999. /** @hidden */
  26000. get: function () {
  26001. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26002. return null;
  26003. },
  26004. enumerable: true,
  26005. configurable: true
  26006. });
  26007. /** @hidden */
  26008. Scene.prototype.getSpritesDuration = function () {
  26009. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26010. return 0;
  26011. };
  26012. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26013. /** @hidden */
  26014. get: function () {
  26015. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26016. return null;
  26017. },
  26018. enumerable: true,
  26019. configurable: true
  26020. });
  26021. /**
  26022. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26023. * @returns a number
  26024. */
  26025. Scene.prototype.getAnimationRatio = function () {
  26026. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26027. };
  26028. /**
  26029. * Gets an unique Id for the current render phase
  26030. * @returns a number
  26031. */
  26032. Scene.prototype.getRenderId = function () {
  26033. return this._renderId;
  26034. };
  26035. /**
  26036. * Gets an unique Id for the current frame
  26037. * @returns a number
  26038. */
  26039. Scene.prototype.getFrameId = function () {
  26040. return this._frameId;
  26041. };
  26042. /** Call this function if you want to manually increment the render Id*/
  26043. Scene.prototype.incrementRenderId = function () {
  26044. this._renderId++;
  26045. };
  26046. Scene.prototype._updatePointerPosition = function (evt) {
  26047. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26048. if (!canvasRect) {
  26049. return;
  26050. }
  26051. this._pointerX = evt.clientX - canvasRect.left;
  26052. this._pointerY = evt.clientY - canvasRect.top;
  26053. this._unTranslatedPointerX = this._pointerX;
  26054. this._unTranslatedPointerY = this._pointerY;
  26055. };
  26056. Scene.prototype._createUbo = function () {
  26057. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26058. this._sceneUbo.addUniform("viewProjection", 16);
  26059. this._sceneUbo.addUniform("view", 16);
  26060. };
  26061. Scene.prototype._createAlternateUbo = function () {
  26062. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26063. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26064. this._alternateSceneUbo.addUniform("view", 16);
  26065. };
  26066. // Pointers handling
  26067. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26068. if (pointerInfo.pickInfo) {
  26069. if (!pointerInfo.pickInfo.ray) {
  26070. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26071. }
  26072. }
  26073. };
  26074. /**
  26075. * Use this method to simulate a pointer move on a mesh
  26076. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26077. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26078. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26079. * @returns the current scene
  26080. */
  26081. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26082. var evt = new PointerEvent("pointermove", pointerEventInit);
  26083. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26084. return this;
  26085. }
  26086. return this._processPointerMove(pickResult, evt);
  26087. };
  26088. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26089. var canvas = this._engine.getRenderingCanvas();
  26090. if (!canvas) {
  26091. return this;
  26092. }
  26093. // Restore pointer
  26094. canvas.style.cursor = this.defaultCursor;
  26095. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26096. if (isMeshPicked) {
  26097. this.setPointerOverMesh(pickResult.pickedMesh);
  26098. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26099. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26100. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26101. }
  26102. else {
  26103. canvas.style.cursor = this.hoverCursor;
  26104. }
  26105. }
  26106. }
  26107. else {
  26108. this.setPointerOverMesh(null);
  26109. }
  26110. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26111. var step = _a[_i];
  26112. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26113. }
  26114. if (pickResult) {
  26115. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26116. if (this.onPointerMove) {
  26117. this.onPointerMove(evt, pickResult, type);
  26118. }
  26119. if (this.onPointerObservable.hasObservers()) {
  26120. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26121. this._setRayOnPointerInfo(pi);
  26122. this.onPointerObservable.notifyObservers(pi, type);
  26123. }
  26124. }
  26125. return this;
  26126. };
  26127. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26128. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26129. if (pickResult) {
  26130. pi.ray = pickResult.ray;
  26131. }
  26132. this.onPrePointerObservable.notifyObservers(pi, type);
  26133. if (pi.skipOnPointerObservable) {
  26134. return true;
  26135. }
  26136. else {
  26137. return false;
  26138. }
  26139. };
  26140. /**
  26141. * Use this method to simulate a pointer down on a mesh
  26142. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26143. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26144. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26145. * @returns the current scene
  26146. */
  26147. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26148. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26149. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26150. return this;
  26151. }
  26152. return this._processPointerDown(pickResult, evt);
  26153. };
  26154. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26155. var _this = this;
  26156. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26157. this._pickedDownMesh = pickResult.pickedMesh;
  26158. var actionManager = pickResult.pickedMesh.actionManager;
  26159. if (actionManager) {
  26160. if (actionManager.hasPickTriggers) {
  26161. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26162. switch (evt.button) {
  26163. case 0:
  26164. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26165. break;
  26166. case 1:
  26167. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26168. break;
  26169. case 2:
  26170. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26171. break;
  26172. }
  26173. }
  26174. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26175. window.setTimeout(function () {
  26176. 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);
  26177. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26178. if (_this._totalPointersPressed !== 0 &&
  26179. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26180. !_this._isPointerSwiping()) {
  26181. _this._startingPointerTime = 0;
  26182. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26183. }
  26184. }
  26185. }, Scene.LongPressDelay);
  26186. }
  26187. }
  26188. }
  26189. else {
  26190. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26191. var step = _a[_i];
  26192. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26193. }
  26194. }
  26195. if (pickResult) {
  26196. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26197. if (this.onPointerDown) {
  26198. this.onPointerDown(evt, pickResult, type);
  26199. }
  26200. if (this.onPointerObservable.hasObservers()) {
  26201. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26202. this._setRayOnPointerInfo(pi);
  26203. this.onPointerObservable.notifyObservers(pi, type);
  26204. }
  26205. }
  26206. return this;
  26207. };
  26208. /**
  26209. * Use this method to simulate a pointer up on a mesh
  26210. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26211. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26212. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26213. * @returns the current scene
  26214. */
  26215. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26216. var evt = new PointerEvent("pointerup", pointerEventInit);
  26217. var clickInfo = new ClickInfo();
  26218. clickInfo.singleClick = true;
  26219. clickInfo.ignore = true;
  26220. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26221. return this;
  26222. }
  26223. return this._processPointerUp(pickResult, evt, clickInfo);
  26224. };
  26225. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26226. if (pickResult && pickResult && pickResult.pickedMesh) {
  26227. this._pickedUpMesh = pickResult.pickedMesh;
  26228. if (this._pickedDownMesh === this._pickedUpMesh) {
  26229. if (this.onPointerPick) {
  26230. this.onPointerPick(evt, pickResult);
  26231. }
  26232. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26233. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26234. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26235. this._setRayOnPointerInfo(pi);
  26236. this.onPointerObservable.notifyObservers(pi, type_1);
  26237. }
  26238. }
  26239. if (pickResult.pickedMesh.actionManager) {
  26240. if (clickInfo.ignore) {
  26241. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26242. }
  26243. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26244. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26245. }
  26246. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26247. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26248. }
  26249. }
  26250. }
  26251. else {
  26252. if (!clickInfo.ignore) {
  26253. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26254. var step = _a[_i];
  26255. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26256. }
  26257. }
  26258. }
  26259. if (this._pickedDownMesh &&
  26260. this._pickedDownMesh.actionManager &&
  26261. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26262. this._pickedDownMesh !== this._pickedUpMesh) {
  26263. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26264. }
  26265. var type = BABYLON.PointerEventTypes.POINTERUP;
  26266. if (this.onPointerObservable.hasObservers()) {
  26267. if (!clickInfo.ignore) {
  26268. if (!clickInfo.hasSwiped) {
  26269. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26270. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26271. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26272. this._setRayOnPointerInfo(pi);
  26273. this.onPointerObservable.notifyObservers(pi, type_2);
  26274. }
  26275. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26276. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26277. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26278. this._setRayOnPointerInfo(pi);
  26279. this.onPointerObservable.notifyObservers(pi, type_3);
  26280. }
  26281. }
  26282. }
  26283. else {
  26284. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26285. this._setRayOnPointerInfo(pi);
  26286. this.onPointerObservable.notifyObservers(pi, type);
  26287. }
  26288. }
  26289. if (this.onPointerUp) {
  26290. this.onPointerUp(evt, pickResult, type);
  26291. }
  26292. return this;
  26293. };
  26294. /**
  26295. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26296. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26297. * @returns true if the pointer was captured
  26298. */
  26299. Scene.prototype.isPointerCaptured = function (pointerId) {
  26300. if (pointerId === void 0) { pointerId = 0; }
  26301. return this._pointerCaptures[pointerId];
  26302. };
  26303. /** @hidden */
  26304. Scene.prototype._isPointerSwiping = function () {
  26305. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26306. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26307. };
  26308. /**
  26309. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26310. * @param attachUp defines if you want to attach events to pointerup
  26311. * @param attachDown defines if you want to attach events to pointerdown
  26312. * @param attachMove defines if you want to attach events to pointermove
  26313. */
  26314. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26315. var _this = this;
  26316. if (attachUp === void 0) { attachUp = true; }
  26317. if (attachDown === void 0) { attachDown = true; }
  26318. if (attachMove === void 0) { attachMove = true; }
  26319. this._initActionManager = function (act, clickInfo) {
  26320. if (!_this._meshPickProceed) {
  26321. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26322. _this._currentPickResult = pickResult;
  26323. if (pickResult) {
  26324. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26325. }
  26326. _this._meshPickProceed = true;
  26327. }
  26328. return act;
  26329. };
  26330. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26331. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26332. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26333. btn !== _this._previousButtonPressed) {
  26334. _this._doubleClickOccured = false;
  26335. clickInfo.singleClick = true;
  26336. clickInfo.ignore = false;
  26337. cb(clickInfo, _this._currentPickResult);
  26338. }
  26339. };
  26340. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26341. var clickInfo = new ClickInfo();
  26342. _this._currentPickResult = null;
  26343. var act = null;
  26344. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26345. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26346. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26347. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26348. act = _this._initActionManager(act, clickInfo);
  26349. if (act)
  26350. checkPicking = act.hasPickTriggers;
  26351. }
  26352. if (checkPicking) {
  26353. var btn = evt.button;
  26354. clickInfo.hasSwiped = _this._isPointerSwiping();
  26355. if (!clickInfo.hasSwiped) {
  26356. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26357. if (!checkSingleClickImmediately) {
  26358. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26359. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26360. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26361. act = _this._initActionManager(act, clickInfo);
  26362. if (act)
  26363. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26364. }
  26365. }
  26366. if (checkSingleClickImmediately) {
  26367. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26368. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26369. btn !== _this._previousButtonPressed) {
  26370. clickInfo.singleClick = true;
  26371. cb(clickInfo, _this._currentPickResult);
  26372. }
  26373. }
  26374. // at least one double click is required to be check and exclusive double click is enabled
  26375. else {
  26376. // wait that no double click has been raised during the double click delay
  26377. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26378. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26379. }
  26380. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26381. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26382. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26383. act = _this._initActionManager(act, clickInfo);
  26384. if (act)
  26385. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26386. }
  26387. if (checkDoubleClick) {
  26388. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26389. if (btn === _this._previousButtonPressed &&
  26390. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26391. !_this._doubleClickOccured) {
  26392. // pointer has not moved for 2 clicks, it's a double click
  26393. if (!clickInfo.hasSwiped &&
  26394. !_this._isPointerSwiping()) {
  26395. _this._previousStartingPointerTime = 0;
  26396. _this._doubleClickOccured = true;
  26397. clickInfo.doubleClick = true;
  26398. clickInfo.ignore = false;
  26399. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26400. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26401. }
  26402. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26403. cb(clickInfo, _this._currentPickResult);
  26404. }
  26405. // if the two successive clicks are too far, it's just two simple clicks
  26406. else {
  26407. _this._doubleClickOccured = false;
  26408. _this._previousStartingPointerTime = _this._startingPointerTime;
  26409. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26410. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26411. _this._previousButtonPressed = btn;
  26412. if (Scene.ExclusiveDoubleClickMode) {
  26413. if (_this._previousDelayedSimpleClickTimeout) {
  26414. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26415. }
  26416. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26417. cb(clickInfo, _this._previousPickResult);
  26418. }
  26419. else {
  26420. cb(clickInfo, _this._currentPickResult);
  26421. }
  26422. }
  26423. }
  26424. // just the first click of the double has been raised
  26425. else {
  26426. _this._doubleClickOccured = false;
  26427. _this._previousStartingPointerTime = _this._startingPointerTime;
  26428. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26429. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26430. _this._previousButtonPressed = btn;
  26431. }
  26432. }
  26433. }
  26434. }
  26435. clickInfo.ignore = true;
  26436. cb(clickInfo, _this._currentPickResult);
  26437. };
  26438. this._onPointerMove = function (evt) {
  26439. _this._updatePointerPosition(evt);
  26440. // PreObservable support
  26441. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26442. return;
  26443. }
  26444. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26445. return;
  26446. }
  26447. if (!_this.pointerMovePredicate) {
  26448. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26449. }
  26450. // Meshes
  26451. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26452. _this._processPointerMove(pickResult, evt);
  26453. };
  26454. this._onPointerDown = function (evt) {
  26455. _this._totalPointersPressed++;
  26456. _this._pickedDownMesh = null;
  26457. _this._meshPickProceed = false;
  26458. _this._updatePointerPosition(evt);
  26459. if (_this.preventDefaultOnPointerDown && canvas) {
  26460. evt.preventDefault();
  26461. canvas.focus();
  26462. }
  26463. // PreObservable support
  26464. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26465. return;
  26466. }
  26467. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26468. return;
  26469. }
  26470. _this._pointerCaptures[evt.pointerId] = true;
  26471. _this._startingPointerPosition.x = _this._pointerX;
  26472. _this._startingPointerPosition.y = _this._pointerY;
  26473. _this._startingPointerTime = Date.now();
  26474. if (!_this.pointerDownPredicate) {
  26475. _this.pointerDownPredicate = function (mesh) {
  26476. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26477. };
  26478. }
  26479. // Meshes
  26480. _this._pickedDownMesh = null;
  26481. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26482. _this._processPointerDown(pickResult, evt);
  26483. };
  26484. this._onPointerUp = function (evt) {
  26485. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26486. return; // So we need to test it the pointer down was pressed before.
  26487. }
  26488. _this._totalPointersPressed--;
  26489. _this._pickedUpMesh = null;
  26490. _this._meshPickProceed = false;
  26491. _this._updatePointerPosition(evt);
  26492. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26493. // PreObservable support
  26494. if (_this.onPrePointerObservable.hasObservers()) {
  26495. if (!clickInfo.ignore) {
  26496. if (!clickInfo.hasSwiped) {
  26497. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26498. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26499. return;
  26500. }
  26501. }
  26502. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26503. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26504. return;
  26505. }
  26506. }
  26507. }
  26508. }
  26509. else {
  26510. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26511. return;
  26512. }
  26513. }
  26514. }
  26515. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26516. return;
  26517. }
  26518. _this._pointerCaptures[evt.pointerId] = false;
  26519. if (!_this.pointerUpPredicate) {
  26520. _this.pointerUpPredicate = function (mesh) {
  26521. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26522. };
  26523. }
  26524. // Meshes
  26525. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26526. _this._initActionManager(null, clickInfo);
  26527. }
  26528. if (!pickResult) {
  26529. pickResult = _this._currentPickResult;
  26530. }
  26531. _this._processPointerUp(pickResult, evt, clickInfo);
  26532. _this._previousPickResult = _this._currentPickResult;
  26533. });
  26534. };
  26535. this._onKeyDown = function (evt) {
  26536. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26537. if (_this.onPreKeyboardObservable.hasObservers()) {
  26538. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26539. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26540. if (pi.skipOnPointerObservable) {
  26541. return;
  26542. }
  26543. }
  26544. if (_this.onKeyboardObservable.hasObservers()) {
  26545. var pi = new BABYLON.KeyboardInfo(type, evt);
  26546. _this.onKeyboardObservable.notifyObservers(pi, type);
  26547. }
  26548. if (_this.actionManager) {
  26549. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26550. }
  26551. };
  26552. this._onKeyUp = function (evt) {
  26553. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26554. if (_this.onPreKeyboardObservable.hasObservers()) {
  26555. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26556. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26557. if (pi.skipOnPointerObservable) {
  26558. return;
  26559. }
  26560. }
  26561. if (_this.onKeyboardObservable.hasObservers()) {
  26562. var pi = new BABYLON.KeyboardInfo(type, evt);
  26563. _this.onKeyboardObservable.notifyObservers(pi, type);
  26564. }
  26565. if (_this.actionManager) {
  26566. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26567. }
  26568. };
  26569. var engine = this.getEngine();
  26570. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26571. if (!canvas) {
  26572. return;
  26573. }
  26574. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26575. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26576. });
  26577. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26578. if (!canvas) {
  26579. return;
  26580. }
  26581. canvas.removeEventListener("keydown", _this._onKeyDown);
  26582. canvas.removeEventListener("keyup", _this._onKeyUp);
  26583. });
  26584. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26585. var canvas = this._engine.getRenderingCanvas();
  26586. if (!canvas) {
  26587. return;
  26588. }
  26589. if (attachMove) {
  26590. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26591. // Wheel
  26592. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26593. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26594. }
  26595. if (attachDown) {
  26596. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26597. }
  26598. if (attachUp) {
  26599. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26600. }
  26601. canvas.tabIndex = 1;
  26602. };
  26603. /** Detaches all event handlers*/
  26604. Scene.prototype.detachControl = function () {
  26605. var engine = this.getEngine();
  26606. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26607. var canvas = engine.getRenderingCanvas();
  26608. if (!canvas) {
  26609. return;
  26610. }
  26611. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26612. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26613. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26614. if (this._onCanvasBlurObserver) {
  26615. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26616. }
  26617. if (this._onCanvasFocusObserver) {
  26618. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26619. }
  26620. // Wheel
  26621. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26622. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26623. // Keyboard
  26624. canvas.removeEventListener("keydown", this._onKeyDown);
  26625. canvas.removeEventListener("keyup", this._onKeyUp);
  26626. // Observables
  26627. this.onKeyboardObservable.clear();
  26628. this.onPreKeyboardObservable.clear();
  26629. this.onPointerObservable.clear();
  26630. this.onPrePointerObservable.clear();
  26631. };
  26632. /**
  26633. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26634. * Delay loaded resources are not taking in account
  26635. * @return true if all required resources are ready
  26636. */
  26637. Scene.prototype.isReady = function () {
  26638. if (this._isDisposed) {
  26639. return false;
  26640. }
  26641. if (this._pendingData.length > 0) {
  26642. return false;
  26643. }
  26644. var index;
  26645. var engine = this.getEngine();
  26646. // Geometries
  26647. for (index = 0; index < this.geometries.length; index++) {
  26648. var geometry = this.geometries[index];
  26649. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26650. return false;
  26651. }
  26652. }
  26653. // Meshes
  26654. for (index = 0; index < this.meshes.length; index++) {
  26655. var mesh = this.meshes[index];
  26656. if (!mesh.isEnabled()) {
  26657. continue;
  26658. }
  26659. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26660. continue;
  26661. }
  26662. if (!mesh.isReady(true)) {
  26663. return false;
  26664. }
  26665. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26666. // Is Ready For Mesh
  26667. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26668. var step = _a[_i];
  26669. if (!step.action(mesh, hardwareInstancedRendering)) {
  26670. return false;
  26671. }
  26672. }
  26673. }
  26674. // Post-processes
  26675. if (this.activeCameras && this.activeCameras.length > 0) {
  26676. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26677. var camera = _c[_b];
  26678. if (!camera.isReady(true)) {
  26679. return false;
  26680. }
  26681. }
  26682. }
  26683. else if (this.activeCamera) {
  26684. if (!this.activeCamera.isReady(true)) {
  26685. return false;
  26686. }
  26687. }
  26688. // Particles
  26689. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26690. var particleSystem = _e[_d];
  26691. if (!particleSystem.isReady()) {
  26692. return false;
  26693. }
  26694. }
  26695. return true;
  26696. };
  26697. /** Resets all cached information relative to material (including effect and visibility) */
  26698. Scene.prototype.resetCachedMaterial = function () {
  26699. this._cachedMaterial = null;
  26700. this._cachedEffect = null;
  26701. this._cachedVisibility = null;
  26702. };
  26703. /**
  26704. * Registers a function to be called before every frame render
  26705. * @param func defines the function to register
  26706. */
  26707. Scene.prototype.registerBeforeRender = function (func) {
  26708. this.onBeforeRenderObservable.add(func);
  26709. };
  26710. /**
  26711. * Unregisters a function called before every frame render
  26712. * @param func defines the function to unregister
  26713. */
  26714. Scene.prototype.unregisterBeforeRender = function (func) {
  26715. this.onBeforeRenderObservable.removeCallback(func);
  26716. };
  26717. /**
  26718. * Registers a function to be called after every frame render
  26719. * @param func defines the function to register
  26720. */
  26721. Scene.prototype.registerAfterRender = function (func) {
  26722. this.onAfterRenderObservable.add(func);
  26723. };
  26724. /**
  26725. * Unregisters a function called after every frame render
  26726. * @param func defines the function to unregister
  26727. */
  26728. Scene.prototype.unregisterAfterRender = function (func) {
  26729. this.onAfterRenderObservable.removeCallback(func);
  26730. };
  26731. Scene.prototype._executeOnceBeforeRender = function (func) {
  26732. var _this = this;
  26733. var execFunc = function () {
  26734. func();
  26735. setTimeout(function () {
  26736. _this.unregisterBeforeRender(execFunc);
  26737. });
  26738. };
  26739. this.registerBeforeRender(execFunc);
  26740. };
  26741. /**
  26742. * The provided function will run before render once and will be disposed afterwards.
  26743. * A timeout delay can be provided so that the function will be executed in N ms.
  26744. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26745. * @param func The function to be executed.
  26746. * @param timeout optional delay in ms
  26747. */
  26748. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26749. var _this = this;
  26750. if (timeout !== undefined) {
  26751. setTimeout(function () {
  26752. _this._executeOnceBeforeRender(func);
  26753. }, timeout);
  26754. }
  26755. else {
  26756. this._executeOnceBeforeRender(func);
  26757. }
  26758. };
  26759. /** @hidden */
  26760. Scene.prototype._addPendingData = function (data) {
  26761. this._pendingData.push(data);
  26762. };
  26763. /** @hidden */
  26764. Scene.prototype._removePendingData = function (data) {
  26765. var wasLoading = this.isLoading;
  26766. var index = this._pendingData.indexOf(data);
  26767. if (index !== -1) {
  26768. this._pendingData.splice(index, 1);
  26769. }
  26770. if (wasLoading && !this.isLoading) {
  26771. this.onDataLoadedObservable.notifyObservers(this);
  26772. }
  26773. };
  26774. /**
  26775. * Returns the number of items waiting to be loaded
  26776. * @returns the number of items waiting to be loaded
  26777. */
  26778. Scene.prototype.getWaitingItemsCount = function () {
  26779. return this._pendingData.length;
  26780. };
  26781. Object.defineProperty(Scene.prototype, "isLoading", {
  26782. /**
  26783. * Returns a boolean indicating if the scene is still loading data
  26784. */
  26785. get: function () {
  26786. return this._pendingData.length > 0;
  26787. },
  26788. enumerable: true,
  26789. configurable: true
  26790. });
  26791. /**
  26792. * Registers a function to be executed when the scene is ready
  26793. * @param {Function} func - the function to be executed
  26794. */
  26795. Scene.prototype.executeWhenReady = function (func) {
  26796. var _this = this;
  26797. this.onReadyObservable.add(func);
  26798. if (this._executeWhenReadyTimeoutId !== -1) {
  26799. return;
  26800. }
  26801. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26802. _this._checkIsReady();
  26803. }, 150);
  26804. };
  26805. /**
  26806. * Returns a promise that resolves when the scene is ready
  26807. * @returns A promise that resolves when the scene is ready
  26808. */
  26809. Scene.prototype.whenReadyAsync = function () {
  26810. var _this = this;
  26811. return new Promise(function (resolve) {
  26812. _this.executeWhenReady(function () {
  26813. resolve();
  26814. });
  26815. });
  26816. };
  26817. /** @hidden */
  26818. Scene.prototype._checkIsReady = function () {
  26819. var _this = this;
  26820. this._registerTransientComponents();
  26821. if (this.isReady()) {
  26822. this.onReadyObservable.notifyObservers(this);
  26823. this.onReadyObservable.clear();
  26824. this._executeWhenReadyTimeoutId = -1;
  26825. return;
  26826. }
  26827. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26828. _this._checkIsReady();
  26829. }, 150);
  26830. };
  26831. // Animations
  26832. /**
  26833. * Will start the animation sequence of a given target
  26834. * @param target defines the target
  26835. * @param from defines from which frame should animation start
  26836. * @param to defines until which frame should animation run.
  26837. * @param weight defines the weight to apply to the animation (1.0 by default)
  26838. * @param loop defines if the animation loops
  26839. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26840. * @param onAnimationEnd defines the function to be executed when the animation ends
  26841. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26842. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26843. * @returns the animatable object created for this animation
  26844. */
  26845. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26846. if (weight === void 0) { weight = 1.0; }
  26847. if (speedRatio === void 0) { speedRatio = 1.0; }
  26848. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26849. returnedAnimatable.weight = weight;
  26850. return returnedAnimatable;
  26851. };
  26852. /**
  26853. * Will start the animation sequence of a given target
  26854. * @param target defines the target
  26855. * @param from defines from which frame should animation start
  26856. * @param to defines until which frame should animation run.
  26857. * @param loop defines if the animation loops
  26858. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26859. * @param onAnimationEnd defines the function to be executed when the animation ends
  26860. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26861. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26862. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26863. * @returns the animatable object created for this animation
  26864. */
  26865. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26866. if (speedRatio === void 0) { speedRatio = 1.0; }
  26867. if (stopCurrent === void 0) { stopCurrent = true; }
  26868. if (from > to && speedRatio > 0) {
  26869. speedRatio *= -1;
  26870. }
  26871. if (stopCurrent) {
  26872. this.stopAnimation(target, undefined, targetMask);
  26873. }
  26874. if (!animatable) {
  26875. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26876. }
  26877. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26878. // Local animations
  26879. if (target.animations && shouldRunTargetAnimations) {
  26880. animatable.appendAnimations(target, target.animations);
  26881. }
  26882. // Children animations
  26883. if (target.getAnimatables) {
  26884. var animatables = target.getAnimatables();
  26885. for (var index = 0; index < animatables.length; index++) {
  26886. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26887. }
  26888. }
  26889. animatable.reset();
  26890. return animatable;
  26891. };
  26892. /**
  26893. * Begin a new animation on a given node
  26894. * @param target defines the target where the animation will take place
  26895. * @param animations defines the list of animations to start
  26896. * @param from defines the initial value
  26897. * @param to defines the final value
  26898. * @param loop defines if you want animation to loop (off by default)
  26899. * @param speedRatio defines the speed ratio to apply to all animations
  26900. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26901. * @returns the list of created animatables
  26902. */
  26903. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26904. if (speedRatio === undefined) {
  26905. speedRatio = 1.0;
  26906. }
  26907. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26908. return animatable;
  26909. };
  26910. /**
  26911. * Begin a new animation on a given node and its hierarchy
  26912. * @param target defines the root node where the animation will take place
  26913. * @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.
  26914. * @param animations defines the list of animations to start
  26915. * @param from defines the initial value
  26916. * @param to defines the final value
  26917. * @param loop defines if you want animation to loop (off by default)
  26918. * @param speedRatio defines the speed ratio to apply to all animations
  26919. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26920. * @returns the list of animatables created for all nodes
  26921. */
  26922. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26923. var children = target.getDescendants(directDescendantsOnly);
  26924. var result = [];
  26925. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26926. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26927. var child = children_1[_i];
  26928. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26929. }
  26930. return result;
  26931. };
  26932. /**
  26933. * Gets the animatable associated with a specific target
  26934. * @param target defines the target of the animatable
  26935. * @returns the required animatable if found
  26936. */
  26937. Scene.prototype.getAnimatableByTarget = function (target) {
  26938. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26939. if (this._activeAnimatables[index].target === target) {
  26940. return this._activeAnimatables[index];
  26941. }
  26942. }
  26943. return null;
  26944. };
  26945. /**
  26946. * Gets all animatables associated with a given target
  26947. * @param target defines the target to look animatables for
  26948. * @returns an array of Animatables
  26949. */
  26950. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26951. var result = [];
  26952. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26953. if (this._activeAnimatables[index].target === target) {
  26954. result.push(this._activeAnimatables[index]);
  26955. }
  26956. }
  26957. return result;
  26958. };
  26959. Object.defineProperty(Scene.prototype, "animatables", {
  26960. /**
  26961. * Gets all animatable attached to the scene
  26962. */
  26963. get: function () {
  26964. return this._activeAnimatables;
  26965. },
  26966. enumerable: true,
  26967. configurable: true
  26968. });
  26969. /**
  26970. * Will stop the animation of the given target
  26971. * @param target - the target
  26972. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26973. * @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)
  26974. */
  26975. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26976. var animatables = this.getAllAnimatablesByTarget(target);
  26977. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26978. var animatable = animatables_1[_i];
  26979. animatable.stop(animationName, targetMask);
  26980. }
  26981. };
  26982. /**
  26983. * Stops and removes all animations that have been applied to the scene
  26984. */
  26985. Scene.prototype.stopAllAnimations = function () {
  26986. if (this._activeAnimatables) {
  26987. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26988. this._activeAnimatables[i].stop();
  26989. }
  26990. this._activeAnimatables = [];
  26991. }
  26992. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26993. var group = _a[_i];
  26994. group.stop();
  26995. }
  26996. };
  26997. Scene.prototype._animate = function () {
  26998. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26999. return;
  27000. }
  27001. // Getting time
  27002. var now = BABYLON.Tools.Now;
  27003. if (!this._animationTimeLast) {
  27004. if (this._pendingData.length > 0) {
  27005. return;
  27006. }
  27007. this._animationTimeLast = now;
  27008. }
  27009. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27010. this._animationTime += deltaTime;
  27011. this._animationTimeLast = now;
  27012. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27013. this._activeAnimatables[index]._animate(this._animationTime);
  27014. }
  27015. // Late animation bindings
  27016. this._processLateAnimationBindings();
  27017. };
  27018. /** @hidden */
  27019. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27020. var target = runtimeAnimation.target;
  27021. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27022. if (!target._lateAnimationHolders) {
  27023. target._lateAnimationHolders = {};
  27024. }
  27025. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27026. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27027. totalWeight: 0,
  27028. animations: [],
  27029. originalValue: originalValue
  27030. };
  27031. }
  27032. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27033. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27034. };
  27035. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27036. var normalizer = 1.0;
  27037. var finalPosition = BABYLON.Tmp.Vector3[0];
  27038. var finalScaling = BABYLON.Tmp.Vector3[1];
  27039. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27040. var startIndex = 0;
  27041. var originalAnimation = holder.animations[0];
  27042. var originalValue = holder.originalValue;
  27043. var scale = 1;
  27044. if (holder.totalWeight < 1.0) {
  27045. // We need to mix the original value in
  27046. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27047. scale = 1.0 - holder.totalWeight;
  27048. }
  27049. else {
  27050. startIndex = 1;
  27051. // We need to normalize the weights
  27052. normalizer = holder.totalWeight;
  27053. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27054. scale = originalAnimation.weight / normalizer;
  27055. if (scale == 1) {
  27056. return originalAnimation.currentValue;
  27057. }
  27058. }
  27059. finalScaling.scaleInPlace(scale);
  27060. finalPosition.scaleInPlace(scale);
  27061. finalQuaternion.scaleInPlace(scale);
  27062. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27063. var runtimeAnimation = holder.animations[animIndex];
  27064. var scale = runtimeAnimation.weight / normalizer;
  27065. var currentPosition = BABYLON.Tmp.Vector3[2];
  27066. var currentScaling = BABYLON.Tmp.Vector3[3];
  27067. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27068. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27069. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27070. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27071. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27072. }
  27073. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27074. return originalAnimation._workValue;
  27075. };
  27076. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27077. var originalAnimation = holder.animations[0];
  27078. var originalValue = holder.originalValue;
  27079. if (holder.animations.length === 1) {
  27080. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27081. return refQuaternion;
  27082. }
  27083. var normalizer = 1.0;
  27084. var quaternions;
  27085. var weights;
  27086. if (holder.totalWeight < 1.0) {
  27087. var scale = 1.0 - holder.totalWeight;
  27088. quaternions = [];
  27089. weights = [];
  27090. quaternions.push(originalValue);
  27091. weights.push(scale);
  27092. }
  27093. else {
  27094. if (holder.animations.length === 2) { // Slerp as soon as we can
  27095. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27096. return refQuaternion;
  27097. }
  27098. quaternions = [];
  27099. weights = [];
  27100. normalizer = holder.totalWeight;
  27101. }
  27102. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27103. var runtimeAnimation = holder.animations[animIndex];
  27104. quaternions.push(runtimeAnimation.currentValue);
  27105. weights.push(runtimeAnimation.weight / normalizer);
  27106. }
  27107. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27108. var cumulativeAmount = 0;
  27109. var cumulativeQuaternion = null;
  27110. for (var index = 0; index < quaternions.length;) {
  27111. if (!cumulativeQuaternion) {
  27112. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27113. cumulativeQuaternion = refQuaternion;
  27114. cumulativeAmount = weights[index] + weights[index + 1];
  27115. index += 2;
  27116. continue;
  27117. }
  27118. cumulativeAmount += weights[index];
  27119. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27120. index++;
  27121. }
  27122. return cumulativeQuaternion;
  27123. };
  27124. Scene.prototype._processLateAnimationBindings = function () {
  27125. if (!this._registeredForLateAnimationBindings.length) {
  27126. return;
  27127. }
  27128. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27129. var target = this._registeredForLateAnimationBindings.data[index];
  27130. for (var path in target._lateAnimationHolders) {
  27131. var holder = target._lateAnimationHolders[path];
  27132. var originalAnimation = holder.animations[0];
  27133. var originalValue = holder.originalValue;
  27134. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27135. var finalValue = target[path];
  27136. if (matrixDecomposeMode) {
  27137. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27138. }
  27139. else {
  27140. var quaternionMode = originalValue.w !== undefined;
  27141. if (quaternionMode) {
  27142. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27143. }
  27144. else {
  27145. var startIndex = 0;
  27146. var normalizer = 1.0;
  27147. if (holder.totalWeight < 1.0) {
  27148. // We need to mix the original value in
  27149. if (originalValue.scale) {
  27150. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27151. }
  27152. else {
  27153. finalValue = originalValue * (1.0 - holder.totalWeight);
  27154. }
  27155. }
  27156. else {
  27157. // We need to normalize the weights
  27158. normalizer = holder.totalWeight;
  27159. var scale_1 = originalAnimation.weight / normalizer;
  27160. if (scale_1 !== 1) {
  27161. if (originalAnimation.currentValue.scale) {
  27162. finalValue = originalAnimation.currentValue.scale(scale_1);
  27163. }
  27164. else {
  27165. finalValue = originalAnimation.currentValue * scale_1;
  27166. }
  27167. }
  27168. else {
  27169. finalValue = originalAnimation.currentValue;
  27170. }
  27171. startIndex = 1;
  27172. }
  27173. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27174. var runtimeAnimation = holder.animations[animIndex];
  27175. var scale = runtimeAnimation.weight / normalizer;
  27176. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27177. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27178. }
  27179. else {
  27180. finalValue += runtimeAnimation.currentValue * scale;
  27181. }
  27182. }
  27183. }
  27184. }
  27185. target[path] = finalValue;
  27186. }
  27187. target._lateAnimationHolders = {};
  27188. }
  27189. this._registeredForLateAnimationBindings.reset();
  27190. };
  27191. // Matrix
  27192. /** @hidden */
  27193. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27194. this._useAlternateCameraConfiguration = active;
  27195. };
  27196. /**
  27197. * Gets the current view matrix
  27198. * @returns a Matrix
  27199. */
  27200. Scene.prototype.getViewMatrix = function () {
  27201. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27202. };
  27203. /**
  27204. * Gets the current projection matrix
  27205. * @returns a Matrix
  27206. */
  27207. Scene.prototype.getProjectionMatrix = function () {
  27208. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27209. };
  27210. /**
  27211. * Gets the current transform matrix
  27212. * @returns a Matrix made of View * Projection
  27213. */
  27214. Scene.prototype.getTransformMatrix = function () {
  27215. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27216. };
  27217. /**
  27218. * Sets the current transform matrix
  27219. * @param view defines the View matrix to use
  27220. * @param projection defines the Projection matrix to use
  27221. */
  27222. Scene.prototype.setTransformMatrix = function (view, projection) {
  27223. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27224. return;
  27225. }
  27226. this._viewUpdateFlag = view.updateFlag;
  27227. this._projectionUpdateFlag = projection.updateFlag;
  27228. this._viewMatrix = view;
  27229. this._projectionMatrix = projection;
  27230. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27231. // Update frustum
  27232. if (!this._frustumPlanes) {
  27233. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27234. }
  27235. else {
  27236. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27237. }
  27238. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27239. var otherCamera = this.activeCamera._alternateCamera;
  27240. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27241. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27242. }
  27243. if (this._sceneUbo.useUbo) {
  27244. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27245. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27246. this._sceneUbo.update();
  27247. }
  27248. };
  27249. /** @hidden */
  27250. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27251. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27252. return;
  27253. }
  27254. this._alternateViewUpdateFlag = view.updateFlag;
  27255. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27256. this._alternateViewMatrix = view;
  27257. this._alternateProjectionMatrix = projection;
  27258. if (!this._alternateTransformMatrix) {
  27259. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27260. }
  27261. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27262. if (!this._alternateSceneUbo) {
  27263. this._createAlternateUbo();
  27264. }
  27265. if (this._alternateSceneUbo.useUbo) {
  27266. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27267. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27268. this._alternateSceneUbo.update();
  27269. }
  27270. };
  27271. /**
  27272. * Gets the uniform buffer used to store scene data
  27273. * @returns a UniformBuffer
  27274. */
  27275. Scene.prototype.getSceneUniformBuffer = function () {
  27276. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27277. };
  27278. /**
  27279. * Gets an unique (relatively to the current scene) Id
  27280. * @returns an unique number for the scene
  27281. */
  27282. Scene.prototype.getUniqueId = function () {
  27283. var result = Scene._uniqueIdCounter;
  27284. Scene._uniqueIdCounter++;
  27285. return result;
  27286. };
  27287. /**
  27288. * Add a mesh to the list of scene's meshes
  27289. * @param newMesh defines the mesh to add
  27290. * @param recursive if all child meshes should also be added to the scene
  27291. */
  27292. Scene.prototype.addMesh = function (newMesh, recursive) {
  27293. var _this = this;
  27294. if (recursive === void 0) { recursive = false; }
  27295. this.meshes.push(newMesh);
  27296. //notify the collision coordinator
  27297. if (this.collisionCoordinator) {
  27298. this.collisionCoordinator.onMeshAdded(newMesh);
  27299. }
  27300. newMesh._resyncLightSources();
  27301. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27302. if (recursive) {
  27303. newMesh.getChildMeshes().forEach(function (m) {
  27304. _this.addMesh(m);
  27305. });
  27306. }
  27307. };
  27308. /**
  27309. * Remove a mesh for the list of scene's meshes
  27310. * @param toRemove defines the mesh to remove
  27311. * @param recursive if all child meshes should also be removed from the scene
  27312. * @returns the index where the mesh was in the mesh list
  27313. */
  27314. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27315. var _this = this;
  27316. if (recursive === void 0) { recursive = false; }
  27317. var index = this.meshes.indexOf(toRemove);
  27318. if (index !== -1) {
  27319. // Remove from the scene if mesh found
  27320. this.meshes.splice(index, 1);
  27321. }
  27322. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27323. if (recursive) {
  27324. toRemove.getChildMeshes().forEach(function (m) {
  27325. _this.removeMesh(m);
  27326. });
  27327. }
  27328. return index;
  27329. };
  27330. /**
  27331. * Add a transform node to the list of scene's transform nodes
  27332. * @param newTransformNode defines the transform node to add
  27333. */
  27334. Scene.prototype.addTransformNode = function (newTransformNode) {
  27335. this.transformNodes.push(newTransformNode);
  27336. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27337. };
  27338. /**
  27339. * Remove a transform node for the list of scene's transform nodes
  27340. * @param toRemove defines the transform node to remove
  27341. * @returns the index where the transform node was in the transform node list
  27342. */
  27343. Scene.prototype.removeTransformNode = function (toRemove) {
  27344. var index = this.transformNodes.indexOf(toRemove);
  27345. if (index !== -1) {
  27346. // Remove from the scene if found
  27347. this.transformNodes.splice(index, 1);
  27348. }
  27349. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27350. return index;
  27351. };
  27352. /**
  27353. * Remove a skeleton for the list of scene's skeletons
  27354. * @param toRemove defines the skeleton to remove
  27355. * @returns the index where the skeleton was in the skeleton list
  27356. */
  27357. Scene.prototype.removeSkeleton = function (toRemove) {
  27358. var index = this.skeletons.indexOf(toRemove);
  27359. if (index !== -1) {
  27360. // Remove from the scene if found
  27361. this.skeletons.splice(index, 1);
  27362. }
  27363. return index;
  27364. };
  27365. /**
  27366. * Remove a morph target for the list of scene's morph targets
  27367. * @param toRemove defines the morph target to remove
  27368. * @returns the index where the morph target was in the morph target list
  27369. */
  27370. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27371. var index = this.morphTargetManagers.indexOf(toRemove);
  27372. if (index !== -1) {
  27373. // Remove from the scene if found
  27374. this.morphTargetManagers.splice(index, 1);
  27375. }
  27376. return index;
  27377. };
  27378. /**
  27379. * Remove a light for the list of scene's lights
  27380. * @param toRemove defines the light to remove
  27381. * @returns the index where the light was in the light list
  27382. */
  27383. Scene.prototype.removeLight = function (toRemove) {
  27384. var index = this.lights.indexOf(toRemove);
  27385. if (index !== -1) {
  27386. // Remove from meshes
  27387. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27388. var mesh = _a[_i];
  27389. mesh._removeLightSource(toRemove);
  27390. }
  27391. // Remove from the scene if mesh found
  27392. this.lights.splice(index, 1);
  27393. this.sortLightsByPriority();
  27394. }
  27395. this.onLightRemovedObservable.notifyObservers(toRemove);
  27396. return index;
  27397. };
  27398. /**
  27399. * Remove a camera for the list of scene's cameras
  27400. * @param toRemove defines the camera to remove
  27401. * @returns the index where the camera was in the camera list
  27402. */
  27403. Scene.prototype.removeCamera = function (toRemove) {
  27404. var index = this.cameras.indexOf(toRemove);
  27405. if (index !== -1) {
  27406. // Remove from the scene if mesh found
  27407. this.cameras.splice(index, 1);
  27408. }
  27409. // Remove from activeCameras
  27410. var index2 = this.activeCameras.indexOf(toRemove);
  27411. if (index2 !== -1) {
  27412. // Remove from the scene if mesh found
  27413. this.activeCameras.splice(index2, 1);
  27414. }
  27415. // Reset the activeCamera
  27416. if (this.activeCamera === toRemove) {
  27417. if (this.cameras.length > 0) {
  27418. this.activeCamera = this.cameras[0];
  27419. }
  27420. else {
  27421. this.activeCamera = null;
  27422. }
  27423. }
  27424. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27425. return index;
  27426. };
  27427. /**
  27428. * Remove a particle system for the list of scene's particle systems
  27429. * @param toRemove defines the particle system to remove
  27430. * @returns the index where the particle system was in the particle system list
  27431. */
  27432. Scene.prototype.removeParticleSystem = function (toRemove) {
  27433. var index = this.particleSystems.indexOf(toRemove);
  27434. if (index !== -1) {
  27435. this.particleSystems.splice(index, 1);
  27436. }
  27437. return index;
  27438. };
  27439. /**
  27440. * Remove a animation for the list of scene's animations
  27441. * @param toRemove defines the animation to remove
  27442. * @returns the index where the animation was in the animation list
  27443. */
  27444. Scene.prototype.removeAnimation = function (toRemove) {
  27445. var index = this.animations.indexOf(toRemove);
  27446. if (index !== -1) {
  27447. this.animations.splice(index, 1);
  27448. }
  27449. return index;
  27450. };
  27451. /**
  27452. * Removes the given animation group from this scene.
  27453. * @param toRemove The animation group to remove
  27454. * @returns The index of the removed animation group
  27455. */
  27456. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27457. var index = this.animationGroups.indexOf(toRemove);
  27458. if (index !== -1) {
  27459. this.animationGroups.splice(index, 1);
  27460. }
  27461. return index;
  27462. };
  27463. /**
  27464. * Removes the given multi-material from this scene.
  27465. * @param toRemove The multi-material to remove
  27466. * @returns The index of the removed multi-material
  27467. */
  27468. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27469. var index = this.multiMaterials.indexOf(toRemove);
  27470. if (index !== -1) {
  27471. this.multiMaterials.splice(index, 1);
  27472. }
  27473. return index;
  27474. };
  27475. /**
  27476. * Removes the given material from this scene.
  27477. * @param toRemove The material to remove
  27478. * @returns The index of the removed material
  27479. */
  27480. Scene.prototype.removeMaterial = function (toRemove) {
  27481. var index = this.materials.indexOf(toRemove);
  27482. if (index !== -1) {
  27483. this.materials.splice(index, 1);
  27484. }
  27485. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27486. return index;
  27487. };
  27488. /**
  27489. * Removes the given action manager from this scene.
  27490. * @param toRemove The action manager to remove
  27491. * @returns The index of the removed action manager
  27492. */
  27493. Scene.prototype.removeActionManager = function (toRemove) {
  27494. var index = this.actionManagers.indexOf(toRemove);
  27495. if (index !== -1) {
  27496. this.actionManagers.splice(index, 1);
  27497. }
  27498. return index;
  27499. };
  27500. /**
  27501. * Removes the given texture from this scene.
  27502. * @param toRemove The texture to remove
  27503. * @returns The index of the removed texture
  27504. */
  27505. Scene.prototype.removeTexture = function (toRemove) {
  27506. var index = this.textures.indexOf(toRemove);
  27507. if (index !== -1) {
  27508. this.textures.splice(index, 1);
  27509. }
  27510. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27511. return index;
  27512. };
  27513. /**
  27514. * Adds the given light to this scene
  27515. * @param newLight The light to add
  27516. */
  27517. Scene.prototype.addLight = function (newLight) {
  27518. this.lights.push(newLight);
  27519. this.sortLightsByPriority();
  27520. // Add light to all meshes (To support if the light is removed and then readded)
  27521. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27522. var mesh = _a[_i];
  27523. if (mesh._lightSources.indexOf(newLight) === -1) {
  27524. mesh._lightSources.push(newLight);
  27525. mesh._resyncLightSources();
  27526. }
  27527. }
  27528. this.onNewLightAddedObservable.notifyObservers(newLight);
  27529. };
  27530. /**
  27531. * Sorts the list list based on light priorities
  27532. */
  27533. Scene.prototype.sortLightsByPriority = function () {
  27534. if (this.requireLightSorting) {
  27535. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27536. }
  27537. };
  27538. /**
  27539. * Adds the given camera to this scene
  27540. * @param newCamera The camera to add
  27541. */
  27542. Scene.prototype.addCamera = function (newCamera) {
  27543. this.cameras.push(newCamera);
  27544. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27545. };
  27546. /**
  27547. * Adds the given skeleton to this scene
  27548. * @param newSkeleton The skeleton to add
  27549. */
  27550. Scene.prototype.addSkeleton = function (newSkeleton) {
  27551. this.skeletons.push(newSkeleton);
  27552. };
  27553. /**
  27554. * Adds the given particle system to this scene
  27555. * @param newParticleSystem The particle system to add
  27556. */
  27557. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27558. this.particleSystems.push(newParticleSystem);
  27559. };
  27560. /**
  27561. * Adds the given animation to this scene
  27562. * @param newAnimation The animation to add
  27563. */
  27564. Scene.prototype.addAnimation = function (newAnimation) {
  27565. this.animations.push(newAnimation);
  27566. };
  27567. /**
  27568. * Adds the given animation group to this scene.
  27569. * @param newAnimationGroup The animation group to add
  27570. */
  27571. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27572. this.animationGroups.push(newAnimationGroup);
  27573. };
  27574. /**
  27575. * Adds the given multi-material to this scene
  27576. * @param newMultiMaterial The multi-material to add
  27577. */
  27578. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27579. this.multiMaterials.push(newMultiMaterial);
  27580. };
  27581. /**
  27582. * Adds the given material to this scene
  27583. * @param newMaterial The material to add
  27584. */
  27585. Scene.prototype.addMaterial = function (newMaterial) {
  27586. this.materials.push(newMaterial);
  27587. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27588. };
  27589. /**
  27590. * Adds the given morph target to this scene
  27591. * @param newMorphTargetManager The morph target to add
  27592. */
  27593. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27594. this.morphTargetManagers.push(newMorphTargetManager);
  27595. };
  27596. /**
  27597. * Adds the given geometry to this scene
  27598. * @param newGeometry The geometry to add
  27599. */
  27600. Scene.prototype.addGeometry = function (newGeometry) {
  27601. this.geometries.push(newGeometry);
  27602. };
  27603. /**
  27604. * Adds the given action manager to this scene
  27605. * @param newActionManager The action manager to add
  27606. */
  27607. Scene.prototype.addActionManager = function (newActionManager) {
  27608. this.actionManagers.push(newActionManager);
  27609. };
  27610. /**
  27611. * Adds the given texture to this scene.
  27612. * @param newTexture The texture to add
  27613. */
  27614. Scene.prototype.addTexture = function (newTexture) {
  27615. this.textures.push(newTexture);
  27616. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27617. };
  27618. /**
  27619. * Switch active camera
  27620. * @param newCamera defines the new active camera
  27621. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27622. */
  27623. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27624. if (attachControl === void 0) { attachControl = true; }
  27625. var canvas = this._engine.getRenderingCanvas();
  27626. if (!canvas) {
  27627. return;
  27628. }
  27629. if (this.activeCamera) {
  27630. this.activeCamera.detachControl(canvas);
  27631. }
  27632. this.activeCamera = newCamera;
  27633. if (attachControl) {
  27634. newCamera.attachControl(canvas);
  27635. }
  27636. };
  27637. /**
  27638. * sets the active camera of the scene using its ID
  27639. * @param id defines the camera's ID
  27640. * @return the new active camera or null if none found.
  27641. */
  27642. Scene.prototype.setActiveCameraByID = function (id) {
  27643. var camera = this.getCameraByID(id);
  27644. if (camera) {
  27645. this.activeCamera = camera;
  27646. return camera;
  27647. }
  27648. return null;
  27649. };
  27650. /**
  27651. * sets the active camera of the scene using its name
  27652. * @param name defines the camera's name
  27653. * @returns the new active camera or null if none found.
  27654. */
  27655. Scene.prototype.setActiveCameraByName = function (name) {
  27656. var camera = this.getCameraByName(name);
  27657. if (camera) {
  27658. this.activeCamera = camera;
  27659. return camera;
  27660. }
  27661. return null;
  27662. };
  27663. /**
  27664. * get an animation group using its name
  27665. * @param name defines the material's name
  27666. * @return the animation group or null if none found.
  27667. */
  27668. Scene.prototype.getAnimationGroupByName = function (name) {
  27669. for (var index = 0; index < this.animationGroups.length; index++) {
  27670. if (this.animationGroups[index].name === name) {
  27671. return this.animationGroups[index];
  27672. }
  27673. }
  27674. return null;
  27675. };
  27676. /**
  27677. * get a material using its id
  27678. * @param id defines the material's ID
  27679. * @return the material or null if none found.
  27680. */
  27681. Scene.prototype.getMaterialByID = function (id) {
  27682. for (var index = 0; index < this.materials.length; index++) {
  27683. if (this.materials[index].id === id) {
  27684. return this.materials[index];
  27685. }
  27686. }
  27687. return null;
  27688. };
  27689. /**
  27690. * Gets a material using its name
  27691. * @param name defines the material's name
  27692. * @return the material or null if none found.
  27693. */
  27694. Scene.prototype.getMaterialByName = function (name) {
  27695. for (var index = 0; index < this.materials.length; index++) {
  27696. if (this.materials[index].name === name) {
  27697. return this.materials[index];
  27698. }
  27699. }
  27700. return null;
  27701. };
  27702. /**
  27703. * Gets a camera using its id
  27704. * @param id defines the id to look for
  27705. * @returns the camera or null if not found
  27706. */
  27707. Scene.prototype.getCameraByID = function (id) {
  27708. for (var index = 0; index < this.cameras.length; index++) {
  27709. if (this.cameras[index].id === id) {
  27710. return this.cameras[index];
  27711. }
  27712. }
  27713. return null;
  27714. };
  27715. /**
  27716. * Gets a camera using its unique id
  27717. * @param uniqueId defines the unique id to look for
  27718. * @returns the camera or null if not found
  27719. */
  27720. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27721. for (var index = 0; index < this.cameras.length; index++) {
  27722. if (this.cameras[index].uniqueId === uniqueId) {
  27723. return this.cameras[index];
  27724. }
  27725. }
  27726. return null;
  27727. };
  27728. /**
  27729. * Gets a camera using its name
  27730. * @param name defines the camera's name
  27731. * @return the camera or null if none found.
  27732. */
  27733. Scene.prototype.getCameraByName = function (name) {
  27734. for (var index = 0; index < this.cameras.length; index++) {
  27735. if (this.cameras[index].name === name) {
  27736. return this.cameras[index];
  27737. }
  27738. }
  27739. return null;
  27740. };
  27741. /**
  27742. * Gets a bone using its id
  27743. * @param id defines the bone's id
  27744. * @return the bone or null if not found
  27745. */
  27746. Scene.prototype.getBoneByID = function (id) {
  27747. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27748. var skeleton = this.skeletons[skeletonIndex];
  27749. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27750. if (skeleton.bones[boneIndex].id === id) {
  27751. return skeleton.bones[boneIndex];
  27752. }
  27753. }
  27754. }
  27755. return null;
  27756. };
  27757. /**
  27758. * Gets a bone using its id
  27759. * @param name defines the bone's name
  27760. * @return the bone or null if not found
  27761. */
  27762. Scene.prototype.getBoneByName = function (name) {
  27763. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27764. var skeleton = this.skeletons[skeletonIndex];
  27765. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27766. if (skeleton.bones[boneIndex].name === name) {
  27767. return skeleton.bones[boneIndex];
  27768. }
  27769. }
  27770. }
  27771. return null;
  27772. };
  27773. /**
  27774. * Gets a light node using its name
  27775. * @param name defines the the light's name
  27776. * @return the light or null if none found.
  27777. */
  27778. Scene.prototype.getLightByName = function (name) {
  27779. for (var index = 0; index < this.lights.length; index++) {
  27780. if (this.lights[index].name === name) {
  27781. return this.lights[index];
  27782. }
  27783. }
  27784. return null;
  27785. };
  27786. /**
  27787. * Gets a light node using its id
  27788. * @param id defines the light's id
  27789. * @return the light or null if none found.
  27790. */
  27791. Scene.prototype.getLightByID = function (id) {
  27792. for (var index = 0; index < this.lights.length; index++) {
  27793. if (this.lights[index].id === id) {
  27794. return this.lights[index];
  27795. }
  27796. }
  27797. return null;
  27798. };
  27799. /**
  27800. * Gets a light node using its scene-generated unique ID
  27801. * @param uniqueId defines the light's unique id
  27802. * @return the light or null if none found.
  27803. */
  27804. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27805. for (var index = 0; index < this.lights.length; index++) {
  27806. if (this.lights[index].uniqueId === uniqueId) {
  27807. return this.lights[index];
  27808. }
  27809. }
  27810. return null;
  27811. };
  27812. /**
  27813. * Gets a particle system by id
  27814. * @param id defines the particle system id
  27815. * @return the corresponding system or null if none found
  27816. */
  27817. Scene.prototype.getParticleSystemByID = function (id) {
  27818. for (var index = 0; index < this.particleSystems.length; index++) {
  27819. if (this.particleSystems[index].id === id) {
  27820. return this.particleSystems[index];
  27821. }
  27822. }
  27823. return null;
  27824. };
  27825. /**
  27826. * Gets a geometry using its ID
  27827. * @param id defines the geometry's id
  27828. * @return the geometry or null if none found.
  27829. */
  27830. Scene.prototype.getGeometryByID = function (id) {
  27831. for (var index = 0; index < this.geometries.length; index++) {
  27832. if (this.geometries[index].id === id) {
  27833. return this.geometries[index];
  27834. }
  27835. }
  27836. return null;
  27837. };
  27838. /**
  27839. * Add a new geometry to this scene
  27840. * @param geometry defines the geometry to be added to the scene.
  27841. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27842. * @return a boolean defining if the geometry was added or not
  27843. */
  27844. Scene.prototype.pushGeometry = function (geometry, force) {
  27845. if (!force && this.getGeometryByID(geometry.id)) {
  27846. return false;
  27847. }
  27848. this.geometries.push(geometry);
  27849. //notify the collision coordinator
  27850. if (this.collisionCoordinator) {
  27851. this.collisionCoordinator.onGeometryAdded(geometry);
  27852. }
  27853. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27854. return true;
  27855. };
  27856. /**
  27857. * Removes an existing geometry
  27858. * @param geometry defines the geometry to be removed from the scene
  27859. * @return a boolean defining if the geometry was removed or not
  27860. */
  27861. Scene.prototype.removeGeometry = function (geometry) {
  27862. var index = this.geometries.indexOf(geometry);
  27863. if (index > -1) {
  27864. this.geometries.splice(index, 1);
  27865. //notify the collision coordinator
  27866. if (this.collisionCoordinator) {
  27867. this.collisionCoordinator.onGeometryDeleted(geometry);
  27868. }
  27869. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27870. return true;
  27871. }
  27872. return false;
  27873. };
  27874. /**
  27875. * Gets the list of geometries attached to the scene
  27876. * @returns an array of Geometry
  27877. */
  27878. Scene.prototype.getGeometries = function () {
  27879. return this.geometries;
  27880. };
  27881. /**
  27882. * Gets the first added mesh found of a given ID
  27883. * @param id defines the id to search for
  27884. * @return the mesh found or null if not found at all
  27885. */
  27886. Scene.prototype.getMeshByID = function (id) {
  27887. for (var index = 0; index < this.meshes.length; index++) {
  27888. if (this.meshes[index].id === id) {
  27889. return this.meshes[index];
  27890. }
  27891. }
  27892. return null;
  27893. };
  27894. /**
  27895. * Gets a list of meshes using their id
  27896. * @param id defines the id to search for
  27897. * @returns a list of meshes
  27898. */
  27899. Scene.prototype.getMeshesByID = function (id) {
  27900. return this.meshes.filter(function (m) {
  27901. return m.id === id;
  27902. });
  27903. };
  27904. /**
  27905. * Gets the first added transform node found of a given ID
  27906. * @param id defines the id to search for
  27907. * @return the found transform node or null if not found at all.
  27908. */
  27909. Scene.prototype.getTransformNodeByID = function (id) {
  27910. for (var index = 0; index < this.transformNodes.length; index++) {
  27911. if (this.transformNodes[index].id === id) {
  27912. return this.transformNodes[index];
  27913. }
  27914. }
  27915. return null;
  27916. };
  27917. /**
  27918. * Gets a list of transform nodes using their id
  27919. * @param id defines the id to search for
  27920. * @returns a list of transform nodes
  27921. */
  27922. Scene.prototype.getTransformNodesByID = function (id) {
  27923. return this.transformNodes.filter(function (m) {
  27924. return m.id === id;
  27925. });
  27926. };
  27927. /**
  27928. * Gets a mesh with its auto-generated unique id
  27929. * @param uniqueId defines the unique id to search for
  27930. * @return the found mesh or null if not found at all.
  27931. */
  27932. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27933. for (var index = 0; index < this.meshes.length; index++) {
  27934. if (this.meshes[index].uniqueId === uniqueId) {
  27935. return this.meshes[index];
  27936. }
  27937. }
  27938. return null;
  27939. };
  27940. /**
  27941. * Gets a the last added mesh using a given id
  27942. * @param id defines the id to search for
  27943. * @return the found mesh or null if not found at all.
  27944. */
  27945. Scene.prototype.getLastMeshByID = function (id) {
  27946. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27947. if (this.meshes[index].id === id) {
  27948. return this.meshes[index];
  27949. }
  27950. }
  27951. return null;
  27952. };
  27953. /**
  27954. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27955. * @param id defines the id to search for
  27956. * @return the found node or null if not found at all
  27957. */
  27958. Scene.prototype.getLastEntryByID = function (id) {
  27959. var index;
  27960. for (index = this.meshes.length - 1; index >= 0; index--) {
  27961. if (this.meshes[index].id === id) {
  27962. return this.meshes[index];
  27963. }
  27964. }
  27965. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27966. if (this.transformNodes[index].id === id) {
  27967. return this.transformNodes[index];
  27968. }
  27969. }
  27970. for (index = this.cameras.length - 1; index >= 0; index--) {
  27971. if (this.cameras[index].id === id) {
  27972. return this.cameras[index];
  27973. }
  27974. }
  27975. for (index = this.lights.length - 1; index >= 0; index--) {
  27976. if (this.lights[index].id === id) {
  27977. return this.lights[index];
  27978. }
  27979. }
  27980. return null;
  27981. };
  27982. /**
  27983. * Gets a node (Mesh, Camera, Light) using a given id
  27984. * @param id defines the id to search for
  27985. * @return the found node or null if not found at all
  27986. */
  27987. Scene.prototype.getNodeByID = function (id) {
  27988. var mesh = this.getMeshByID(id);
  27989. if (mesh) {
  27990. return mesh;
  27991. }
  27992. var light = this.getLightByID(id);
  27993. if (light) {
  27994. return light;
  27995. }
  27996. var camera = this.getCameraByID(id);
  27997. if (camera) {
  27998. return camera;
  27999. }
  28000. var bone = this.getBoneByID(id);
  28001. return bone;
  28002. };
  28003. /**
  28004. * Gets a node (Mesh, Camera, Light) using a given name
  28005. * @param name defines the name to search for
  28006. * @return the found node or null if not found at all.
  28007. */
  28008. Scene.prototype.getNodeByName = function (name) {
  28009. var mesh = this.getMeshByName(name);
  28010. if (mesh) {
  28011. return mesh;
  28012. }
  28013. var light = this.getLightByName(name);
  28014. if (light) {
  28015. return light;
  28016. }
  28017. var camera = this.getCameraByName(name);
  28018. if (camera) {
  28019. return camera;
  28020. }
  28021. var bone = this.getBoneByName(name);
  28022. return bone;
  28023. };
  28024. /**
  28025. * Gets a mesh using a given name
  28026. * @param name defines the name to search for
  28027. * @return the found mesh or null if not found at all.
  28028. */
  28029. Scene.prototype.getMeshByName = function (name) {
  28030. for (var index = 0; index < this.meshes.length; index++) {
  28031. if (this.meshes[index].name === name) {
  28032. return this.meshes[index];
  28033. }
  28034. }
  28035. return null;
  28036. };
  28037. /**
  28038. * Gets a transform node using a given name
  28039. * @param name defines the name to search for
  28040. * @return the found transform node or null if not found at all.
  28041. */
  28042. Scene.prototype.getTransformNodeByName = function (name) {
  28043. for (var index = 0; index < this.transformNodes.length; index++) {
  28044. if (this.transformNodes[index].name === name) {
  28045. return this.transformNodes[index];
  28046. }
  28047. }
  28048. return null;
  28049. };
  28050. /**
  28051. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28052. * @param id defines the id to search for
  28053. * @return the found skeleton or null if not found at all.
  28054. */
  28055. Scene.prototype.getLastSkeletonByID = function (id) {
  28056. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28057. if (this.skeletons[index].id === id) {
  28058. return this.skeletons[index];
  28059. }
  28060. }
  28061. return null;
  28062. };
  28063. /**
  28064. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28065. * @param id defines the id to search for
  28066. * @return the found skeleton or null if not found at all.
  28067. */
  28068. Scene.prototype.getSkeletonById = function (id) {
  28069. for (var index = 0; index < this.skeletons.length; index++) {
  28070. if (this.skeletons[index].id === id) {
  28071. return this.skeletons[index];
  28072. }
  28073. }
  28074. return null;
  28075. };
  28076. /**
  28077. * Gets a skeleton using a given name
  28078. * @param name defines the name to search for
  28079. * @return the found skeleton or null if not found at all.
  28080. */
  28081. Scene.prototype.getSkeletonByName = function (name) {
  28082. for (var index = 0; index < this.skeletons.length; index++) {
  28083. if (this.skeletons[index].name === name) {
  28084. return this.skeletons[index];
  28085. }
  28086. }
  28087. return null;
  28088. };
  28089. /**
  28090. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28091. * @param id defines the id to search for
  28092. * @return the found morph target manager or null if not found at all.
  28093. */
  28094. Scene.prototype.getMorphTargetManagerById = function (id) {
  28095. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28096. if (this.morphTargetManagers[index].uniqueId === id) {
  28097. return this.morphTargetManagers[index];
  28098. }
  28099. }
  28100. return null;
  28101. };
  28102. /**
  28103. * Gets a boolean indicating if the given mesh is active
  28104. * @param mesh defines the mesh to look for
  28105. * @returns true if the mesh is in the active list
  28106. */
  28107. Scene.prototype.isActiveMesh = function (mesh) {
  28108. return (this._activeMeshes.indexOf(mesh) !== -1);
  28109. };
  28110. Object.defineProperty(Scene.prototype, "uid", {
  28111. /**
  28112. * Return a unique id as a string which can serve as an identifier for the scene
  28113. */
  28114. get: function () {
  28115. if (!this._uid) {
  28116. this._uid = BABYLON.Tools.RandomId();
  28117. }
  28118. return this._uid;
  28119. },
  28120. enumerable: true,
  28121. configurable: true
  28122. });
  28123. /**
  28124. * Add an externaly attached data from its key.
  28125. * This method call will fail and return false, if such key already exists.
  28126. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28127. * @param key the unique key that identifies the data
  28128. * @param data the data object to associate to the key for this Engine instance
  28129. * @return true if no such key were already present and the data was added successfully, false otherwise
  28130. */
  28131. Scene.prototype.addExternalData = function (key, data) {
  28132. if (!this._externalData) {
  28133. this._externalData = new BABYLON.StringDictionary();
  28134. }
  28135. return this._externalData.add(key, data);
  28136. };
  28137. /**
  28138. * Get an externaly attached data from its key
  28139. * @param key the unique key that identifies the data
  28140. * @return the associated data, if present (can be null), or undefined if not present
  28141. */
  28142. Scene.prototype.getExternalData = function (key) {
  28143. if (!this._externalData) {
  28144. return null;
  28145. }
  28146. return this._externalData.get(key);
  28147. };
  28148. /**
  28149. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28150. * @param key the unique key that identifies the data
  28151. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28152. * @return the associated data, can be null if the factory returned null.
  28153. */
  28154. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28155. if (!this._externalData) {
  28156. this._externalData = new BABYLON.StringDictionary();
  28157. }
  28158. return this._externalData.getOrAddWithFactory(key, factory);
  28159. };
  28160. /**
  28161. * Remove an externaly attached data from the Engine instance
  28162. * @param key the unique key that identifies the data
  28163. * @return true if the data was successfully removed, false if it doesn't exist
  28164. */
  28165. Scene.prototype.removeExternalData = function (key) {
  28166. return this._externalData.remove(key);
  28167. };
  28168. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28169. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28170. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28171. var step = _a[_i];
  28172. step.action(mesh, subMesh);
  28173. }
  28174. var material = subMesh.getMaterial();
  28175. if (material !== null && material !== undefined) {
  28176. // Render targets
  28177. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28178. if (this._processedMaterials.indexOf(material) === -1) {
  28179. this._processedMaterials.push(material);
  28180. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28181. }
  28182. }
  28183. // Dispatch
  28184. this._activeIndices.addCount(subMesh.indexCount, false);
  28185. this._renderingManager.dispatch(subMesh, mesh, material);
  28186. }
  28187. }
  28188. };
  28189. /**
  28190. * Clear the processed materials smart array preventing retention point in material dispose.
  28191. */
  28192. Scene.prototype.freeProcessedMaterials = function () {
  28193. this._processedMaterials.dispose();
  28194. };
  28195. /**
  28196. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28197. */
  28198. Scene.prototype.freeActiveMeshes = function () {
  28199. this._activeMeshes.dispose();
  28200. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28201. this.activeCamera._activeMeshes.dispose();
  28202. }
  28203. if (this.activeCameras) {
  28204. for (var i = 0; i < this.activeCameras.length; i++) {
  28205. var activeCamera = this.activeCameras[i];
  28206. if (activeCamera && activeCamera._activeMeshes) {
  28207. activeCamera._activeMeshes.dispose();
  28208. }
  28209. }
  28210. }
  28211. };
  28212. /**
  28213. * Clear the info related to rendering groups preventing retention points during dispose.
  28214. */
  28215. Scene.prototype.freeRenderingGroups = function () {
  28216. if (this._renderingManager) {
  28217. this._renderingManager.freeRenderingGroups();
  28218. }
  28219. if (this.textures) {
  28220. for (var i = 0; i < this.textures.length; i++) {
  28221. var texture = this.textures[i];
  28222. if (texture && texture.renderList) {
  28223. texture.freeRenderingGroups();
  28224. }
  28225. }
  28226. }
  28227. };
  28228. /** @hidden */
  28229. Scene.prototype._isInIntermediateRendering = function () {
  28230. return this._intermediateRendering;
  28231. };
  28232. /**
  28233. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28234. * @returns the current scene
  28235. */
  28236. Scene.prototype.freezeActiveMeshes = function () {
  28237. if (!this.activeCamera) {
  28238. return this;
  28239. }
  28240. if (!this._frustumPlanes) {
  28241. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28242. }
  28243. this._evaluateActiveMeshes();
  28244. this._activeMeshesFrozen = true;
  28245. return this;
  28246. };
  28247. /**
  28248. * Use this function to restart evaluating active meshes on every frame
  28249. * @returns the current scene
  28250. */
  28251. Scene.prototype.unfreezeActiveMeshes = function () {
  28252. this._activeMeshesFrozen = false;
  28253. return this;
  28254. };
  28255. Scene.prototype._evaluateActiveMeshes = function () {
  28256. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28257. return;
  28258. }
  28259. if (!this.activeCamera) {
  28260. return;
  28261. }
  28262. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28263. this.activeCamera._activeMeshes.reset();
  28264. this._activeMeshes.reset();
  28265. this._renderingManager.reset();
  28266. this._processedMaterials.reset();
  28267. this._activeParticleSystems.reset();
  28268. this._activeSkeletons.reset();
  28269. this._softwareSkinnedMeshes.reset();
  28270. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28271. var step = _a[_i];
  28272. step.action();
  28273. }
  28274. // Determine mesh candidates
  28275. var meshes = this.getActiveMeshCandidates();
  28276. // Check each mesh
  28277. var len = meshes.length;
  28278. for (var i = 0; i < len; i++) {
  28279. var mesh = meshes.data[i];
  28280. if (mesh.isBlocked) {
  28281. continue;
  28282. }
  28283. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28284. if (!mesh.isReady() || !mesh.isEnabled()) {
  28285. continue;
  28286. }
  28287. mesh.computeWorldMatrix();
  28288. // Intersections
  28289. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28290. this._meshesForIntersections.pushNoDuplicate(mesh);
  28291. }
  28292. // Switch to current LOD
  28293. var meshLOD = mesh.getLOD(this.activeCamera);
  28294. if (meshLOD === undefined || meshLOD === null) {
  28295. continue;
  28296. }
  28297. mesh._preActivate();
  28298. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28299. this._activeMeshes.push(mesh);
  28300. this.activeCamera._activeMeshes.push(mesh);
  28301. mesh._activate(this._renderId);
  28302. if (meshLOD !== mesh) {
  28303. meshLOD._activate(this._renderId);
  28304. }
  28305. this._activeMesh(mesh, meshLOD);
  28306. }
  28307. }
  28308. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28309. // Particle systems
  28310. if (this.particlesEnabled) {
  28311. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28312. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28313. var particleSystem = this.particleSystems[particleIndex];
  28314. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28315. continue;
  28316. }
  28317. var emitter = particleSystem.emitter;
  28318. if (!emitter.position || emitter.isEnabled()) {
  28319. this._activeParticleSystems.push(particleSystem);
  28320. particleSystem.animate();
  28321. this._renderingManager.dispatchParticles(particleSystem);
  28322. }
  28323. }
  28324. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28325. }
  28326. };
  28327. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28328. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28329. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28330. mesh.skeleton.prepare();
  28331. }
  28332. if (!mesh.computeBonesUsingShaders) {
  28333. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28334. }
  28335. }
  28336. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28337. var step = _a[_i];
  28338. step.action(sourceMesh, mesh);
  28339. }
  28340. if (mesh !== undefined && mesh !== null
  28341. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28342. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28343. var len = subMeshes.length;
  28344. for (var i = 0; i < len; i++) {
  28345. var subMesh = subMeshes.data[i];
  28346. this._evaluateSubMesh(subMesh, mesh);
  28347. }
  28348. }
  28349. };
  28350. /**
  28351. * Update the transform matrix to update from the current active camera
  28352. * @param force defines a boolean used to force the update even if cache is up to date
  28353. */
  28354. Scene.prototype.updateTransformMatrix = function (force) {
  28355. if (!this.activeCamera) {
  28356. return;
  28357. }
  28358. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28359. };
  28360. /**
  28361. * 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)
  28362. * @param alternateCamera defines the camera to use
  28363. */
  28364. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28365. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28366. };
  28367. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28368. if (camera && camera._skipRendering) {
  28369. return;
  28370. }
  28371. var engine = this._engine;
  28372. this.activeCamera = camera;
  28373. if (!this.activeCamera)
  28374. throw new Error("Active camera not set");
  28375. // Viewport
  28376. engine.setViewport(this.activeCamera.viewport);
  28377. // Camera
  28378. this.resetCachedMaterial();
  28379. this._renderId++;
  28380. this.updateTransformMatrix();
  28381. if (camera._alternateCamera) {
  28382. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28383. this._alternateRendering = true;
  28384. }
  28385. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28386. // Meshes
  28387. this._evaluateActiveMeshes();
  28388. // Software skinning
  28389. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28390. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28391. mesh.applySkeleton(mesh.skeleton);
  28392. }
  28393. // Render targets
  28394. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28395. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28396. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28397. }
  28398. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28399. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28400. }
  28401. // Collects render targets from external components.
  28402. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28403. var step = _a[_i];
  28404. step.action(this._renderTargets);
  28405. }
  28406. if (this.renderTargetsEnabled) {
  28407. this._intermediateRendering = true;
  28408. if (this._renderTargets.length > 0) {
  28409. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28410. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28411. var renderTarget = this._renderTargets.data[renderIndex];
  28412. if (renderTarget._shouldRender()) {
  28413. this._renderId++;
  28414. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28415. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28416. }
  28417. }
  28418. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28419. this._renderId++;
  28420. }
  28421. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28422. var step = _c[_b];
  28423. step.action(this.activeCamera);
  28424. }
  28425. this._intermediateRendering = false;
  28426. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28427. }
  28428. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28429. // Prepare Frame
  28430. if (this.postProcessManager) {
  28431. this.postProcessManager._prepareFrame();
  28432. }
  28433. // Before Camera Draw
  28434. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28435. var step = _e[_d];
  28436. step.action(this.activeCamera);
  28437. }
  28438. // Render
  28439. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28440. this._renderingManager.render(null, null, true, true);
  28441. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28442. // After Camera Draw
  28443. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28444. var step = _g[_f];
  28445. step.action(this.activeCamera);
  28446. }
  28447. // Finalize frame
  28448. if (this.postProcessManager) {
  28449. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28450. }
  28451. // Reset some special arrays
  28452. this._renderTargets.reset();
  28453. this._alternateRendering = false;
  28454. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28455. };
  28456. Scene.prototype._processSubCameras = function (camera) {
  28457. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28458. this._renderForCamera(camera);
  28459. return;
  28460. }
  28461. // rig cameras
  28462. for (var index = 0; index < camera._rigCameras.length; index++) {
  28463. this._renderForCamera(camera._rigCameras[index], camera);
  28464. }
  28465. this.activeCamera = camera;
  28466. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28467. };
  28468. Scene.prototype._checkIntersections = function () {
  28469. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28470. var sourceMesh = this._meshesForIntersections.data[index];
  28471. if (!sourceMesh.actionManager) {
  28472. continue;
  28473. }
  28474. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28475. var action = sourceMesh.actionManager.actions[actionIndex];
  28476. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28477. var parameters = action.getTriggerParameter();
  28478. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28479. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28480. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28481. if (areIntersecting && currentIntersectionInProgress === -1) {
  28482. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28483. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28484. sourceMesh._intersectionsInProgress.push(otherMesh);
  28485. }
  28486. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28487. sourceMesh._intersectionsInProgress.push(otherMesh);
  28488. }
  28489. }
  28490. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28491. //They intersected, and now they don't.
  28492. //is this trigger an exit trigger? execute an event.
  28493. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28494. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28495. }
  28496. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28497. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28498. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28499. return otherMesh === parameterMesh;
  28500. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28501. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28502. }
  28503. }
  28504. }
  28505. }
  28506. }
  28507. };
  28508. /** @hidden */
  28509. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28510. // Do nothing. Code will be replaced if physics engine component is referenced
  28511. };
  28512. /**
  28513. * Render the scene
  28514. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28515. */
  28516. Scene.prototype.render = function (updateCameras) {
  28517. if (updateCameras === void 0) { updateCameras = true; }
  28518. if (this.isDisposed) {
  28519. return;
  28520. }
  28521. this._frameId++;
  28522. // Register components that have been associated lately to the scene.
  28523. this._registerTransientComponents();
  28524. this._activeParticles.fetchNewFrame();
  28525. this._totalVertices.fetchNewFrame();
  28526. this._activeIndices.fetchNewFrame();
  28527. this._activeBones.fetchNewFrame();
  28528. this._meshesForIntersections.reset();
  28529. this.resetCachedMaterial();
  28530. this.onBeforeAnimationsObservable.notifyObservers(this);
  28531. // Actions
  28532. if (this.actionManager) {
  28533. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28534. }
  28535. if (this._engine.isDeterministicLockStep()) {
  28536. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28537. var defaultFPS = (60.0 / 1000.0);
  28538. var defaultFrameTime = this.getDeterministicFrameTime();
  28539. var stepsTaken = 0;
  28540. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28541. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28542. internalSteps = Math.min(internalSteps, maxSubSteps);
  28543. do {
  28544. this.onBeforeStepObservable.notifyObservers(this);
  28545. // Animations
  28546. this._animationRatio = defaultFrameTime * defaultFPS;
  28547. this._animate();
  28548. this.onAfterAnimationsObservable.notifyObservers(this);
  28549. // Physics
  28550. this._advancePhysicsEngineStep(defaultFrameTime);
  28551. this.onAfterStepObservable.notifyObservers(this);
  28552. this._currentStepId++;
  28553. stepsTaken++;
  28554. deltaTime -= defaultFrameTime;
  28555. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28556. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28557. }
  28558. else {
  28559. // Animations
  28560. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28561. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28562. this._animate();
  28563. this.onAfterAnimationsObservable.notifyObservers(this);
  28564. // Physics
  28565. this._advancePhysicsEngineStep(deltaTime);
  28566. }
  28567. // Before camera update steps
  28568. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28569. var step = _a[_i];
  28570. step.action();
  28571. }
  28572. // Update Cameras
  28573. if (updateCameras) {
  28574. if (this.activeCameras.length > 0) {
  28575. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28576. var camera = this.activeCameras[cameraIndex];
  28577. camera.update();
  28578. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28579. // rig cameras
  28580. for (var index = 0; index < camera._rigCameras.length; index++) {
  28581. camera._rigCameras[index].update();
  28582. }
  28583. }
  28584. }
  28585. }
  28586. else if (this.activeCamera) {
  28587. this.activeCamera.update();
  28588. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28589. // rig cameras
  28590. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28591. this.activeCamera._rigCameras[index].update();
  28592. }
  28593. }
  28594. }
  28595. }
  28596. // Before render
  28597. this.onBeforeRenderObservable.notifyObservers(this);
  28598. // Customs render targets
  28599. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28600. var engine = this.getEngine();
  28601. var currentActiveCamera = this.activeCamera;
  28602. if (this.renderTargetsEnabled) {
  28603. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28604. this._intermediateRendering = true;
  28605. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28606. var renderTarget = this.customRenderTargets[customIndex];
  28607. if (renderTarget._shouldRender()) {
  28608. this._renderId++;
  28609. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28610. if (!this.activeCamera)
  28611. throw new Error("Active camera not set");
  28612. // Viewport
  28613. engine.setViewport(this.activeCamera.viewport);
  28614. // Camera
  28615. this.updateTransformMatrix();
  28616. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28617. }
  28618. }
  28619. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28620. this._intermediateRendering = false;
  28621. this._renderId++;
  28622. }
  28623. // Restore back buffer
  28624. if (this.customRenderTargets.length > 0) {
  28625. engine.restoreDefaultFramebuffer();
  28626. }
  28627. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28628. this.activeCamera = currentActiveCamera;
  28629. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28630. var step = _c[_b];
  28631. step.action();
  28632. }
  28633. // Clear
  28634. if (this.autoClearDepthAndStencil || this.autoClear) {
  28635. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28636. }
  28637. // Collects render targets from external components.
  28638. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28639. var step = _e[_d];
  28640. step.action(this._renderTargets);
  28641. }
  28642. // Multi-cameras?
  28643. if (this.activeCameras.length > 0) {
  28644. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28645. if (cameraIndex > 0) {
  28646. this._engine.clear(null, false, true, true);
  28647. }
  28648. this._processSubCameras(this.activeCameras[cameraIndex]);
  28649. }
  28650. }
  28651. else {
  28652. if (!this.activeCamera) {
  28653. throw new Error("No camera defined");
  28654. }
  28655. this._processSubCameras(this.activeCamera);
  28656. }
  28657. // Intersection checks
  28658. this._checkIntersections();
  28659. // Executes the after render stage actions.
  28660. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28661. var step = _g[_f];
  28662. step.action();
  28663. }
  28664. // After render
  28665. if (this.afterRender) {
  28666. this.afterRender();
  28667. }
  28668. this.onAfterRenderObservable.notifyObservers(this);
  28669. // Cleaning
  28670. if (this._toBeDisposed.length) {
  28671. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28672. var data = this._toBeDisposed[index];
  28673. if (data) {
  28674. data.dispose();
  28675. }
  28676. }
  28677. this._toBeDisposed = [];
  28678. }
  28679. if (this.dumpNextRenderTargets) {
  28680. this.dumpNextRenderTargets = false;
  28681. }
  28682. this._activeBones.addCount(0, true);
  28683. this._activeIndices.addCount(0, true);
  28684. this._activeParticles.addCount(0, true);
  28685. };
  28686. /**
  28687. * Freeze all materials
  28688. * A frozen material will not be updatable but should be faster to render
  28689. */
  28690. Scene.prototype.freezeMaterials = function () {
  28691. for (var i = 0; i < this.materials.length; i++) {
  28692. this.materials[i].freeze();
  28693. }
  28694. };
  28695. /**
  28696. * Unfreeze all materials
  28697. * A frozen material will not be updatable but should be faster to render
  28698. */
  28699. Scene.prototype.unfreezeMaterials = function () {
  28700. for (var i = 0; i < this.materials.length; i++) {
  28701. this.materials[i].unfreeze();
  28702. }
  28703. };
  28704. /**
  28705. * Releases all held ressources
  28706. */
  28707. Scene.prototype.dispose = function () {
  28708. this.beforeRender = null;
  28709. this.afterRender = null;
  28710. this.skeletons = [];
  28711. this.morphTargetManagers = [];
  28712. this._transientComponents = [];
  28713. this._isReadyForMeshStage.clear();
  28714. this._beforeEvaluateActiveMeshStage.clear();
  28715. this._evaluateSubMeshStage.clear();
  28716. this._activeMeshStage.clear();
  28717. this._cameraDrawRenderTargetStage.clear();
  28718. this._beforeCameraDrawStage.clear();
  28719. this._beforeRenderingGroupDrawStage.clear();
  28720. this._beforeRenderingMeshStage.clear();
  28721. this._afterRenderingMeshStage.clear();
  28722. this._afterRenderingGroupDrawStage.clear();
  28723. this._afterCameraDrawStage.clear();
  28724. this._afterRenderStage.clear();
  28725. this._beforeCameraUpdateStage.clear();
  28726. this._beforeClearStage.clear();
  28727. this._gatherRenderTargetsStage.clear();
  28728. this._gatherActiveCameraRenderTargetsStage.clear();
  28729. this._pointerMoveStage.clear();
  28730. this._pointerDownStage.clear();
  28731. this._pointerUpStage.clear();
  28732. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28733. var component = _a[_i];
  28734. component.dispose();
  28735. }
  28736. this.importedMeshesFiles = new Array();
  28737. this.stopAllAnimations();
  28738. this.resetCachedMaterial();
  28739. // Smart arrays
  28740. if (this.activeCamera) {
  28741. this.activeCamera._activeMeshes.dispose();
  28742. this.activeCamera = null;
  28743. }
  28744. this._activeMeshes.dispose();
  28745. this._renderingManager.dispose();
  28746. this._processedMaterials.dispose();
  28747. this._activeParticleSystems.dispose();
  28748. this._activeSkeletons.dispose();
  28749. this._softwareSkinnedMeshes.dispose();
  28750. this._renderTargets.dispose();
  28751. this._registeredForLateAnimationBindings.dispose();
  28752. this._meshesForIntersections.dispose();
  28753. this._toBeDisposed = [];
  28754. // Abort active requests
  28755. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28756. var request = _c[_b];
  28757. request.abort();
  28758. }
  28759. // Events
  28760. this.onDisposeObservable.notifyObservers(this);
  28761. this.onDisposeObservable.clear();
  28762. this.onBeforeRenderObservable.clear();
  28763. this.onAfterRenderObservable.clear();
  28764. this.onBeforeRenderTargetsRenderObservable.clear();
  28765. this.onAfterRenderTargetsRenderObservable.clear();
  28766. this.onAfterStepObservable.clear();
  28767. this.onBeforeStepObservable.clear();
  28768. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28769. this.onAfterActiveMeshesEvaluationObservable.clear();
  28770. this.onBeforeParticlesRenderingObservable.clear();
  28771. this.onAfterParticlesRenderingObservable.clear();
  28772. this.onBeforeDrawPhaseObservable.clear();
  28773. this.onAfterDrawPhaseObservable.clear();
  28774. this.onBeforeAnimationsObservable.clear();
  28775. this.onAfterAnimationsObservable.clear();
  28776. this.onDataLoadedObservable.clear();
  28777. this.onBeforeRenderingGroupObservable.clear();
  28778. this.onAfterRenderingGroupObservable.clear();
  28779. this.onMeshImportedObservable.clear();
  28780. this.onBeforeCameraRenderObservable.clear();
  28781. this.onAfterCameraRenderObservable.clear();
  28782. this.onReadyObservable.clear();
  28783. this.onNewCameraAddedObservable.clear();
  28784. this.onCameraRemovedObservable.clear();
  28785. this.onNewLightAddedObservable.clear();
  28786. this.onLightRemovedObservable.clear();
  28787. this.onNewGeometryAddedObservable.clear();
  28788. this.onGeometryRemovedObservable.clear();
  28789. this.onNewTransformNodeAddedObservable.clear();
  28790. this.onTransformNodeRemovedObservable.clear();
  28791. this.onNewMeshAddedObservable.clear();
  28792. this.onMeshRemovedObservable.clear();
  28793. this.onNewMaterialAddedObservable.clear();
  28794. this.onMaterialRemovedObservable.clear();
  28795. this.onNewTextureAddedObservable.clear();
  28796. this.onTextureRemovedObservable.clear();
  28797. this.onPrePointerObservable.clear();
  28798. this.onPointerObservable.clear();
  28799. this.onPreKeyboardObservable.clear();
  28800. this.onKeyboardObservable.clear();
  28801. this.detachControl();
  28802. // Detach cameras
  28803. var canvas = this._engine.getRenderingCanvas();
  28804. if (canvas) {
  28805. var index;
  28806. for (index = 0; index < this.cameras.length; index++) {
  28807. this.cameras[index].detachControl(canvas);
  28808. }
  28809. }
  28810. // Release animation groups
  28811. while (this.animationGroups.length) {
  28812. this.animationGroups[0].dispose();
  28813. }
  28814. // Release lights
  28815. while (this.lights.length) {
  28816. this.lights[0].dispose();
  28817. }
  28818. // Release meshes
  28819. while (this.meshes.length) {
  28820. this.meshes[0].dispose(true);
  28821. }
  28822. while (this.transformNodes.length) {
  28823. this.removeTransformNode(this.transformNodes[0]);
  28824. }
  28825. // Release cameras
  28826. while (this.cameras.length) {
  28827. this.cameras[0].dispose();
  28828. }
  28829. // Release materials
  28830. if (this.defaultMaterial) {
  28831. this.defaultMaterial.dispose();
  28832. }
  28833. while (this.multiMaterials.length) {
  28834. this.multiMaterials[0].dispose();
  28835. }
  28836. while (this.materials.length) {
  28837. this.materials[0].dispose();
  28838. }
  28839. // Release particles
  28840. while (this.particleSystems.length) {
  28841. this.particleSystems[0].dispose();
  28842. }
  28843. // Release postProcesses
  28844. while (this.postProcesses.length) {
  28845. this.postProcesses[0].dispose();
  28846. }
  28847. // Release textures
  28848. while (this.textures.length) {
  28849. this.textures[0].dispose();
  28850. }
  28851. // Release UBO
  28852. this._sceneUbo.dispose();
  28853. if (this._alternateSceneUbo) {
  28854. this._alternateSceneUbo.dispose();
  28855. }
  28856. // Post-processes
  28857. this.postProcessManager.dispose();
  28858. // Remove from engine
  28859. index = this._engine.scenes.indexOf(this);
  28860. if (index > -1) {
  28861. this._engine.scenes.splice(index, 1);
  28862. }
  28863. this._engine.wipeCaches(true);
  28864. this._isDisposed = true;
  28865. };
  28866. Object.defineProperty(Scene.prototype, "isDisposed", {
  28867. /**
  28868. * Gets if the scene is already disposed
  28869. */
  28870. get: function () {
  28871. return this._isDisposed;
  28872. },
  28873. enumerable: true,
  28874. configurable: true
  28875. });
  28876. /**
  28877. * Call this function to reduce memory footprint of the scene.
  28878. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28879. */
  28880. Scene.prototype.clearCachedVertexData = function () {
  28881. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28882. var mesh = this.meshes[meshIndex];
  28883. var geometry = mesh.geometry;
  28884. if (geometry) {
  28885. geometry._indices = [];
  28886. for (var vbName in geometry._vertexBuffers) {
  28887. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28888. continue;
  28889. }
  28890. geometry._vertexBuffers[vbName]._buffer._data = null;
  28891. }
  28892. }
  28893. }
  28894. };
  28895. /**
  28896. * This function will remove the local cached buffer data from texture.
  28897. * It will save memory but will prevent the texture from being rebuilt
  28898. */
  28899. Scene.prototype.cleanCachedTextureBuffer = function () {
  28900. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28901. var baseTexture = _a[_i];
  28902. var buffer = baseTexture._buffer;
  28903. if (buffer) {
  28904. baseTexture._buffer = null;
  28905. }
  28906. }
  28907. };
  28908. /**
  28909. * Get the world extend vectors with an optional filter
  28910. *
  28911. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28912. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28913. */
  28914. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28915. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28916. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28917. filterPredicate = filterPredicate || (function () { return true; });
  28918. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28919. mesh.computeWorldMatrix(true);
  28920. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28921. return;
  28922. }
  28923. var boundingInfo = mesh.getBoundingInfo();
  28924. var minBox = boundingInfo.boundingBox.minimumWorld;
  28925. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28926. BABYLON.Tools.CheckExtends(minBox, min, max);
  28927. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28928. });
  28929. return {
  28930. min: min,
  28931. max: max
  28932. };
  28933. };
  28934. // Picking
  28935. /**
  28936. * Creates a ray that can be used to pick in the scene
  28937. * @param x defines the x coordinate of the origin (on-screen)
  28938. * @param y defines the y coordinate of the origin (on-screen)
  28939. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28940. * @param camera defines the camera to use for the picking
  28941. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28942. * @returns a Ray
  28943. */
  28944. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28945. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28946. var result = BABYLON.Ray.Zero();
  28947. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28948. return result;
  28949. };
  28950. /**
  28951. * Creates a ray that can be used to pick in the scene
  28952. * @param x defines the x coordinate of the origin (on-screen)
  28953. * @param y defines the y coordinate of the origin (on-screen)
  28954. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28955. * @param result defines the ray where to store the picking ray
  28956. * @param camera defines the camera to use for the picking
  28957. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28958. * @returns the current scene
  28959. */
  28960. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28961. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28962. var engine = this._engine;
  28963. if (!camera) {
  28964. if (!this.activeCamera)
  28965. throw new Error("Active camera not set");
  28966. camera = this.activeCamera;
  28967. }
  28968. var cameraViewport = camera.viewport;
  28969. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28970. // Moving coordinates to local viewport world
  28971. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28972. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28973. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28974. return this;
  28975. };
  28976. /**
  28977. * Creates a ray that can be used to pick in the scene
  28978. * @param x defines the x coordinate of the origin (on-screen)
  28979. * @param y defines the y coordinate of the origin (on-screen)
  28980. * @param camera defines the camera to use for the picking
  28981. * @returns a Ray
  28982. */
  28983. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28984. var result = BABYLON.Ray.Zero();
  28985. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28986. return result;
  28987. };
  28988. /**
  28989. * Creates a ray that can be used to pick in the scene
  28990. * @param x defines the x coordinate of the origin (on-screen)
  28991. * @param y defines the y coordinate of the origin (on-screen)
  28992. * @param result defines the ray where to store the picking ray
  28993. * @param camera defines the camera to use for the picking
  28994. * @returns the current scene
  28995. */
  28996. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28997. if (!BABYLON.PickingInfo) {
  28998. return this;
  28999. }
  29000. var engine = this._engine;
  29001. if (!camera) {
  29002. if (!this.activeCamera)
  29003. throw new Error("Active camera not set");
  29004. camera = this.activeCamera;
  29005. }
  29006. var cameraViewport = camera.viewport;
  29007. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29008. var identity = BABYLON.Matrix.Identity();
  29009. // Moving coordinates to local viewport world
  29010. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29011. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29012. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29013. return this;
  29014. };
  29015. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29016. if (!BABYLON.PickingInfo) {
  29017. return null;
  29018. }
  29019. var pickingInfo = null;
  29020. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29021. var mesh = this.meshes[meshIndex];
  29022. if (predicate) {
  29023. if (!predicate(mesh)) {
  29024. continue;
  29025. }
  29026. }
  29027. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29028. continue;
  29029. }
  29030. var world = mesh.getWorldMatrix();
  29031. var ray = rayFunction(world);
  29032. var result = mesh.intersects(ray, fastCheck);
  29033. if (!result || !result.hit)
  29034. continue;
  29035. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29036. continue;
  29037. pickingInfo = result;
  29038. if (fastCheck) {
  29039. break;
  29040. }
  29041. }
  29042. return pickingInfo || new BABYLON.PickingInfo();
  29043. };
  29044. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29045. if (!BABYLON.PickingInfo) {
  29046. return null;
  29047. }
  29048. var pickingInfos = new Array();
  29049. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29050. var mesh = this.meshes[meshIndex];
  29051. if (predicate) {
  29052. if (!predicate(mesh)) {
  29053. continue;
  29054. }
  29055. }
  29056. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29057. continue;
  29058. }
  29059. var world = mesh.getWorldMatrix();
  29060. var ray = rayFunction(world);
  29061. var result = mesh.intersects(ray, false);
  29062. if (!result || !result.hit)
  29063. continue;
  29064. pickingInfos.push(result);
  29065. }
  29066. return pickingInfos;
  29067. };
  29068. /** Launch a ray to try to pick a mesh in the scene
  29069. * @param x position on screen
  29070. * @param y position on screen
  29071. * @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
  29072. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29073. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29074. * @returns a PickingInfo
  29075. */
  29076. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29077. var _this = this;
  29078. if (!BABYLON.PickingInfo) {
  29079. return null;
  29080. }
  29081. var result = this._internalPick(function (world) {
  29082. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29083. return _this._tempPickingRay;
  29084. }, predicate, fastCheck);
  29085. if (result) {
  29086. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29087. }
  29088. return result;
  29089. };
  29090. /** Use the given ray to pick a mesh in the scene
  29091. * @param ray The ray to use to pick meshes
  29092. * @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
  29093. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29094. * @returns a PickingInfo
  29095. */
  29096. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29097. var _this = this;
  29098. var result = this._internalPick(function (world) {
  29099. if (!_this._pickWithRayInverseMatrix) {
  29100. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29101. }
  29102. world.invertToRef(_this._pickWithRayInverseMatrix);
  29103. if (!_this._cachedRayForTransform) {
  29104. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29105. }
  29106. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29107. return _this._cachedRayForTransform;
  29108. }, predicate, fastCheck);
  29109. if (result) {
  29110. result.ray = ray;
  29111. }
  29112. return result;
  29113. };
  29114. /**
  29115. * Launch a ray to try to pick a mesh in the scene
  29116. * @param x X position on screen
  29117. * @param y Y position on screen
  29118. * @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
  29119. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29120. * @returns an array of PickingInfo
  29121. */
  29122. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29123. var _this = this;
  29124. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29125. };
  29126. /**
  29127. * Launch a ray to try to pick a mesh in the scene
  29128. * @param ray Ray to use
  29129. * @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
  29130. * @returns an array of PickingInfo
  29131. */
  29132. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29133. var _this = this;
  29134. return this._internalMultiPick(function (world) {
  29135. if (!_this._pickWithRayInverseMatrix) {
  29136. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29137. }
  29138. world.invertToRef(_this._pickWithRayInverseMatrix);
  29139. if (!_this._cachedRayForTransform) {
  29140. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29141. }
  29142. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29143. return _this._cachedRayForTransform;
  29144. }, predicate);
  29145. };
  29146. /**
  29147. * Force the value of meshUnderPointer
  29148. * @param mesh defines the mesh to use
  29149. */
  29150. Scene.prototype.setPointerOverMesh = function (mesh) {
  29151. if (this._pointerOverMesh === mesh) {
  29152. return;
  29153. }
  29154. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29155. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29156. }
  29157. this._pointerOverMesh = mesh;
  29158. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29159. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29160. }
  29161. };
  29162. /**
  29163. * Gets the mesh under the pointer
  29164. * @returns a Mesh or null if no mesh is under the pointer
  29165. */
  29166. Scene.prototype.getPointerOverMesh = function () {
  29167. return this._pointerOverMesh;
  29168. };
  29169. // Misc.
  29170. /** @hidden */
  29171. Scene.prototype._rebuildGeometries = function () {
  29172. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29173. var geometry = _a[_i];
  29174. geometry._rebuild();
  29175. }
  29176. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29177. var mesh = _c[_b];
  29178. mesh._rebuild();
  29179. }
  29180. if (this.postProcessManager) {
  29181. this.postProcessManager._rebuild();
  29182. }
  29183. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29184. var component = _e[_d];
  29185. component.rebuild();
  29186. }
  29187. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29188. var system = _g[_f];
  29189. system.rebuild();
  29190. }
  29191. };
  29192. /** @hidden */
  29193. Scene.prototype._rebuildTextures = function () {
  29194. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29195. var texture = _a[_i];
  29196. texture._rebuild();
  29197. }
  29198. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29199. };
  29200. // Tags
  29201. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29202. if (tagsQuery === undefined) {
  29203. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29204. return list;
  29205. }
  29206. var listByTags = [];
  29207. forEach = forEach || (function (item) { return; });
  29208. for (var i in list) {
  29209. var item = list[i];
  29210. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29211. listByTags.push(item);
  29212. forEach(item);
  29213. }
  29214. }
  29215. return listByTags;
  29216. };
  29217. /**
  29218. * Get a list of meshes by tags
  29219. * @param tagsQuery defines the tags query to use
  29220. * @param forEach defines a predicate used to filter results
  29221. * @returns an array of Mesh
  29222. */
  29223. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29224. return this._getByTags(this.meshes, tagsQuery, forEach);
  29225. };
  29226. /**
  29227. * Get a list of cameras by tags
  29228. * @param tagsQuery defines the tags query to use
  29229. * @param forEach defines a predicate used to filter results
  29230. * @returns an array of Camera
  29231. */
  29232. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29233. return this._getByTags(this.cameras, tagsQuery, forEach);
  29234. };
  29235. /**
  29236. * Get a list of lights by tags
  29237. * @param tagsQuery defines the tags query to use
  29238. * @param forEach defines a predicate used to filter results
  29239. * @returns an array of Light
  29240. */
  29241. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29242. return this._getByTags(this.lights, tagsQuery, forEach);
  29243. };
  29244. /**
  29245. * Get a list of materials by tags
  29246. * @param tagsQuery defines the tags query to use
  29247. * @param forEach defines a predicate used to filter results
  29248. * @returns an array of Material
  29249. */
  29250. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29251. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29252. };
  29253. /**
  29254. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29255. * This allowed control for front to back rendering or reversly depending of the special needs.
  29256. *
  29257. * @param renderingGroupId The rendering group id corresponding to its index
  29258. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29259. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29260. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29261. */
  29262. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29263. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29264. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29265. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29266. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29267. };
  29268. /**
  29269. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29270. *
  29271. * @param renderingGroupId The rendering group id corresponding to its index
  29272. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29273. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29274. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29275. */
  29276. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29277. if (depth === void 0) { depth = true; }
  29278. if (stencil === void 0) { stencil = true; }
  29279. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29280. };
  29281. /**
  29282. * Gets the current auto clear configuration for one rendering group of the rendering
  29283. * manager.
  29284. * @param index the rendering group index to get the information for
  29285. * @returns The auto clear setup for the requested rendering group
  29286. */
  29287. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29288. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29289. };
  29290. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29291. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29292. get: function () {
  29293. return this._blockMaterialDirtyMechanism;
  29294. },
  29295. set: function (value) {
  29296. if (this._blockMaterialDirtyMechanism === value) {
  29297. return;
  29298. }
  29299. this._blockMaterialDirtyMechanism = value;
  29300. if (!value) { // Do a complete update
  29301. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29302. }
  29303. },
  29304. enumerable: true,
  29305. configurable: true
  29306. });
  29307. /**
  29308. * Will flag all materials as dirty to trigger new shader compilation
  29309. * @param flag defines the flag used to specify which material part must be marked as dirty
  29310. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29311. */
  29312. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29313. if (this._blockMaterialDirtyMechanism) {
  29314. return;
  29315. }
  29316. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29317. var material = _a[_i];
  29318. if (predicate && !predicate(material)) {
  29319. continue;
  29320. }
  29321. material.markAsDirty(flag);
  29322. }
  29323. };
  29324. /** @hidden */
  29325. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29326. var _this = this;
  29327. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29328. this._activeRequests.push(request);
  29329. request.onCompleteObservable.add(function (request) {
  29330. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29331. });
  29332. return request;
  29333. };
  29334. /** @hidden */
  29335. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29336. var _this = this;
  29337. return new Promise(function (resolve, reject) {
  29338. _this._loadFile(url, function (data) {
  29339. resolve(data);
  29340. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29341. reject(exception);
  29342. });
  29343. });
  29344. };
  29345. // Statics
  29346. Scene._uniqueIdCounter = 0;
  29347. /** The fog is deactivated */
  29348. Scene.FOGMODE_NONE = 0;
  29349. /** The fog density is following an exponential function */
  29350. Scene.FOGMODE_EXP = 1;
  29351. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29352. Scene.FOGMODE_EXP2 = 2;
  29353. /** The fog density is following a linear function. */
  29354. Scene.FOGMODE_LINEAR = 3;
  29355. /**
  29356. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29357. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29358. */
  29359. Scene.MinDeltaTime = 1.0;
  29360. /**
  29361. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29362. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29363. */
  29364. Scene.MaxDeltaTime = 1000.0;
  29365. /** The distance in pixel that you have to move to prevent some events */
  29366. Scene.DragMovementThreshold = 10; // in pixels
  29367. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29368. Scene.LongPressDelay = 500; // in milliseconds
  29369. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29370. Scene.DoubleClickDelay = 300; // in milliseconds
  29371. /** If you need to check double click without raising a single click at first click, enable this flag */
  29372. Scene.ExclusiveDoubleClickMode = false;
  29373. return Scene;
  29374. }(BABYLON.AbstractScene));
  29375. BABYLON.Scene = Scene;
  29376. })(BABYLON || (BABYLON = {}));
  29377. //# sourceMappingURL=babylon.scene.js.map
  29378. var BABYLON;
  29379. (function (BABYLON) {
  29380. /**
  29381. * Set of assets to keep when moving a scene into an asset container.
  29382. */
  29383. var KeepAssets = /** @class */ (function (_super) {
  29384. __extends(KeepAssets, _super);
  29385. function KeepAssets() {
  29386. return _super !== null && _super.apply(this, arguments) || this;
  29387. }
  29388. return KeepAssets;
  29389. }(BABYLON.AbstractScene));
  29390. BABYLON.KeepAssets = KeepAssets;
  29391. /**
  29392. * Container with a set of assets that can be added or removed from a scene.
  29393. */
  29394. var AssetContainer = /** @class */ (function (_super) {
  29395. __extends(AssetContainer, _super);
  29396. /**
  29397. * Instantiates an AssetContainer.
  29398. * @param scene The scene the AssetContainer belongs to.
  29399. */
  29400. function AssetContainer(scene) {
  29401. var _this = _super.call(this) || this;
  29402. _this.scene = scene;
  29403. return _this;
  29404. }
  29405. /**
  29406. * Adds all the assets from the container to the scene.
  29407. */
  29408. AssetContainer.prototype.addAllToScene = function () {
  29409. var _this = this;
  29410. this.cameras.forEach(function (o) {
  29411. _this.scene.addCamera(o);
  29412. });
  29413. this.lights.forEach(function (o) {
  29414. _this.scene.addLight(o);
  29415. });
  29416. this.meshes.forEach(function (o) {
  29417. _this.scene.addMesh(o);
  29418. });
  29419. this.skeletons.forEach(function (o) {
  29420. _this.scene.addSkeleton(o);
  29421. });
  29422. this.animations.forEach(function (o) {
  29423. _this.scene.addAnimation(o);
  29424. });
  29425. this.animationGroups.forEach(function (o) {
  29426. _this.scene.addAnimationGroup(o);
  29427. });
  29428. this.multiMaterials.forEach(function (o) {
  29429. _this.scene.addMultiMaterial(o);
  29430. });
  29431. this.materials.forEach(function (o) {
  29432. _this.scene.addMaterial(o);
  29433. });
  29434. this.morphTargetManagers.forEach(function (o) {
  29435. _this.scene.addMorphTargetManager(o);
  29436. });
  29437. this.geometries.forEach(function (o) {
  29438. _this.scene.addGeometry(o);
  29439. });
  29440. this.transformNodes.forEach(function (o) {
  29441. _this.scene.addTransformNode(o);
  29442. });
  29443. this.actionManagers.forEach(function (o) {
  29444. _this.scene.addActionManager(o);
  29445. });
  29446. this.textures.forEach(function (o) {
  29447. _this.scene.addTexture(o);
  29448. });
  29449. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29450. var component = _a[_i];
  29451. component.addFromContainer(this.scene);
  29452. }
  29453. };
  29454. /**
  29455. * Removes all the assets in the container from the scene
  29456. */
  29457. AssetContainer.prototype.removeAllFromScene = function () {
  29458. var _this = this;
  29459. this.cameras.forEach(function (o) {
  29460. _this.scene.removeCamera(o);
  29461. });
  29462. this.lights.forEach(function (o) {
  29463. _this.scene.removeLight(o);
  29464. });
  29465. this.meshes.forEach(function (o) {
  29466. _this.scene.removeMesh(o);
  29467. });
  29468. this.skeletons.forEach(function (o) {
  29469. _this.scene.removeSkeleton(o);
  29470. });
  29471. this.animations.forEach(function (o) {
  29472. _this.scene.removeAnimation(o);
  29473. });
  29474. this.animationGroups.forEach(function (o) {
  29475. _this.scene.removeAnimationGroup(o);
  29476. });
  29477. this.multiMaterials.forEach(function (o) {
  29478. _this.scene.removeMultiMaterial(o);
  29479. });
  29480. this.materials.forEach(function (o) {
  29481. _this.scene.removeMaterial(o);
  29482. });
  29483. this.morphTargetManagers.forEach(function (o) {
  29484. _this.scene.removeMorphTargetManager(o);
  29485. });
  29486. this.geometries.forEach(function (o) {
  29487. _this.scene.removeGeometry(o);
  29488. });
  29489. this.transformNodes.forEach(function (o) {
  29490. _this.scene.removeTransformNode(o);
  29491. });
  29492. this.actionManagers.forEach(function (o) {
  29493. _this.scene.removeActionManager(o);
  29494. });
  29495. this.textures.forEach(function (o) {
  29496. _this.scene.removeTexture(o);
  29497. });
  29498. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29499. var component = _a[_i];
  29500. component.removeFromContainer(this.scene);
  29501. }
  29502. };
  29503. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29504. if (!sourceAssets) {
  29505. return;
  29506. }
  29507. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29508. var asset = sourceAssets_1[_i];
  29509. var move = true;
  29510. if (keepAssets) {
  29511. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29512. var keepAsset = keepAssets_1[_a];
  29513. if (asset === keepAsset) {
  29514. move = false;
  29515. break;
  29516. }
  29517. }
  29518. }
  29519. if (move) {
  29520. targetAssets.push(asset);
  29521. }
  29522. }
  29523. };
  29524. /**
  29525. * Removes all the assets contained in the scene and adds them to the container.
  29526. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29527. */
  29528. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29529. if (keepAssets === undefined) {
  29530. keepAssets = new KeepAssets();
  29531. }
  29532. for (var key in this) {
  29533. if (this.hasOwnProperty(key)) {
  29534. this[key] = this[key] || [];
  29535. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29536. }
  29537. }
  29538. this.removeAllFromScene();
  29539. };
  29540. /**
  29541. * 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.
  29542. * @returns the root mesh
  29543. */
  29544. AssetContainer.prototype.createRootMesh = function () {
  29545. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29546. this.meshes.forEach(function (m) {
  29547. if (!m.parent) {
  29548. rootMesh.addChild(m);
  29549. }
  29550. });
  29551. this.meshes.unshift(rootMesh);
  29552. return rootMesh;
  29553. };
  29554. return AssetContainer;
  29555. }(BABYLON.AbstractScene));
  29556. BABYLON.AssetContainer = AssetContainer;
  29557. })(BABYLON || (BABYLON = {}));
  29558. //# sourceMappingURL=babylon.assetContainer.js.map
  29559. var BABYLON;
  29560. (function (BABYLON) {
  29561. /**
  29562. * Class used to store data that will be store in GPU memory
  29563. */
  29564. var Buffer = /** @class */ (function () {
  29565. /**
  29566. * Constructor
  29567. * @param engine the engine
  29568. * @param data the data to use for this buffer
  29569. * @param updatable whether the data is updatable
  29570. * @param stride the stride (optional)
  29571. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29572. * @param instanced whether the buffer is instanced (optional)
  29573. * @param useBytes set to true if the stride in in bytes (optional)
  29574. */
  29575. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29576. if (stride === void 0) { stride = 0; }
  29577. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29578. if (instanced === void 0) { instanced = false; }
  29579. if (useBytes === void 0) { useBytes = false; }
  29580. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29581. this._engine = engine.getScene().getEngine();
  29582. }
  29583. else {
  29584. this._engine = engine;
  29585. }
  29586. this._updatable = updatable;
  29587. this._instanced = instanced;
  29588. this._data = data;
  29589. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29590. if (!postponeInternalCreation) { // by default
  29591. this.create();
  29592. }
  29593. }
  29594. /**
  29595. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29596. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29597. * @param offset defines offset in the buffer (0 by default)
  29598. * @param size defines the size in floats of attributes (position is 3 for instance)
  29599. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29600. * @param instanced defines if the vertex buffer contains indexed data
  29601. * @param useBytes defines if the offset and stride are in bytes
  29602. * @returns the new vertex buffer
  29603. */
  29604. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29605. if (useBytes === void 0) { useBytes = false; }
  29606. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29607. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29608. // a lot of these parameters are ignored as they are overriden by the buffer
  29609. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29610. };
  29611. // Properties
  29612. /**
  29613. * Gets a boolean indicating if the Buffer is updatable?
  29614. * @returns true if the buffer is updatable
  29615. */
  29616. Buffer.prototype.isUpdatable = function () {
  29617. return this._updatable;
  29618. };
  29619. /**
  29620. * Gets current buffer's data
  29621. * @returns a DataArray or null
  29622. */
  29623. Buffer.prototype.getData = function () {
  29624. return this._data;
  29625. };
  29626. /**
  29627. * Gets underlying native buffer
  29628. * @returns underlying native buffer
  29629. */
  29630. Buffer.prototype.getBuffer = function () {
  29631. return this._buffer;
  29632. };
  29633. /**
  29634. * Gets the stride in float32 units (i.e. byte stride / 4).
  29635. * May not be an integer if the byte stride is not divisible by 4.
  29636. * DEPRECATED. Use byteStride instead.
  29637. * @returns the stride in float32 units
  29638. */
  29639. Buffer.prototype.getStrideSize = function () {
  29640. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29641. };
  29642. // Methods
  29643. /**
  29644. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29645. * @param data defines the data to store
  29646. */
  29647. Buffer.prototype.create = function (data) {
  29648. if (data === void 0) { data = null; }
  29649. if (!data && this._buffer) {
  29650. return; // nothing to do
  29651. }
  29652. data = data || this._data;
  29653. if (!data) {
  29654. return;
  29655. }
  29656. if (!this._buffer) { // create buffer
  29657. if (this._updatable) {
  29658. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29659. this._data = data;
  29660. }
  29661. else {
  29662. this._buffer = this._engine.createVertexBuffer(data);
  29663. }
  29664. }
  29665. else if (this._updatable) { // update buffer
  29666. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29667. this._data = data;
  29668. }
  29669. };
  29670. /** @hidden */
  29671. Buffer.prototype._rebuild = function () {
  29672. this._buffer = null;
  29673. this.create(this._data);
  29674. };
  29675. /**
  29676. * Update current buffer data
  29677. * @param data defines the data to store
  29678. */
  29679. Buffer.prototype.update = function (data) {
  29680. this.create(data);
  29681. };
  29682. /**
  29683. * Updates the data directly.
  29684. * @param data the new data
  29685. * @param offset the new offset
  29686. * @param vertexCount the vertex count (optional)
  29687. * @param useBytes set to true if the offset is in bytes
  29688. */
  29689. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29690. if (useBytes === void 0) { useBytes = false; }
  29691. if (!this._buffer) {
  29692. return;
  29693. }
  29694. if (this._updatable) { // update buffer
  29695. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29696. this._data = null;
  29697. }
  29698. };
  29699. /**
  29700. * Release all resources
  29701. */
  29702. Buffer.prototype.dispose = function () {
  29703. if (!this._buffer) {
  29704. return;
  29705. }
  29706. if (this._engine._releaseBuffer(this._buffer)) {
  29707. this._buffer = null;
  29708. }
  29709. };
  29710. return Buffer;
  29711. }());
  29712. BABYLON.Buffer = Buffer;
  29713. })(BABYLON || (BABYLON = {}));
  29714. //# sourceMappingURL=babylon.buffer.js.map
  29715. var BABYLON;
  29716. (function (BABYLON) {
  29717. /**
  29718. * Specialized buffer used to store vertex data
  29719. */
  29720. var VertexBuffer = /** @class */ (function () {
  29721. /**
  29722. * Constructor
  29723. * @param engine the engine
  29724. * @param data the data to use for this vertex buffer
  29725. * @param kind the vertex buffer kind
  29726. * @param updatable whether the data is updatable
  29727. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29728. * @param stride the stride (optional)
  29729. * @param instanced whether the buffer is instanced (optional)
  29730. * @param offset the offset of the data (optional)
  29731. * @param size the number of components (optional)
  29732. * @param type the type of the component (optional)
  29733. * @param normalized whether the data contains normalized data (optional)
  29734. * @param useBytes set to true if stride and offset are in bytes (optional)
  29735. */
  29736. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29737. if (normalized === void 0) { normalized = false; }
  29738. if (useBytes === void 0) { useBytes = false; }
  29739. if (data instanceof BABYLON.Buffer) {
  29740. this._buffer = data;
  29741. this._ownsBuffer = false;
  29742. }
  29743. else {
  29744. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29745. this._ownsBuffer = true;
  29746. }
  29747. this._kind = kind;
  29748. if (type == undefined) {
  29749. var data_1 = this.getData();
  29750. this.type = VertexBuffer.FLOAT;
  29751. if (data_1 instanceof Int8Array)
  29752. this.type = VertexBuffer.BYTE;
  29753. else if (data_1 instanceof Uint8Array)
  29754. this.type = VertexBuffer.UNSIGNED_BYTE;
  29755. else if (data_1 instanceof Int16Array)
  29756. this.type = VertexBuffer.SHORT;
  29757. else if (data_1 instanceof Uint16Array)
  29758. this.type = VertexBuffer.UNSIGNED_SHORT;
  29759. else if (data_1 instanceof Int32Array)
  29760. this.type = VertexBuffer.INT;
  29761. else if (data_1 instanceof Uint32Array)
  29762. this.type = VertexBuffer.UNSIGNED_INT;
  29763. }
  29764. else {
  29765. this.type = type;
  29766. }
  29767. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29768. if (useBytes) {
  29769. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29770. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29771. this.byteOffset = offset || 0;
  29772. }
  29773. else {
  29774. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29775. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29776. this.byteOffset = (offset || 0) * typeByteLength;
  29777. }
  29778. this.normalized = normalized;
  29779. this._instanced = instanced !== undefined ? instanced : false;
  29780. this._instanceDivisor = instanced ? 1 : 0;
  29781. }
  29782. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29783. /**
  29784. * Gets or sets the instance divisor when in instanced mode
  29785. */
  29786. get: function () {
  29787. return this._instanceDivisor;
  29788. },
  29789. set: function (value) {
  29790. this._instanceDivisor = value;
  29791. if (value == 0) {
  29792. this._instanced = false;
  29793. }
  29794. else {
  29795. this._instanced = true;
  29796. }
  29797. },
  29798. enumerable: true,
  29799. configurable: true
  29800. });
  29801. /** @hidden */
  29802. VertexBuffer.prototype._rebuild = function () {
  29803. if (!this._buffer) {
  29804. return;
  29805. }
  29806. this._buffer._rebuild();
  29807. };
  29808. /**
  29809. * Returns the kind of the VertexBuffer (string)
  29810. * @returns a string
  29811. */
  29812. VertexBuffer.prototype.getKind = function () {
  29813. return this._kind;
  29814. };
  29815. // Properties
  29816. /**
  29817. * Gets a boolean indicating if the VertexBuffer is updatable?
  29818. * @returns true if the buffer is updatable
  29819. */
  29820. VertexBuffer.prototype.isUpdatable = function () {
  29821. return this._buffer.isUpdatable();
  29822. };
  29823. /**
  29824. * Gets current buffer's data
  29825. * @returns a DataArray or null
  29826. */
  29827. VertexBuffer.prototype.getData = function () {
  29828. return this._buffer.getData();
  29829. };
  29830. /**
  29831. * Gets underlying native buffer
  29832. * @returns underlying native buffer
  29833. */
  29834. VertexBuffer.prototype.getBuffer = function () {
  29835. return this._buffer.getBuffer();
  29836. };
  29837. /**
  29838. * Gets the stride in float32 units (i.e. byte stride / 4).
  29839. * May not be an integer if the byte stride is not divisible by 4.
  29840. * DEPRECATED. Use byteStride instead.
  29841. * @returns the stride in float32 units
  29842. */
  29843. VertexBuffer.prototype.getStrideSize = function () {
  29844. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29845. };
  29846. /**
  29847. * Returns the offset as a multiple of the type byte length.
  29848. * DEPRECATED. Use byteOffset instead.
  29849. * @returns the offset in bytes
  29850. */
  29851. VertexBuffer.prototype.getOffset = function () {
  29852. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29853. };
  29854. /**
  29855. * Returns the number of components per vertex attribute (integer)
  29856. * @returns the size in float
  29857. */
  29858. VertexBuffer.prototype.getSize = function () {
  29859. return this._size;
  29860. };
  29861. /**
  29862. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  29863. * @returns true if this buffer is instanced
  29864. */
  29865. VertexBuffer.prototype.getIsInstanced = function () {
  29866. return this._instanced;
  29867. };
  29868. /**
  29869. * Returns the instancing divisor, zero for non-instanced (integer).
  29870. * @returns a number
  29871. */
  29872. VertexBuffer.prototype.getInstanceDivisor = function () {
  29873. return this._instanceDivisor;
  29874. };
  29875. // Methods
  29876. /**
  29877. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29878. * @param data defines the data to store
  29879. */
  29880. VertexBuffer.prototype.create = function (data) {
  29881. this._buffer.create(data);
  29882. };
  29883. /**
  29884. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  29885. * This function will create a new buffer if the current one is not updatable
  29886. * @param data defines the data to store
  29887. */
  29888. VertexBuffer.prototype.update = function (data) {
  29889. this._buffer.update(data);
  29890. };
  29891. /**
  29892. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29893. * Returns the directly updated WebGLBuffer.
  29894. * @param data the new data
  29895. * @param offset the new offset
  29896. * @param useBytes set to true if the offset is in bytes
  29897. */
  29898. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29899. if (useBytes === void 0) { useBytes = false; }
  29900. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29901. };
  29902. /**
  29903. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29904. */
  29905. VertexBuffer.prototype.dispose = function () {
  29906. if (this._ownsBuffer) {
  29907. this._buffer.dispose();
  29908. }
  29909. };
  29910. /**
  29911. * Enumerates each value of this vertex buffer as numbers.
  29912. * @param count the number of values to enumerate
  29913. * @param callback the callback function called for each value
  29914. */
  29915. VertexBuffer.prototype.forEach = function (count, callback) {
  29916. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29917. };
  29918. /**
  29919. * Deduces the stride given a kind.
  29920. * @param kind The kind string to deduce
  29921. * @returns The deduced stride
  29922. */
  29923. VertexBuffer.DeduceStride = function (kind) {
  29924. switch (kind) {
  29925. case VertexBuffer.UVKind:
  29926. case VertexBuffer.UV2Kind:
  29927. case VertexBuffer.UV3Kind:
  29928. case VertexBuffer.UV4Kind:
  29929. case VertexBuffer.UV5Kind:
  29930. case VertexBuffer.UV6Kind:
  29931. return 2;
  29932. case VertexBuffer.NormalKind:
  29933. case VertexBuffer.PositionKind:
  29934. return 3;
  29935. case VertexBuffer.ColorKind:
  29936. case VertexBuffer.MatricesIndicesKind:
  29937. case VertexBuffer.MatricesIndicesExtraKind:
  29938. case VertexBuffer.MatricesWeightsKind:
  29939. case VertexBuffer.MatricesWeightsExtraKind:
  29940. case VertexBuffer.TangentKind:
  29941. return 4;
  29942. default:
  29943. throw new Error("Invalid kind '" + kind + "'");
  29944. }
  29945. };
  29946. /**
  29947. * Gets the byte length of the given type.
  29948. * @param type the type
  29949. * @returns the number of bytes
  29950. */
  29951. VertexBuffer.GetTypeByteLength = function (type) {
  29952. switch (type) {
  29953. case VertexBuffer.BYTE:
  29954. case VertexBuffer.UNSIGNED_BYTE:
  29955. return 1;
  29956. case VertexBuffer.SHORT:
  29957. case VertexBuffer.UNSIGNED_SHORT:
  29958. return 2;
  29959. case VertexBuffer.INT:
  29960. case VertexBuffer.FLOAT:
  29961. return 4;
  29962. default:
  29963. throw new Error("Invalid type '" + type + "'");
  29964. }
  29965. };
  29966. /**
  29967. * Enumerates each value of the given parameters as numbers.
  29968. * @param data the data to enumerate
  29969. * @param byteOffset the byte offset of the data
  29970. * @param byteStride the byte stride of the data
  29971. * @param componentCount the number of components per element
  29972. * @param componentType the type of the component
  29973. * @param count the total number of components
  29974. * @param normalized whether the data is normalized
  29975. * @param callback the callback function called for each value
  29976. */
  29977. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29978. if (data instanceof Array) {
  29979. var offset = byteOffset / 4;
  29980. var stride = byteStride / 4;
  29981. for (var index = 0; index < count; index += componentCount) {
  29982. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29983. callback(data[offset + componentIndex], index + componentIndex);
  29984. }
  29985. offset += stride;
  29986. }
  29987. }
  29988. else {
  29989. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29990. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29991. for (var index = 0; index < count; index += componentCount) {
  29992. var componentByteOffset = byteOffset;
  29993. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29994. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29995. callback(value, index + componentIndex);
  29996. componentByteOffset += componentByteLength;
  29997. }
  29998. byteOffset += byteStride;
  29999. }
  30000. }
  30001. };
  30002. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30003. switch (type) {
  30004. case VertexBuffer.BYTE: {
  30005. var value = dataView.getInt8(byteOffset);
  30006. if (normalized) {
  30007. value = Math.max(value / 127, -1);
  30008. }
  30009. return value;
  30010. }
  30011. case VertexBuffer.UNSIGNED_BYTE: {
  30012. var value = dataView.getUint8(byteOffset);
  30013. if (normalized) {
  30014. value = value / 255;
  30015. }
  30016. return value;
  30017. }
  30018. case VertexBuffer.SHORT: {
  30019. var value = dataView.getInt16(byteOffset, true);
  30020. if (normalized) {
  30021. value = Math.max(value / 16383, -1);
  30022. }
  30023. return value;
  30024. }
  30025. case VertexBuffer.UNSIGNED_SHORT: {
  30026. var value = dataView.getUint16(byteOffset, true);
  30027. if (normalized) {
  30028. value = value / 65535;
  30029. }
  30030. return value;
  30031. }
  30032. case VertexBuffer.FLOAT: {
  30033. return dataView.getFloat32(byteOffset, true);
  30034. }
  30035. default: {
  30036. throw new Error("Invalid component type " + type);
  30037. }
  30038. }
  30039. };
  30040. /**
  30041. * The byte type.
  30042. */
  30043. VertexBuffer.BYTE = 5120;
  30044. /**
  30045. * The unsigned byte type.
  30046. */
  30047. VertexBuffer.UNSIGNED_BYTE = 5121;
  30048. /**
  30049. * The short type.
  30050. */
  30051. VertexBuffer.SHORT = 5122;
  30052. /**
  30053. * The unsigned short type.
  30054. */
  30055. VertexBuffer.UNSIGNED_SHORT = 5123;
  30056. /**
  30057. * The integer type.
  30058. */
  30059. VertexBuffer.INT = 5124;
  30060. /**
  30061. * The unsigned integer type.
  30062. */
  30063. VertexBuffer.UNSIGNED_INT = 5125;
  30064. /**
  30065. * The float type.
  30066. */
  30067. VertexBuffer.FLOAT = 5126;
  30068. // Enums
  30069. /**
  30070. * Positions
  30071. */
  30072. VertexBuffer.PositionKind = "position";
  30073. /**
  30074. * Normals
  30075. */
  30076. VertexBuffer.NormalKind = "normal";
  30077. /**
  30078. * Tangents
  30079. */
  30080. VertexBuffer.TangentKind = "tangent";
  30081. /**
  30082. * Texture coordinates
  30083. */
  30084. VertexBuffer.UVKind = "uv";
  30085. /**
  30086. * Texture coordinates 2
  30087. */
  30088. VertexBuffer.UV2Kind = "uv2";
  30089. /**
  30090. * Texture coordinates 3
  30091. */
  30092. VertexBuffer.UV3Kind = "uv3";
  30093. /**
  30094. * Texture coordinates 4
  30095. */
  30096. VertexBuffer.UV4Kind = "uv4";
  30097. /**
  30098. * Texture coordinates 5
  30099. */
  30100. VertexBuffer.UV5Kind = "uv5";
  30101. /**
  30102. * Texture coordinates 6
  30103. */
  30104. VertexBuffer.UV6Kind = "uv6";
  30105. /**
  30106. * Colors
  30107. */
  30108. VertexBuffer.ColorKind = "color";
  30109. /**
  30110. * Matrix indices (for bones)
  30111. */
  30112. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30113. /**
  30114. * Matrix weights (for bones)
  30115. */
  30116. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30117. /**
  30118. * Additional matrix indices (for bones)
  30119. */
  30120. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30121. /**
  30122. * Additional matrix weights (for bones)
  30123. */
  30124. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30125. return VertexBuffer;
  30126. }());
  30127. BABYLON.VertexBuffer = VertexBuffer;
  30128. })(BABYLON || (BABYLON = {}));
  30129. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30130. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30131. var BABYLON;
  30132. (function (BABYLON) {
  30133. /**
  30134. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30135. */
  30136. var DummyInternalTextureTracker = /** @class */ (function () {
  30137. function DummyInternalTextureTracker() {
  30138. /**
  30139. * Gets or set the previous tracker in the list
  30140. */
  30141. this.previous = null;
  30142. /**
  30143. * Gets or set the next tracker in the list
  30144. */
  30145. this.next = null;
  30146. }
  30147. return DummyInternalTextureTracker;
  30148. }());
  30149. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30150. })(BABYLON || (BABYLON = {}));
  30151. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30152. var BABYLON;
  30153. (function (BABYLON) {
  30154. /**
  30155. * Class used to store data associated with WebGL texture data for the engine
  30156. * This class should not be used directly
  30157. */
  30158. var InternalTexture = /** @class */ (function () {
  30159. /**
  30160. * Creates a new InternalTexture
  30161. * @param engine defines the engine to use
  30162. * @param dataSource defines the type of data that will be used
  30163. */
  30164. function InternalTexture(engine, dataSource) {
  30165. /**
  30166. * Observable called when the texture is loaded
  30167. */
  30168. this.onLoadedObservable = new BABYLON.Observable();
  30169. /**
  30170. * Gets or set the previous tracker in the list
  30171. */
  30172. this.previous = null;
  30173. /**
  30174. * Gets or set the next tracker in the list
  30175. */
  30176. this.next = null;
  30177. // Private
  30178. /** @hidden */
  30179. this._initialSlot = -1;
  30180. /** @hidden */
  30181. this._designatedSlot = -1;
  30182. /** @hidden */
  30183. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30184. /** @hidden */
  30185. this._comparisonFunction = 0;
  30186. /** @hidden */
  30187. this._sphericalPolynomial = null;
  30188. /** @hidden */
  30189. this._lodGenerationScale = 0;
  30190. /** @hidden */
  30191. this._lodGenerationOffset = 0;
  30192. /** @hidden */
  30193. this._isRGBD = false;
  30194. /** @hidden */
  30195. this._references = 1;
  30196. this._engine = engine;
  30197. this._dataSource = dataSource;
  30198. this._webGLTexture = engine._createTexture();
  30199. }
  30200. /**
  30201. * Gets the Engine the texture belongs to.
  30202. * @returns The babylon engine
  30203. */
  30204. InternalTexture.prototype.getEngine = function () {
  30205. return this._engine;
  30206. };
  30207. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30208. /**
  30209. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30210. */
  30211. get: function () {
  30212. return this._dataSource;
  30213. },
  30214. enumerable: true,
  30215. configurable: true
  30216. });
  30217. /**
  30218. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30219. */
  30220. InternalTexture.prototype.incrementReferences = function () {
  30221. this._references++;
  30222. };
  30223. /**
  30224. * Change the size of the texture (not the size of the content)
  30225. * @param width defines the new width
  30226. * @param height defines the new height
  30227. * @param depth defines the new depth (1 by default)
  30228. */
  30229. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30230. if (depth === void 0) { depth = 1; }
  30231. this.width = width;
  30232. this.height = height;
  30233. this.depth = depth;
  30234. this.baseWidth = width;
  30235. this.baseHeight = height;
  30236. this.baseDepth = depth;
  30237. this._size = width * height * depth;
  30238. };
  30239. /** @hidden */
  30240. InternalTexture.prototype._rebuild = function () {
  30241. var _this = this;
  30242. var proxy;
  30243. this.isReady = false;
  30244. this._cachedCoordinatesMode = null;
  30245. this._cachedWrapU = null;
  30246. this._cachedWrapV = null;
  30247. this._cachedAnisotropicFilteringLevel = null;
  30248. switch (this._dataSource) {
  30249. case InternalTexture.DATASOURCE_TEMP:
  30250. return;
  30251. case InternalTexture.DATASOURCE_URL:
  30252. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30253. _this.isReady = true;
  30254. }, null, this._buffer, undefined, this.format);
  30255. proxy._swapAndDie(this);
  30256. return;
  30257. case InternalTexture.DATASOURCE_RAW:
  30258. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30259. proxy._swapAndDie(this);
  30260. this.isReady = true;
  30261. return;
  30262. case InternalTexture.DATASOURCE_RAW3D:
  30263. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30264. proxy._swapAndDie(this);
  30265. this.isReady = true;
  30266. return;
  30267. case InternalTexture.DATASOURCE_DYNAMIC:
  30268. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30269. proxy._swapAndDie(this);
  30270. // The engine will make sure to update content so no need to flag it as isReady = true
  30271. return;
  30272. case InternalTexture.DATASOURCE_RENDERTARGET:
  30273. var options = new BABYLON.RenderTargetCreationOptions();
  30274. options.generateDepthBuffer = this._generateDepthBuffer;
  30275. options.generateMipMaps = this.generateMipMaps;
  30276. options.generateStencilBuffer = this._generateStencilBuffer;
  30277. options.samplingMode = this.samplingMode;
  30278. options.type = this.type;
  30279. if (this.isCube) {
  30280. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30281. }
  30282. else {
  30283. var size = {
  30284. width: this.width,
  30285. height: this.height
  30286. };
  30287. proxy = this._engine.createRenderTargetTexture(size, options);
  30288. }
  30289. proxy._swapAndDie(this);
  30290. this.isReady = true;
  30291. return;
  30292. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30293. var depthTextureOptions = {
  30294. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30295. comparisonFunction: this._comparisonFunction,
  30296. generateStencil: this._generateStencilBuffer,
  30297. isCube: this.isCube
  30298. };
  30299. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30300. proxy._swapAndDie(this);
  30301. this.isReady = true;
  30302. return;
  30303. case InternalTexture.DATASOURCE_CUBE:
  30304. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30305. _this.isReady = true;
  30306. }, null, this.format, this._extension);
  30307. proxy._swapAndDie(this);
  30308. return;
  30309. case InternalTexture.DATASOURCE_CUBERAW:
  30310. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30311. proxy._swapAndDie(this);
  30312. this.isReady = true;
  30313. return;
  30314. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30315. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30316. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30317. _this.isReady = true;
  30318. });
  30319. proxy._swapAndDie(this);
  30320. return;
  30321. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30322. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30323. if (proxy) {
  30324. proxy._swapAndDie(_this);
  30325. }
  30326. _this.isReady = true;
  30327. }, null, this.format, this._extension);
  30328. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30329. return;
  30330. }
  30331. };
  30332. /** @hidden */
  30333. InternalTexture.prototype._swapAndDie = function (target) {
  30334. target._webGLTexture = this._webGLTexture;
  30335. if (this._framebuffer) {
  30336. target._framebuffer = this._framebuffer;
  30337. }
  30338. if (this._depthStencilBuffer) {
  30339. target._depthStencilBuffer = this._depthStencilBuffer;
  30340. }
  30341. if (this._lodTextureHigh) {
  30342. if (target._lodTextureHigh) {
  30343. target._lodTextureHigh.dispose();
  30344. }
  30345. target._lodTextureHigh = this._lodTextureHigh;
  30346. }
  30347. if (this._lodTextureMid) {
  30348. if (target._lodTextureMid) {
  30349. target._lodTextureMid.dispose();
  30350. }
  30351. target._lodTextureMid = this._lodTextureMid;
  30352. }
  30353. if (this._lodTextureLow) {
  30354. if (target._lodTextureLow) {
  30355. target._lodTextureLow.dispose();
  30356. }
  30357. target._lodTextureLow = this._lodTextureLow;
  30358. }
  30359. var cache = this._engine.getLoadedTexturesCache();
  30360. var index = cache.indexOf(this);
  30361. if (index !== -1) {
  30362. cache.splice(index, 1);
  30363. }
  30364. };
  30365. /**
  30366. * Dispose the current allocated resources
  30367. */
  30368. InternalTexture.prototype.dispose = function () {
  30369. if (!this._webGLTexture) {
  30370. return;
  30371. }
  30372. this._references--;
  30373. if (this._references === 0) {
  30374. this._engine._releaseTexture(this);
  30375. this._webGLTexture = null;
  30376. this.previous = null;
  30377. this.next = null;
  30378. }
  30379. };
  30380. /**
  30381. * The source of the texture data is unknown
  30382. */
  30383. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30384. /**
  30385. * Texture data comes from an URL
  30386. */
  30387. InternalTexture.DATASOURCE_URL = 1;
  30388. /**
  30389. * Texture data is only used for temporary storage
  30390. */
  30391. InternalTexture.DATASOURCE_TEMP = 2;
  30392. /**
  30393. * Texture data comes from raw data (ArrayBuffer)
  30394. */
  30395. InternalTexture.DATASOURCE_RAW = 3;
  30396. /**
  30397. * Texture content is dynamic (video or dynamic texture)
  30398. */
  30399. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30400. /**
  30401. * Texture content is generated by rendering to it
  30402. */
  30403. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30404. /**
  30405. * Texture content is part of a multi render target process
  30406. */
  30407. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30408. /**
  30409. * Texture data comes from a cube data file
  30410. */
  30411. InternalTexture.DATASOURCE_CUBE = 7;
  30412. /**
  30413. * Texture data comes from a raw cube data
  30414. */
  30415. InternalTexture.DATASOURCE_CUBERAW = 8;
  30416. /**
  30417. * Texture data come from a prefiltered cube data file
  30418. */
  30419. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30420. /**
  30421. * Texture content is raw 3D data
  30422. */
  30423. InternalTexture.DATASOURCE_RAW3D = 10;
  30424. /**
  30425. * Texture content is a depth texture
  30426. */
  30427. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30428. /**
  30429. * Texture data comes from a raw cube data encoded with RGBD
  30430. */
  30431. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30432. return InternalTexture;
  30433. }());
  30434. BABYLON.InternalTexture = InternalTexture;
  30435. })(BABYLON || (BABYLON = {}));
  30436. //# sourceMappingURL=babylon.internalTexture.js.map
  30437. var BABYLON;
  30438. (function (BABYLON) {
  30439. var BaseTexture = /** @class */ (function () {
  30440. function BaseTexture(scene) {
  30441. this._hasAlpha = false;
  30442. this.getAlphaFromRGB = false;
  30443. this.level = 1;
  30444. this.coordinatesIndex = 0;
  30445. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30446. /**
  30447. * | Value | Type | Description |
  30448. * | ----- | ------------------ | ----------- |
  30449. * | 0 | CLAMP_ADDRESSMODE | |
  30450. * | 1 | WRAP_ADDRESSMODE | |
  30451. * | 2 | MIRROR_ADDRESSMODE | |
  30452. */
  30453. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30454. /**
  30455. * | Value | Type | Description |
  30456. * | ----- | ------------------ | ----------- |
  30457. * | 0 | CLAMP_ADDRESSMODE | |
  30458. * | 1 | WRAP_ADDRESSMODE | |
  30459. * | 2 | MIRROR_ADDRESSMODE | |
  30460. */
  30461. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30462. /**
  30463. * | Value | Type | Description |
  30464. * | ----- | ------------------ | ----------- |
  30465. * | 0 | CLAMP_ADDRESSMODE | |
  30466. * | 1 | WRAP_ADDRESSMODE | |
  30467. * | 2 | MIRROR_ADDRESSMODE | |
  30468. */
  30469. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30470. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30471. this.isCube = false;
  30472. this.is3D = false;
  30473. this.gammaSpace = true;
  30474. this.invertZ = false;
  30475. this.lodLevelInAlpha = false;
  30476. this.isRenderTarget = false;
  30477. this.animations = new Array();
  30478. /**
  30479. * An event triggered when the texture is disposed.
  30480. */
  30481. this.onDisposeObservable = new BABYLON.Observable();
  30482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30483. this._cachedSize = BABYLON.Size.Zero();
  30484. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30485. if (this._scene) {
  30486. this._scene.textures.push(this);
  30487. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30488. }
  30489. this._uid = null;
  30490. }
  30491. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30492. get: function () {
  30493. return this._hasAlpha;
  30494. },
  30495. set: function (value) {
  30496. if (this._hasAlpha === value) {
  30497. return;
  30498. }
  30499. this._hasAlpha = value;
  30500. if (this._scene) {
  30501. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30502. }
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30508. get: function () {
  30509. return this._coordinatesMode;
  30510. },
  30511. /**
  30512. * How a texture is mapped.
  30513. *
  30514. * | Value | Type | Description |
  30515. * | ----- | ----------------------------------- | ----------- |
  30516. * | 0 | EXPLICIT_MODE | |
  30517. * | 1 | SPHERICAL_MODE | |
  30518. * | 2 | PLANAR_MODE | |
  30519. * | 3 | CUBIC_MODE | |
  30520. * | 4 | PROJECTION_MODE | |
  30521. * | 5 | SKYBOX_MODE | |
  30522. * | 6 | INVCUBIC_MODE | |
  30523. * | 7 | EQUIRECTANGULAR_MODE | |
  30524. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30525. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30526. */
  30527. set: function (value) {
  30528. if (this._coordinatesMode === value) {
  30529. return;
  30530. }
  30531. this._coordinatesMode = value;
  30532. if (this._scene) {
  30533. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30534. }
  30535. },
  30536. enumerable: true,
  30537. configurable: true
  30538. });
  30539. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30540. /**
  30541. * Gets whether or not the texture contains RGBD data.
  30542. */
  30543. get: function () {
  30544. return this._texture != null && this._texture._isRGBD;
  30545. },
  30546. enumerable: true,
  30547. configurable: true
  30548. });
  30549. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30550. get: function () {
  30551. if (this._texture)
  30552. return this._texture._lodGenerationOffset;
  30553. return 0.0;
  30554. },
  30555. set: function (value) {
  30556. if (this._texture)
  30557. this._texture._lodGenerationOffset = value;
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30563. get: function () {
  30564. if (this._texture)
  30565. return this._texture._lodGenerationScale;
  30566. return 0.0;
  30567. },
  30568. set: function (value) {
  30569. if (this._texture)
  30570. this._texture._lodGenerationScale = value;
  30571. },
  30572. enumerable: true,
  30573. configurable: true
  30574. });
  30575. Object.defineProperty(BaseTexture.prototype, "uid", {
  30576. get: function () {
  30577. if (!this._uid) {
  30578. this._uid = BABYLON.Tools.RandomId();
  30579. }
  30580. return this._uid;
  30581. },
  30582. enumerable: true,
  30583. configurable: true
  30584. });
  30585. BaseTexture.prototype.toString = function () {
  30586. return this.name;
  30587. };
  30588. BaseTexture.prototype.getClassName = function () {
  30589. return "BaseTexture";
  30590. };
  30591. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30592. set: function (callback) {
  30593. if (this._onDisposeObserver) {
  30594. this.onDisposeObservable.remove(this._onDisposeObserver);
  30595. }
  30596. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30597. },
  30598. enumerable: true,
  30599. configurable: true
  30600. });
  30601. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30602. get: function () {
  30603. return true;
  30604. },
  30605. enumerable: true,
  30606. configurable: true
  30607. });
  30608. BaseTexture.prototype.getScene = function () {
  30609. return this._scene;
  30610. };
  30611. BaseTexture.prototype.getTextureMatrix = function () {
  30612. return BABYLON.Matrix.IdentityReadOnly;
  30613. };
  30614. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30615. return BABYLON.Matrix.IdentityReadOnly;
  30616. };
  30617. BaseTexture.prototype.getInternalTexture = function () {
  30618. return this._texture;
  30619. };
  30620. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30621. return !this.isBlocking || this.isReady();
  30622. };
  30623. BaseTexture.prototype.isReady = function () {
  30624. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30625. this.delayLoad();
  30626. return false;
  30627. }
  30628. if (this._texture) {
  30629. return this._texture.isReady;
  30630. }
  30631. return false;
  30632. };
  30633. BaseTexture.prototype.getSize = function () {
  30634. if (this._texture) {
  30635. if (this._texture.width) {
  30636. this._cachedSize.width = this._texture.width;
  30637. this._cachedSize.height = this._texture.height;
  30638. return this._cachedSize;
  30639. }
  30640. if (this._texture._size) {
  30641. this._cachedSize.width = this._texture._size;
  30642. this._cachedSize.height = this._texture._size;
  30643. return this._cachedSize;
  30644. }
  30645. }
  30646. return this._cachedSize;
  30647. };
  30648. BaseTexture.prototype.getBaseSize = function () {
  30649. if (!this.isReady() || !this._texture)
  30650. return BABYLON.Size.Zero();
  30651. if (this._texture._size) {
  30652. return new BABYLON.Size(this._texture._size, this._texture._size);
  30653. }
  30654. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30655. };
  30656. BaseTexture.prototype.scale = function (ratio) {
  30657. };
  30658. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30659. get: function () {
  30660. return false;
  30661. },
  30662. enumerable: true,
  30663. configurable: true
  30664. });
  30665. /** @hidden */
  30666. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30667. if (!this._scene) {
  30668. return null;
  30669. }
  30670. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30671. for (var index = 0; index < texturesCache.length; index++) {
  30672. var texturesCacheEntry = texturesCache[index];
  30673. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30674. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30675. texturesCacheEntry.incrementReferences();
  30676. return texturesCacheEntry;
  30677. }
  30678. }
  30679. }
  30680. return null;
  30681. };
  30682. /** @hidden */
  30683. BaseTexture.prototype._rebuild = function () {
  30684. };
  30685. BaseTexture.prototype.delayLoad = function () {
  30686. };
  30687. BaseTexture.prototype.clone = function () {
  30688. return null;
  30689. };
  30690. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30691. get: function () {
  30692. if (!this._texture) {
  30693. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30694. }
  30695. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30701. get: function () {
  30702. if (!this._texture) {
  30703. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30704. }
  30705. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30706. },
  30707. enumerable: true,
  30708. configurable: true
  30709. });
  30710. /**
  30711. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30712. * This will returns an RGBA array buffer containing either in values (0-255) or
  30713. * float values (0-1) depending of the underlying buffer type.
  30714. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30715. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30716. * @param buffer defines a user defined buffer to fill with data (can be null)
  30717. * @returns The Array buffer containing the pixels data.
  30718. */
  30719. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30720. if (faceIndex === void 0) { faceIndex = 0; }
  30721. if (level === void 0) { level = 0; }
  30722. if (buffer === void 0) { buffer = null; }
  30723. if (!this._texture) {
  30724. return null;
  30725. }
  30726. var size = this.getSize();
  30727. var width = size.width;
  30728. var height = size.height;
  30729. var scene = this.getScene();
  30730. if (!scene) {
  30731. return null;
  30732. }
  30733. var engine = scene.getEngine();
  30734. if (level != 0) {
  30735. width = width / Math.pow(2, level);
  30736. height = height / Math.pow(2, level);
  30737. width = Math.round(width);
  30738. height = Math.round(height);
  30739. }
  30740. if (this._texture.isCube) {
  30741. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30742. }
  30743. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30744. };
  30745. BaseTexture.prototype.releaseInternalTexture = function () {
  30746. if (this._texture) {
  30747. this._texture.dispose();
  30748. this._texture = null;
  30749. }
  30750. };
  30751. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30752. get: function () {
  30753. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30754. return null;
  30755. }
  30756. if (!this._texture._sphericalPolynomial) {
  30757. this._texture._sphericalPolynomial =
  30758. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30759. }
  30760. return this._texture._sphericalPolynomial;
  30761. },
  30762. set: function (value) {
  30763. if (this._texture) {
  30764. this._texture._sphericalPolynomial = value;
  30765. }
  30766. },
  30767. enumerable: true,
  30768. configurable: true
  30769. });
  30770. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30771. get: function () {
  30772. if (this._texture) {
  30773. return this._texture._lodTextureHigh;
  30774. }
  30775. return null;
  30776. },
  30777. enumerable: true,
  30778. configurable: true
  30779. });
  30780. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30781. get: function () {
  30782. if (this._texture) {
  30783. return this._texture._lodTextureMid;
  30784. }
  30785. return null;
  30786. },
  30787. enumerable: true,
  30788. configurable: true
  30789. });
  30790. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30791. get: function () {
  30792. if (this._texture) {
  30793. return this._texture._lodTextureLow;
  30794. }
  30795. return null;
  30796. },
  30797. enumerable: true,
  30798. configurable: true
  30799. });
  30800. BaseTexture.prototype.dispose = function () {
  30801. if (!this._scene) {
  30802. return;
  30803. }
  30804. // Animations
  30805. this._scene.stopAnimation(this);
  30806. // Remove from scene
  30807. this._scene._removePendingData(this);
  30808. var index = this._scene.textures.indexOf(this);
  30809. if (index >= 0) {
  30810. this._scene.textures.splice(index, 1);
  30811. }
  30812. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30813. if (this._texture === undefined) {
  30814. return;
  30815. }
  30816. // Release
  30817. this.releaseInternalTexture();
  30818. // Callback
  30819. this.onDisposeObservable.notifyObservers(this);
  30820. this.onDisposeObservable.clear();
  30821. };
  30822. BaseTexture.prototype.serialize = function () {
  30823. if (!this.name) {
  30824. return null;
  30825. }
  30826. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30827. // Animations
  30828. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30829. return serializationObject;
  30830. };
  30831. BaseTexture.WhenAllReady = function (textures, callback) {
  30832. var numRemaining = textures.length;
  30833. if (numRemaining === 0) {
  30834. callback();
  30835. return;
  30836. }
  30837. var _loop_1 = function () {
  30838. texture = textures[i];
  30839. if (texture.isReady()) {
  30840. if (--numRemaining === 0) {
  30841. callback();
  30842. }
  30843. }
  30844. else {
  30845. onLoadObservable = texture.onLoadObservable;
  30846. var onLoadCallback_1 = function () {
  30847. onLoadObservable.removeCallback(onLoadCallback_1);
  30848. if (--numRemaining === 0) {
  30849. callback();
  30850. }
  30851. };
  30852. onLoadObservable.add(onLoadCallback_1);
  30853. }
  30854. };
  30855. var texture, onLoadObservable;
  30856. for (var i = 0; i < textures.length; i++) {
  30857. _loop_1();
  30858. }
  30859. };
  30860. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30861. __decorate([
  30862. BABYLON.serialize()
  30863. ], BaseTexture.prototype, "name", void 0);
  30864. __decorate([
  30865. BABYLON.serialize("hasAlpha")
  30866. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30867. __decorate([
  30868. BABYLON.serialize()
  30869. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30870. __decorate([
  30871. BABYLON.serialize()
  30872. ], BaseTexture.prototype, "level", void 0);
  30873. __decorate([
  30874. BABYLON.serialize()
  30875. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30876. __decorate([
  30877. BABYLON.serialize("coordinatesMode")
  30878. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30879. __decorate([
  30880. BABYLON.serialize()
  30881. ], BaseTexture.prototype, "wrapU", void 0);
  30882. __decorate([
  30883. BABYLON.serialize()
  30884. ], BaseTexture.prototype, "wrapV", void 0);
  30885. __decorate([
  30886. BABYLON.serialize()
  30887. ], BaseTexture.prototype, "wrapR", void 0);
  30888. __decorate([
  30889. BABYLON.serialize()
  30890. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30891. __decorate([
  30892. BABYLON.serialize()
  30893. ], BaseTexture.prototype, "isCube", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], BaseTexture.prototype, "is3D", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], BaseTexture.prototype, "gammaSpace", void 0);
  30900. __decorate([
  30901. BABYLON.serialize()
  30902. ], BaseTexture.prototype, "invertZ", void 0);
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], BaseTexture.prototype, "lodGenerationScale", null);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30915. return BaseTexture;
  30916. }());
  30917. BABYLON.BaseTexture = BaseTexture;
  30918. })(BABYLON || (BABYLON = {}));
  30919. //# sourceMappingURL=babylon.baseTexture.js.map
  30920. var BABYLON;
  30921. (function (BABYLON) {
  30922. var Texture = /** @class */ (function (_super) {
  30923. __extends(Texture, _super);
  30924. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30925. if (noMipmap === void 0) { noMipmap = false; }
  30926. if (invertY === void 0) { invertY = true; }
  30927. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30928. if (onLoad === void 0) { onLoad = null; }
  30929. if (onError === void 0) { onError = null; }
  30930. if (buffer === void 0) { buffer = null; }
  30931. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30932. var _this = _super.call(this, scene) || this;
  30933. _this.uOffset = 0;
  30934. _this.vOffset = 0;
  30935. _this.uScale = 1.0;
  30936. _this.vScale = 1.0;
  30937. _this.uAng = 0;
  30938. _this.vAng = 0;
  30939. _this.wAng = 0;
  30940. /**
  30941. * Defines the center of rotation (U)
  30942. */
  30943. _this.uRotationCenter = 0.5;
  30944. /**
  30945. * Defines the center of rotation (V)
  30946. */
  30947. _this.vRotationCenter = 0.5;
  30948. /**
  30949. * Defines the center of rotation (W)
  30950. */
  30951. _this.wRotationCenter = 0.5;
  30952. _this._isBlocking = true;
  30953. _this.name = url || "";
  30954. _this.url = url;
  30955. _this._noMipmap = noMipmap;
  30956. _this._invertY = invertY;
  30957. _this._samplingMode = samplingMode;
  30958. _this._buffer = buffer;
  30959. _this._deleteBuffer = deleteBuffer;
  30960. if (format) {
  30961. _this._format = format;
  30962. }
  30963. scene = _this.getScene();
  30964. if (!scene) {
  30965. return _this;
  30966. }
  30967. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30968. var load = function () {
  30969. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30970. _this.onLoadObservable.notifyObservers(_this);
  30971. }
  30972. if (onLoad) {
  30973. onLoad();
  30974. }
  30975. if (!_this.isBlocking && scene) {
  30976. scene.resetCachedMaterial();
  30977. }
  30978. };
  30979. if (!_this.url) {
  30980. _this._delayedOnLoad = load;
  30981. _this._delayedOnError = onError;
  30982. return _this;
  30983. }
  30984. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30985. if (!_this._texture) {
  30986. if (!scene.useDelayedTextureLoading) {
  30987. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30988. if (deleteBuffer) {
  30989. delete _this._buffer;
  30990. }
  30991. }
  30992. else {
  30993. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30994. _this._delayedOnLoad = load;
  30995. _this._delayedOnError = onError;
  30996. }
  30997. }
  30998. else {
  30999. if (_this._texture.isReady) {
  31000. BABYLON.Tools.SetImmediate(function () { return load(); });
  31001. }
  31002. else {
  31003. _this._texture.onLoadedObservable.add(load);
  31004. }
  31005. }
  31006. return _this;
  31007. }
  31008. Object.defineProperty(Texture.prototype, "noMipmap", {
  31009. get: function () {
  31010. return this._noMipmap;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. Object.defineProperty(Texture.prototype, "isBlocking", {
  31016. get: function () {
  31017. return this._isBlocking;
  31018. },
  31019. set: function (value) {
  31020. this._isBlocking = value;
  31021. },
  31022. enumerable: true,
  31023. configurable: true
  31024. });
  31025. Object.defineProperty(Texture.prototype, "samplingMode", {
  31026. get: function () {
  31027. return this._samplingMode;
  31028. },
  31029. enumerable: true,
  31030. configurable: true
  31031. });
  31032. /**
  31033. * Update the url (and optional buffer) of this texture if url was null during construction.
  31034. * @param url the url of the texture
  31035. * @param buffer the buffer of the texture (defaults to null)
  31036. */
  31037. Texture.prototype.updateURL = function (url, buffer) {
  31038. if (buffer === void 0) { buffer = null; }
  31039. if (this.url) {
  31040. throw new Error("URL is already set");
  31041. }
  31042. this.url = url;
  31043. this._buffer = buffer;
  31044. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31045. this.delayLoad();
  31046. };
  31047. Texture.prototype.delayLoad = function () {
  31048. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31049. return;
  31050. }
  31051. var scene = this.getScene();
  31052. if (!scene) {
  31053. return;
  31054. }
  31055. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31056. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31057. if (!this._texture) {
  31058. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31059. if (this._deleteBuffer) {
  31060. delete this._buffer;
  31061. }
  31062. }
  31063. else {
  31064. if (this._delayedOnLoad) {
  31065. if (this._texture.isReady) {
  31066. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31067. }
  31068. else {
  31069. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31070. }
  31071. }
  31072. }
  31073. this._delayedOnLoad = null;
  31074. this._delayedOnError = null;
  31075. };
  31076. /**
  31077. * Default is Trilinear mode.
  31078. *
  31079. * | Value | Type | Description |
  31080. * | ----- | ------------------ | ----------- |
  31081. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31082. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31083. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31084. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31085. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31086. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31087. * | 7 | NEAREST_LINEAR | |
  31088. * | 8 | NEAREST_NEAREST | |
  31089. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31090. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31091. * | 11 | LINEAR_LINEAR | |
  31092. * | 12 | LINEAR_NEAREST | |
  31093. *
  31094. * > _mag_: magnification filter (close to the viewer)
  31095. * > _min_: minification filter (far from the viewer)
  31096. * > _mip_: filter used between mip map levels
  31097. *
  31098. */
  31099. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31100. if (!this._texture) {
  31101. return;
  31102. }
  31103. var scene = this.getScene();
  31104. if (!scene) {
  31105. return;
  31106. }
  31107. this._samplingMode = samplingMode;
  31108. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31109. };
  31110. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31111. x *= this.uScale;
  31112. y *= this.vScale;
  31113. x -= this.uRotationCenter * this.uScale;
  31114. y -= this.vRotationCenter * this.vScale;
  31115. z -= this.wRotationCenter;
  31116. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31117. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31118. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31119. t.z += this.wRotationCenter;
  31120. };
  31121. Texture.prototype.getTextureMatrix = function () {
  31122. var _this = this;
  31123. if (this.uOffset === this._cachedUOffset &&
  31124. this.vOffset === this._cachedVOffset &&
  31125. this.uScale === this._cachedUScale &&
  31126. this.vScale === this._cachedVScale &&
  31127. this.uAng === this._cachedUAng &&
  31128. this.vAng === this._cachedVAng &&
  31129. this.wAng === this._cachedWAng) {
  31130. return this._cachedTextureMatrix;
  31131. }
  31132. this._cachedUOffset = this.uOffset;
  31133. this._cachedVOffset = this.vOffset;
  31134. this._cachedUScale = this.uScale;
  31135. this._cachedVScale = this.vScale;
  31136. this._cachedUAng = this.uAng;
  31137. this._cachedVAng = this.vAng;
  31138. this._cachedWAng = this.wAng;
  31139. if (!this._cachedTextureMatrix) {
  31140. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31141. this._rowGenerationMatrix = new BABYLON.Matrix();
  31142. this._t0 = BABYLON.Vector3.Zero();
  31143. this._t1 = BABYLON.Vector3.Zero();
  31144. this._t2 = BABYLON.Vector3.Zero();
  31145. }
  31146. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31147. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31148. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31149. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31150. this._t1.subtractInPlace(this._t0);
  31151. this._t2.subtractInPlace(this._t0);
  31152. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31153. this._cachedTextureMatrix.m[0] = this._t1.x;
  31154. this._cachedTextureMatrix.m[1] = this._t1.y;
  31155. this._cachedTextureMatrix.m[2] = this._t1.z;
  31156. this._cachedTextureMatrix.m[4] = this._t2.x;
  31157. this._cachedTextureMatrix.m[5] = this._t2.y;
  31158. this._cachedTextureMatrix.m[6] = this._t2.z;
  31159. this._cachedTextureMatrix.m[8] = this._t0.x;
  31160. this._cachedTextureMatrix.m[9] = this._t0.y;
  31161. this._cachedTextureMatrix.m[10] = this._t0.z;
  31162. var scene = this.getScene();
  31163. if (!scene) {
  31164. return this._cachedTextureMatrix;
  31165. }
  31166. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31167. return mat.hasTexture(_this);
  31168. });
  31169. return this._cachedTextureMatrix;
  31170. };
  31171. Texture.prototype.getReflectionTextureMatrix = function () {
  31172. var _this = this;
  31173. var scene = this.getScene();
  31174. if (!scene) {
  31175. return this._cachedTextureMatrix;
  31176. }
  31177. if (this.uOffset === this._cachedUOffset &&
  31178. this.vOffset === this._cachedVOffset &&
  31179. this.uScale === this._cachedUScale &&
  31180. this.vScale === this._cachedVScale &&
  31181. this.coordinatesMode === this._cachedCoordinatesMode) {
  31182. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31183. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31184. return this._cachedTextureMatrix;
  31185. }
  31186. }
  31187. else {
  31188. return this._cachedTextureMatrix;
  31189. }
  31190. }
  31191. if (!this._cachedTextureMatrix) {
  31192. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31193. }
  31194. if (!this._projectionModeMatrix) {
  31195. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31196. }
  31197. this._cachedUOffset = this.uOffset;
  31198. this._cachedVOffset = this.vOffset;
  31199. this._cachedUScale = this.uScale;
  31200. this._cachedVScale = this.vScale;
  31201. this._cachedCoordinatesMode = this.coordinatesMode;
  31202. switch (this.coordinatesMode) {
  31203. case Texture.PLANAR_MODE:
  31204. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31205. this._cachedTextureMatrix[0] = this.uScale;
  31206. this._cachedTextureMatrix[5] = this.vScale;
  31207. this._cachedTextureMatrix[12] = this.uOffset;
  31208. this._cachedTextureMatrix[13] = this.vOffset;
  31209. break;
  31210. case Texture.PROJECTION_MODE:
  31211. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31212. this._projectionModeMatrix.m[0] = 0.5;
  31213. this._projectionModeMatrix.m[5] = -0.5;
  31214. this._projectionModeMatrix.m[10] = 0.0;
  31215. this._projectionModeMatrix.m[12] = 0.5;
  31216. this._projectionModeMatrix.m[13] = 0.5;
  31217. this._projectionModeMatrix.m[14] = 1.0;
  31218. this._projectionModeMatrix.m[15] = 1.0;
  31219. var projectionMatrix = scene.getProjectionMatrix();
  31220. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31221. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31222. break;
  31223. default:
  31224. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31225. break;
  31226. }
  31227. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31228. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31229. });
  31230. return this._cachedTextureMatrix;
  31231. };
  31232. Texture.prototype.clone = function () {
  31233. var _this = this;
  31234. return BABYLON.SerializationHelper.Clone(function () {
  31235. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31236. }, this);
  31237. };
  31238. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31239. get: function () {
  31240. if (!this._onLoadObservable) {
  31241. this._onLoadObservable = new BABYLON.Observable();
  31242. }
  31243. return this._onLoadObservable;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Texture.prototype.serialize = function () {
  31249. var serializationObject = _super.prototype.serialize.call(this);
  31250. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31251. serializationObject.base64String = this._buffer;
  31252. serializationObject.name = serializationObject.name.replace("data:", "");
  31253. }
  31254. serializationObject.invertY = this._invertY;
  31255. serializationObject.samplingMode = this.samplingMode;
  31256. return serializationObject;
  31257. };
  31258. Texture.prototype.getClassName = function () {
  31259. return "Texture";
  31260. };
  31261. Texture.prototype.dispose = function () {
  31262. _super.prototype.dispose.call(this);
  31263. if (this._onLoadObservable) {
  31264. this._onLoadObservable.clear();
  31265. this._onLoadObservable = null;
  31266. }
  31267. this._delayedOnLoad = null;
  31268. this._delayedOnError = null;
  31269. };
  31270. // Statics
  31271. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31272. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31273. if (onLoad === void 0) { onLoad = null; }
  31274. if (onError === void 0) { onError = null; }
  31275. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31276. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31277. };
  31278. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31279. if (parsedTexture.customType) {
  31280. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31281. // Update Sampling Mode
  31282. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31283. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31284. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31285. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31286. }
  31287. }
  31288. return parsedCustomTexture;
  31289. }
  31290. if (parsedTexture.isCube) {
  31291. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31292. }
  31293. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31294. return null;
  31295. }
  31296. var texture = BABYLON.SerializationHelper.Parse(function () {
  31297. var generateMipMaps = true;
  31298. if (parsedTexture.noMipmap) {
  31299. generateMipMaps = false;
  31300. }
  31301. if (parsedTexture.mirrorPlane) {
  31302. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31303. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31304. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31305. return mirrorTexture;
  31306. }
  31307. else if (parsedTexture.isRenderTarget) {
  31308. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31309. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31310. return renderTargetTexture;
  31311. }
  31312. else {
  31313. var texture;
  31314. if (parsedTexture.base64String) {
  31315. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31316. }
  31317. else {
  31318. var url = rootUrl + parsedTexture.name;
  31319. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31320. url = parsedTexture.url;
  31321. }
  31322. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31323. }
  31324. return texture;
  31325. }
  31326. }, parsedTexture, scene);
  31327. // Update Sampling Mode
  31328. if (parsedTexture.samplingMode) {
  31329. var sampling = parsedTexture.samplingMode;
  31330. if (texture._samplingMode !== sampling) {
  31331. texture.updateSamplingMode(sampling);
  31332. }
  31333. }
  31334. // Animations
  31335. if (parsedTexture.animations) {
  31336. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31337. var parsedAnimation = parsedTexture.animations[animationIndex];
  31338. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31339. }
  31340. }
  31341. return texture;
  31342. };
  31343. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31344. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31345. if (noMipmap === void 0) { noMipmap = false; }
  31346. if (invertY === void 0) { invertY = true; }
  31347. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31348. if (onLoad === void 0) { onLoad = null; }
  31349. if (onError === void 0) { onError = null; }
  31350. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31351. if (name.substr(0, 5) !== "data:") {
  31352. name = "data:" + name;
  31353. }
  31354. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31355. };
  31356. // Constants
  31357. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31358. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31359. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31360. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31361. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31362. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31363. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31364. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31365. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31366. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31367. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31368. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31369. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31370. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31371. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31372. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31373. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31374. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31375. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31376. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31377. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31378. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31379. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31380. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31381. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31382. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31383. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31384. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31385. /**
  31386. * 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
  31387. */
  31388. Texture.UseSerializedUrlIfAny = false;
  31389. __decorate([
  31390. BABYLON.serialize()
  31391. ], Texture.prototype, "url", void 0);
  31392. __decorate([
  31393. BABYLON.serialize()
  31394. ], Texture.prototype, "uOffset", void 0);
  31395. __decorate([
  31396. BABYLON.serialize()
  31397. ], Texture.prototype, "vOffset", void 0);
  31398. __decorate([
  31399. BABYLON.serialize()
  31400. ], Texture.prototype, "uScale", void 0);
  31401. __decorate([
  31402. BABYLON.serialize()
  31403. ], Texture.prototype, "vScale", void 0);
  31404. __decorate([
  31405. BABYLON.serialize()
  31406. ], Texture.prototype, "uAng", void 0);
  31407. __decorate([
  31408. BABYLON.serialize()
  31409. ], Texture.prototype, "vAng", void 0);
  31410. __decorate([
  31411. BABYLON.serialize()
  31412. ], Texture.prototype, "wAng", void 0);
  31413. __decorate([
  31414. BABYLON.serialize()
  31415. ], Texture.prototype, "uRotationCenter", void 0);
  31416. __decorate([
  31417. BABYLON.serialize()
  31418. ], Texture.prototype, "vRotationCenter", void 0);
  31419. __decorate([
  31420. BABYLON.serialize()
  31421. ], Texture.prototype, "wRotationCenter", void 0);
  31422. __decorate([
  31423. BABYLON.serialize()
  31424. ], Texture.prototype, "isBlocking", null);
  31425. return Texture;
  31426. }(BABYLON.BaseTexture));
  31427. BABYLON.Texture = Texture;
  31428. })(BABYLON || (BABYLON = {}));
  31429. //# sourceMappingURL=babylon.texture.js.map
  31430. var BABYLON;
  31431. (function (BABYLON) {
  31432. /**
  31433. * @hidden
  31434. **/
  31435. var _CreationDataStorage = /** @class */ (function () {
  31436. function _CreationDataStorage() {
  31437. }
  31438. return _CreationDataStorage;
  31439. }());
  31440. BABYLON._CreationDataStorage = _CreationDataStorage;
  31441. /**
  31442. * @hidden
  31443. **/
  31444. var _InstanceDataStorage = /** @class */ (function () {
  31445. function _InstanceDataStorage() {
  31446. this.visibleInstances = {};
  31447. this.renderIdForInstances = new Array();
  31448. this.batchCache = new _InstancesBatch();
  31449. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31450. }
  31451. return _InstanceDataStorage;
  31452. }());
  31453. /**
  31454. * @hidden
  31455. **/
  31456. var _InstancesBatch = /** @class */ (function () {
  31457. function _InstancesBatch() {
  31458. this.mustReturn = false;
  31459. this.visibleInstances = new Array();
  31460. this.renderSelf = new Array();
  31461. }
  31462. return _InstancesBatch;
  31463. }());
  31464. BABYLON._InstancesBatch = _InstancesBatch;
  31465. /**
  31466. * Class used to represent renderable models
  31467. */
  31468. var Mesh = /** @class */ (function (_super) {
  31469. __extends(Mesh, _super);
  31470. /**
  31471. * @constructor
  31472. * @param name The value used by scene.getMeshByName() to do a lookup.
  31473. * @param scene The scene to add this mesh to.
  31474. * @param parent The parent of this mesh, if it has one
  31475. * @param source An optional Mesh from which geometry is shared, cloned.
  31476. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31477. * When false, achieved by calling a clone(), also passing False.
  31478. * This will make creation of children, recursive.
  31479. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31480. */
  31481. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31482. if (scene === void 0) { scene = null; }
  31483. if (parent === void 0) { parent = null; }
  31484. if (source === void 0) { source = null; }
  31485. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31486. var _this = _super.call(this, name, scene) || this;
  31487. // Members
  31488. /**
  31489. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31490. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31491. */
  31492. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31493. /**
  31494. * Gets the list of instances created from this mesh
  31495. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31496. */
  31497. _this.instances = new Array();
  31498. _this._LODLevels = new Array();
  31499. /** @hidden */
  31500. _this._instanceDataStorage = new _InstanceDataStorage();
  31501. // Use by builder only to know what orientation were the mesh build in.
  31502. /** @hidden */
  31503. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31504. /**
  31505. * Use this property to change the original side orientation defined at construction time
  31506. */
  31507. _this.overrideMaterialSideOrientation = null;
  31508. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31509. // Will be used to save a source mesh reference, If any
  31510. _this._source = null;
  31511. scene = _this.getScene();
  31512. if (source) {
  31513. // Geometry
  31514. if (source._geometry) {
  31515. source._geometry.applyToMesh(_this);
  31516. }
  31517. // Deep copy
  31518. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31519. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31520. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31521. ], ["_poseMatrix"]);
  31522. // Source mesh
  31523. _this._source = source;
  31524. // Construction Params
  31525. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31526. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31527. _this._creationDataStorage = source._creationDataStorage;
  31528. // Animation ranges
  31529. if (_this._source._ranges) {
  31530. var ranges = _this._source._ranges;
  31531. for (var name in ranges) {
  31532. if (!ranges.hasOwnProperty(name)) {
  31533. continue;
  31534. }
  31535. if (!ranges[name]) {
  31536. continue;
  31537. }
  31538. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31539. }
  31540. }
  31541. // Metadata
  31542. if (source.metadata && source.metadata.clone) {
  31543. _this.metadata = source.metadata.clone();
  31544. }
  31545. else {
  31546. _this.metadata = source.metadata;
  31547. }
  31548. // Tags
  31549. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31550. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31551. }
  31552. // Parent
  31553. _this.parent = source.parent;
  31554. // Pivot
  31555. _this.setPivotMatrix(source.getPivotMatrix());
  31556. _this.id = name + "." + source.id;
  31557. // Material
  31558. _this.material = source.material;
  31559. var index;
  31560. if (!doNotCloneChildren) {
  31561. // Children
  31562. var directDescendants = source.getDescendants(true);
  31563. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31564. var child = directDescendants[index_1];
  31565. if (child.clone) {
  31566. child.clone(name + "." + child.name, _this);
  31567. }
  31568. }
  31569. }
  31570. // Physics clone
  31571. var physicsEngine = _this.getScene().getPhysicsEngine();
  31572. if (clonePhysicsImpostor && physicsEngine) {
  31573. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31574. if (impostor) {
  31575. _this.physicsImpostor = impostor.clone(_this);
  31576. }
  31577. }
  31578. // Particles
  31579. for (index = 0; index < scene.particleSystems.length; index++) {
  31580. var system = scene.particleSystems[index];
  31581. if (system.emitter === source) {
  31582. system.clone(system.name, _this);
  31583. }
  31584. }
  31585. _this.refreshBoundingInfo();
  31586. _this.computeWorldMatrix(true);
  31587. }
  31588. // Parent
  31589. if (parent !== null) {
  31590. _this.parent = parent;
  31591. }
  31592. return _this;
  31593. }
  31594. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31595. /**
  31596. * An event triggered before rendering the mesh
  31597. */
  31598. get: function () {
  31599. if (!this._onBeforeRenderObservable) {
  31600. this._onBeforeRenderObservable = new BABYLON.Observable();
  31601. }
  31602. return this._onBeforeRenderObservable;
  31603. },
  31604. enumerable: true,
  31605. configurable: true
  31606. });
  31607. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31608. /**
  31609. * An event triggered after rendering the mesh
  31610. */
  31611. get: function () {
  31612. if (!this._onAfterRenderObservable) {
  31613. this._onAfterRenderObservable = new BABYLON.Observable();
  31614. }
  31615. return this._onAfterRenderObservable;
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31621. /**
  31622. * An event triggered before drawing the mesh
  31623. */
  31624. get: function () {
  31625. if (!this._onBeforeDrawObservable) {
  31626. this._onBeforeDrawObservable = new BABYLON.Observable();
  31627. }
  31628. return this._onBeforeDrawObservable;
  31629. },
  31630. enumerable: true,
  31631. configurable: true
  31632. });
  31633. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31634. /**
  31635. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31636. */
  31637. set: function (callback) {
  31638. if (this._onBeforeDrawObserver) {
  31639. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31640. }
  31641. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31642. },
  31643. enumerable: true,
  31644. configurable: true
  31645. });
  31646. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31647. /**
  31648. * Gets or sets the morph target manager
  31649. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31650. */
  31651. get: function () {
  31652. return this._morphTargetManager;
  31653. },
  31654. set: function (value) {
  31655. if (this._morphTargetManager === value) {
  31656. return;
  31657. }
  31658. this._morphTargetManager = value;
  31659. this._syncGeometryWithMorphTargetManager();
  31660. },
  31661. enumerable: true,
  31662. configurable: true
  31663. });
  31664. Object.defineProperty(Mesh.prototype, "source", {
  31665. /**
  31666. * Gets the source mesh (the one used to clone this one from)
  31667. */
  31668. get: function () {
  31669. return this._source;
  31670. },
  31671. enumerable: true,
  31672. configurable: true
  31673. });
  31674. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31675. /**
  31676. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31677. */
  31678. get: function () {
  31679. return this._unIndexed;
  31680. },
  31681. set: function (value) {
  31682. if (this._unIndexed !== value) {
  31683. this._unIndexed = value;
  31684. this._markSubMeshesAsAttributesDirty();
  31685. }
  31686. },
  31687. enumerable: true,
  31688. configurable: true
  31689. });
  31690. // Methods
  31691. /**
  31692. * Gets the class name
  31693. * @returns the string "Mesh".
  31694. */
  31695. Mesh.prototype.getClassName = function () {
  31696. return "Mesh";
  31697. };
  31698. /**
  31699. * Returns a description of this mesh
  31700. * @param fullDetails define if full details about this mesh must be used
  31701. * @returns a descriptive string representing this mesh
  31702. */
  31703. Mesh.prototype.toString = function (fullDetails) {
  31704. var ret = _super.prototype.toString.call(this, fullDetails);
  31705. ret += ", n vertices: " + this.getTotalVertices();
  31706. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31707. if (this.animations) {
  31708. for (var i = 0; i < this.animations.length; i++) {
  31709. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31710. }
  31711. }
  31712. if (fullDetails) {
  31713. if (this._geometry) {
  31714. var ib = this.getIndices();
  31715. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31716. if (vb && ib) {
  31717. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31718. }
  31719. }
  31720. else {
  31721. ret += ", flat shading: UNKNOWN";
  31722. }
  31723. }
  31724. return ret;
  31725. };
  31726. /** @hidden */
  31727. Mesh.prototype._unBindEffect = function () {
  31728. _super.prototype._unBindEffect.call(this);
  31729. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31730. var instance = _a[_i];
  31731. instance._unBindEffect();
  31732. }
  31733. };
  31734. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31735. /**
  31736. * Gets a boolean indicating if this mesh has LOD
  31737. */
  31738. get: function () {
  31739. return this._LODLevels.length > 0;
  31740. },
  31741. enumerable: true,
  31742. configurable: true
  31743. });
  31744. /**
  31745. * Gets the list of MeshLODLevel associated with the current mesh
  31746. * @returns an array of MeshLODLevel
  31747. */
  31748. Mesh.prototype.getLODLevels = function () {
  31749. return this._LODLevels;
  31750. };
  31751. Mesh.prototype._sortLODLevels = function () {
  31752. this._LODLevels.sort(function (a, b) {
  31753. if (a.distance < b.distance) {
  31754. return 1;
  31755. }
  31756. if (a.distance > b.distance) {
  31757. return -1;
  31758. }
  31759. return 0;
  31760. });
  31761. };
  31762. /**
  31763. * Add a mesh as LOD level triggered at the given distance.
  31764. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31765. * @param distance The distance from the center of the object to show this level
  31766. * @param mesh The mesh to be added as LOD level (can be null)
  31767. * @return This mesh (for chaining)
  31768. */
  31769. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31770. if (mesh && mesh._masterMesh) {
  31771. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31772. return this;
  31773. }
  31774. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31775. this._LODLevels.push(level);
  31776. if (mesh) {
  31777. mesh._masterMesh = this;
  31778. }
  31779. this._sortLODLevels();
  31780. return this;
  31781. };
  31782. /**
  31783. * Returns the LOD level mesh at the passed distance or null if not found.
  31784. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31785. * @param distance The distance from the center of the object to show this level
  31786. * @returns a Mesh or `null`
  31787. */
  31788. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31789. for (var index = 0; index < this._LODLevels.length; index++) {
  31790. var level = this._LODLevels[index];
  31791. if (level.distance === distance) {
  31792. return level.mesh;
  31793. }
  31794. }
  31795. return null;
  31796. };
  31797. /**
  31798. * Remove a mesh from the LOD array
  31799. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31800. * @param mesh defines the mesh to be removed
  31801. * @return This mesh (for chaining)
  31802. */
  31803. Mesh.prototype.removeLODLevel = function (mesh) {
  31804. for (var index = 0; index < this._LODLevels.length; index++) {
  31805. if (this._LODLevels[index].mesh === mesh) {
  31806. this._LODLevels.splice(index, 1);
  31807. if (mesh) {
  31808. mesh._masterMesh = null;
  31809. }
  31810. }
  31811. }
  31812. this._sortLODLevels();
  31813. return this;
  31814. };
  31815. /**
  31816. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31817. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31818. * @param camera defines the camera to use to compute distance
  31819. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31820. * @return This mesh (for chaining)
  31821. */
  31822. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31823. if (!this._LODLevels || this._LODLevels.length === 0) {
  31824. return this;
  31825. }
  31826. var bSphere;
  31827. if (boundingSphere) {
  31828. bSphere = boundingSphere;
  31829. }
  31830. else {
  31831. var boundingInfo = this.getBoundingInfo();
  31832. bSphere = boundingInfo.boundingSphere;
  31833. }
  31834. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31835. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31836. if (this.onLODLevelSelection) {
  31837. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31838. }
  31839. return this;
  31840. }
  31841. for (var index = 0; index < this._LODLevels.length; index++) {
  31842. var level = this._LODLevels[index];
  31843. if (level.distance < distanceToCamera) {
  31844. if (level.mesh) {
  31845. level.mesh._preActivate();
  31846. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31847. }
  31848. if (this.onLODLevelSelection) {
  31849. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31850. }
  31851. return level.mesh;
  31852. }
  31853. }
  31854. if (this.onLODLevelSelection) {
  31855. this.onLODLevelSelection(distanceToCamera, this, this);
  31856. }
  31857. return this;
  31858. };
  31859. Object.defineProperty(Mesh.prototype, "geometry", {
  31860. /**
  31861. * Gets the mesh internal Geometry object
  31862. */
  31863. get: function () {
  31864. return this._geometry;
  31865. },
  31866. enumerable: true,
  31867. configurable: true
  31868. });
  31869. /**
  31870. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31871. * @returns the total number of vertices
  31872. */
  31873. Mesh.prototype.getTotalVertices = function () {
  31874. if (this._geometry === null || this._geometry === undefined) {
  31875. return 0;
  31876. }
  31877. return this._geometry.getTotalVertices();
  31878. };
  31879. /**
  31880. * Returns the content of an associated vertex buffer
  31881. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31882. * - BABYLON.VertexBuffer.PositionKind
  31883. * - BABYLON.VertexBuffer.UVKind
  31884. * - BABYLON.VertexBuffer.UV2Kind
  31885. * - BABYLON.VertexBuffer.UV3Kind
  31886. * - BABYLON.VertexBuffer.UV4Kind
  31887. * - BABYLON.VertexBuffer.UV5Kind
  31888. * - BABYLON.VertexBuffer.UV6Kind
  31889. * - BABYLON.VertexBuffer.ColorKind
  31890. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31891. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31892. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31893. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31894. * @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
  31895. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31896. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31897. */
  31898. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31899. if (!this._geometry) {
  31900. return null;
  31901. }
  31902. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31903. };
  31904. /**
  31905. * Returns the mesh VertexBuffer object from the requested `kind`
  31906. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31907. * - BABYLON.VertexBuffer.PositionKind
  31908. * - BABYLON.VertexBuffer.UVKind
  31909. * - BABYLON.VertexBuffer.UV2Kind
  31910. * - BABYLON.VertexBuffer.UV3Kind
  31911. * - BABYLON.VertexBuffer.UV4Kind
  31912. * - BABYLON.VertexBuffer.UV5Kind
  31913. * - BABYLON.VertexBuffer.UV6Kind
  31914. * - BABYLON.VertexBuffer.ColorKind
  31915. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31916. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31917. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31918. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31919. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31920. */
  31921. Mesh.prototype.getVertexBuffer = function (kind) {
  31922. if (!this._geometry) {
  31923. return null;
  31924. }
  31925. return this._geometry.getVertexBuffer(kind);
  31926. };
  31927. /**
  31928. * Tests if a specific vertex buffer is associated with this mesh
  31929. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31930. * - BABYLON.VertexBuffer.PositionKind
  31931. * - BABYLON.VertexBuffer.UVKind
  31932. * - BABYLON.VertexBuffer.UV2Kind
  31933. * - BABYLON.VertexBuffer.UV3Kind
  31934. * - BABYLON.VertexBuffer.UV4Kind
  31935. * - BABYLON.VertexBuffer.UV5Kind
  31936. * - BABYLON.VertexBuffer.UV6Kind
  31937. * - BABYLON.VertexBuffer.ColorKind
  31938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31942. * @returns a boolean
  31943. */
  31944. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31945. if (!this._geometry) {
  31946. if (this._delayInfo) {
  31947. return this._delayInfo.indexOf(kind) !== -1;
  31948. }
  31949. return false;
  31950. }
  31951. return this._geometry.isVerticesDataPresent(kind);
  31952. };
  31953. /**
  31954. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31955. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31956. * - BABYLON.VertexBuffer.PositionKind
  31957. * - BABYLON.VertexBuffer.UVKind
  31958. * - BABYLON.VertexBuffer.UV2Kind
  31959. * - BABYLON.VertexBuffer.UV3Kind
  31960. * - BABYLON.VertexBuffer.UV4Kind
  31961. * - BABYLON.VertexBuffer.UV5Kind
  31962. * - BABYLON.VertexBuffer.UV6Kind
  31963. * - BABYLON.VertexBuffer.ColorKind
  31964. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31965. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31966. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31967. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31968. * @returns a boolean
  31969. */
  31970. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31971. if (!this._geometry) {
  31972. if (this._delayInfo) {
  31973. return this._delayInfo.indexOf(kind) !== -1;
  31974. }
  31975. return false;
  31976. }
  31977. return this._geometry.isVertexBufferUpdatable(kind);
  31978. };
  31979. /**
  31980. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31981. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31982. * - BABYLON.VertexBuffer.PositionKind
  31983. * - BABYLON.VertexBuffer.UVKind
  31984. * - BABYLON.VertexBuffer.UV2Kind
  31985. * - BABYLON.VertexBuffer.UV3Kind
  31986. * - BABYLON.VertexBuffer.UV4Kind
  31987. * - BABYLON.VertexBuffer.UV5Kind
  31988. * - BABYLON.VertexBuffer.UV6Kind
  31989. * - BABYLON.VertexBuffer.ColorKind
  31990. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31991. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31992. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31993. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31994. * @returns an array of strings
  31995. */
  31996. Mesh.prototype.getVerticesDataKinds = function () {
  31997. if (!this._geometry) {
  31998. var result = new Array();
  31999. if (this._delayInfo) {
  32000. this._delayInfo.forEach(function (kind, index, array) {
  32001. result.push(kind);
  32002. });
  32003. }
  32004. return result;
  32005. }
  32006. return this._geometry.getVerticesDataKinds();
  32007. };
  32008. /**
  32009. * Returns a positive integer : the total number of indices in this mesh geometry.
  32010. * @returns the numner of indices or zero if the mesh has no geometry.
  32011. */
  32012. Mesh.prototype.getTotalIndices = function () {
  32013. if (!this._geometry) {
  32014. return 0;
  32015. }
  32016. return this._geometry.getTotalIndices();
  32017. };
  32018. /**
  32019. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32020. * @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.
  32021. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32022. * @returns the indices array or an empty array if the mesh has no geometry
  32023. */
  32024. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32025. if (!this._geometry) {
  32026. return [];
  32027. }
  32028. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32029. };
  32030. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32031. get: function () {
  32032. return this._masterMesh !== null && this._masterMesh !== undefined;
  32033. },
  32034. enumerable: true,
  32035. configurable: true
  32036. });
  32037. /**
  32038. * Determine if the current mesh is ready to be rendered
  32039. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32040. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32041. * @returns true if all associated assets are ready (material, textures, shaders)
  32042. */
  32043. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32044. if (completeCheck === void 0) { completeCheck = false; }
  32045. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32046. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32047. return false;
  32048. }
  32049. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32050. return false;
  32051. }
  32052. if (!this.subMeshes || this.subMeshes.length === 0) {
  32053. return true;
  32054. }
  32055. if (!completeCheck) {
  32056. return true;
  32057. }
  32058. var engine = this.getEngine();
  32059. var scene = this.getScene();
  32060. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32061. this.computeWorldMatrix();
  32062. var mat = this.material || scene.defaultMaterial;
  32063. if (mat) {
  32064. if (mat.storeEffectOnSubMeshes) {
  32065. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32066. var subMesh = _a[_i];
  32067. var effectiveMaterial = subMesh.getMaterial();
  32068. if (effectiveMaterial) {
  32069. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32070. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32071. return false;
  32072. }
  32073. }
  32074. else {
  32075. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32076. return false;
  32077. }
  32078. }
  32079. }
  32080. }
  32081. }
  32082. else {
  32083. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32084. return false;
  32085. }
  32086. }
  32087. }
  32088. // Shadows
  32089. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32090. var light = _c[_b];
  32091. var generator = light.getShadowGenerator();
  32092. if (generator) {
  32093. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32094. var subMesh = _e[_d];
  32095. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32096. return false;
  32097. }
  32098. }
  32099. }
  32100. }
  32101. // LOD
  32102. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32103. var lod = _g[_f];
  32104. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32105. return false;
  32106. }
  32107. }
  32108. return true;
  32109. };
  32110. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32111. /**
  32112. * 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.
  32113. */
  32114. get: function () {
  32115. return this._areNormalsFrozen;
  32116. },
  32117. enumerable: true,
  32118. configurable: true
  32119. });
  32120. /**
  32121. * 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.
  32122. * @returns the current mesh
  32123. */
  32124. Mesh.prototype.freezeNormals = function () {
  32125. this._areNormalsFrozen = true;
  32126. return this;
  32127. };
  32128. /**
  32129. * 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
  32130. * @returns the current mesh
  32131. */
  32132. Mesh.prototype.unfreezeNormals = function () {
  32133. this._areNormalsFrozen = false;
  32134. return this;
  32135. };
  32136. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32137. /**
  32138. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32139. */
  32140. set: function (count) {
  32141. this._instanceDataStorage.overridenInstanceCount = count;
  32142. },
  32143. enumerable: true,
  32144. configurable: true
  32145. });
  32146. // Methods
  32147. /** @hidden */
  32148. Mesh.prototype._preActivate = function () {
  32149. var sceneRenderId = this.getScene().getRenderId();
  32150. if (this._preActivateId === sceneRenderId) {
  32151. return this;
  32152. }
  32153. this._preActivateId = sceneRenderId;
  32154. this._instanceDataStorage.visibleInstances = null;
  32155. return this;
  32156. };
  32157. /** @hidden */
  32158. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32159. if (this._instanceDataStorage.visibleInstances) {
  32160. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32161. }
  32162. return this;
  32163. };
  32164. /** @hidden */
  32165. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32166. if (!this._instanceDataStorage.visibleInstances) {
  32167. this._instanceDataStorage.visibleInstances = {};
  32168. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32169. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32170. }
  32171. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32172. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32173. }
  32174. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32175. return this;
  32176. };
  32177. /**
  32178. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32179. * This means the mesh underlying bounding box and sphere are recomputed.
  32180. * @returns the current mesh
  32181. */
  32182. Mesh.prototype.refreshBoundingInfo = function () {
  32183. return this._refreshBoundingInfo(false);
  32184. };
  32185. /** @hidden */
  32186. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32187. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32188. return this;
  32189. }
  32190. var data = this._getPositionData(applySkeleton);
  32191. if (data) {
  32192. var bias = this.geometry ? this.geometry.boundingBias : null;
  32193. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32194. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32195. }
  32196. if (this.subMeshes) {
  32197. for (var index = 0; index < this.subMeshes.length; index++) {
  32198. this.subMeshes[index].refreshBoundingInfo();
  32199. }
  32200. }
  32201. this._updateBoundingInfo();
  32202. return this;
  32203. };
  32204. Mesh.prototype._getPositionData = function (applySkeleton) {
  32205. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32206. if (data && applySkeleton && this.skeleton) {
  32207. data = BABYLON.Tools.Slice(data);
  32208. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32209. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32210. if (matricesWeightsData && matricesIndicesData) {
  32211. var needExtras = this.numBoneInfluencers > 4;
  32212. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32213. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32214. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32215. var tempVector = BABYLON.Tmp.Vector3[0];
  32216. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32217. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32218. var matWeightIdx = 0;
  32219. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32220. finalMatrix.reset();
  32221. var inf;
  32222. var weight;
  32223. for (inf = 0; inf < 4; inf++) {
  32224. weight = matricesWeightsData[matWeightIdx + inf];
  32225. if (weight > 0) {
  32226. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32227. finalMatrix.addToSelf(tempMatrix);
  32228. }
  32229. }
  32230. if (needExtras) {
  32231. for (inf = 0; inf < 4; inf++) {
  32232. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32233. if (weight > 0) {
  32234. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32235. finalMatrix.addToSelf(tempMatrix);
  32236. }
  32237. }
  32238. }
  32239. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32240. tempVector.toArray(data, index);
  32241. }
  32242. }
  32243. }
  32244. return data;
  32245. };
  32246. /** @hidden */
  32247. Mesh.prototype._createGlobalSubMesh = function (force) {
  32248. var totalVertices = this.getTotalVertices();
  32249. if (!totalVertices || !this.getIndices()) {
  32250. return null;
  32251. }
  32252. // Check if we need to recreate the submeshes
  32253. if (this.subMeshes && this.subMeshes.length > 0) {
  32254. var ib = this.getIndices();
  32255. if (!ib) {
  32256. return null;
  32257. }
  32258. var totalIndices = ib.length;
  32259. var needToRecreate = false;
  32260. if (force) {
  32261. needToRecreate = true;
  32262. }
  32263. else {
  32264. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32265. var submesh = _a[_i];
  32266. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32267. needToRecreate = true;
  32268. break;
  32269. }
  32270. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32271. needToRecreate = true;
  32272. break;
  32273. }
  32274. }
  32275. }
  32276. if (!needToRecreate) {
  32277. return this.subMeshes[0];
  32278. }
  32279. }
  32280. this.releaseSubMeshes();
  32281. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32282. };
  32283. /**
  32284. * This function will subdivide the mesh into multiple submeshes
  32285. * @param count defines the expected number of submeshes
  32286. */
  32287. Mesh.prototype.subdivide = function (count) {
  32288. if (count < 1) {
  32289. return;
  32290. }
  32291. var totalIndices = this.getTotalIndices();
  32292. var subdivisionSize = (totalIndices / count) | 0;
  32293. var offset = 0;
  32294. // Ensure that subdivisionSize is a multiple of 3
  32295. while (subdivisionSize % 3 !== 0) {
  32296. subdivisionSize++;
  32297. }
  32298. this.releaseSubMeshes();
  32299. for (var index = 0; index < count; index++) {
  32300. if (offset >= totalIndices) {
  32301. break;
  32302. }
  32303. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32304. offset += subdivisionSize;
  32305. }
  32306. this.synchronizeInstances();
  32307. };
  32308. /**
  32309. * Copy a FloatArray into a specific associated vertex buffer
  32310. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32311. * - BABYLON.VertexBuffer.PositionKind
  32312. * - BABYLON.VertexBuffer.UVKind
  32313. * - BABYLON.VertexBuffer.UV2Kind
  32314. * - BABYLON.VertexBuffer.UV3Kind
  32315. * - BABYLON.VertexBuffer.UV4Kind
  32316. * - BABYLON.VertexBuffer.UV5Kind
  32317. * - BABYLON.VertexBuffer.UV6Kind
  32318. * - BABYLON.VertexBuffer.ColorKind
  32319. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32320. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32321. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32322. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32323. * @param data defines the data source
  32324. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32325. * @param stride defines the data stride size (can be null)
  32326. * @returns the current mesh
  32327. */
  32328. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32329. if (updatable === void 0) { updatable = false; }
  32330. if (!this._geometry) {
  32331. var vertexData = new BABYLON.VertexData();
  32332. vertexData.set(data, kind);
  32333. var scene = this.getScene();
  32334. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32335. }
  32336. else {
  32337. this._geometry.setVerticesData(kind, data, updatable, stride);
  32338. }
  32339. return this;
  32340. };
  32341. /**
  32342. * Flags an associated vertex buffer as updatable
  32343. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32344. * - BABYLON.VertexBuffer.PositionKind
  32345. * - BABYLON.VertexBuffer.UVKind
  32346. * - BABYLON.VertexBuffer.UV2Kind
  32347. * - BABYLON.VertexBuffer.UV3Kind
  32348. * - BABYLON.VertexBuffer.UV4Kind
  32349. * - BABYLON.VertexBuffer.UV5Kind
  32350. * - BABYLON.VertexBuffer.UV6Kind
  32351. * - BABYLON.VertexBuffer.ColorKind
  32352. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32353. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32354. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32355. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32356. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32357. */
  32358. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32359. if (updatable === void 0) { updatable = true; }
  32360. var vb = this.getVertexBuffer(kind);
  32361. if (!vb || vb.isUpdatable() === updatable) {
  32362. return;
  32363. }
  32364. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32365. };
  32366. /**
  32367. * Sets the mesh global Vertex Buffer
  32368. * @param buffer defines the buffer to use
  32369. * @returns the current mesh
  32370. */
  32371. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32372. if (!this._geometry) {
  32373. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32374. }
  32375. this._geometry.setVerticesBuffer(buffer);
  32376. return this;
  32377. };
  32378. /**
  32379. * Update a specific associated vertex buffer
  32380. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32381. * - BABYLON.VertexBuffer.PositionKind
  32382. * - BABYLON.VertexBuffer.UVKind
  32383. * - BABYLON.VertexBuffer.UV2Kind
  32384. * - BABYLON.VertexBuffer.UV3Kind
  32385. * - BABYLON.VertexBuffer.UV4Kind
  32386. * - BABYLON.VertexBuffer.UV5Kind
  32387. * - BABYLON.VertexBuffer.UV6Kind
  32388. * - BABYLON.VertexBuffer.ColorKind
  32389. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32390. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32391. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32392. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32393. * @param data defines the data source
  32394. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32395. * @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)
  32396. * @returns the current mesh
  32397. */
  32398. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32399. if (!this._geometry) {
  32400. return this;
  32401. }
  32402. if (!makeItUnique) {
  32403. this._geometry.updateVerticesData(kind, data, updateExtends);
  32404. }
  32405. else {
  32406. this.makeGeometryUnique();
  32407. this.updateVerticesData(kind, data, updateExtends, false);
  32408. }
  32409. return this;
  32410. };
  32411. /**
  32412. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32413. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32414. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32415. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32416. * @returns the current mesh
  32417. */
  32418. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32419. if (computeNormals === void 0) { computeNormals = true; }
  32420. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32421. if (!positions) {
  32422. return this;
  32423. }
  32424. positionFunction(positions);
  32425. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32426. if (computeNormals) {
  32427. var indices = this.getIndices();
  32428. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32429. if (!normals) {
  32430. return this;
  32431. }
  32432. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32433. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32434. }
  32435. return this;
  32436. };
  32437. /**
  32438. * Creates a un-shared specific occurence of the geometry for the mesh.
  32439. * @returns the current mesh
  32440. */
  32441. Mesh.prototype.makeGeometryUnique = function () {
  32442. if (!this._geometry) {
  32443. return this;
  32444. }
  32445. var oldGeometry = this._geometry;
  32446. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32447. oldGeometry.releaseForMesh(this, true);
  32448. geometry.applyToMesh(this);
  32449. return this;
  32450. };
  32451. /**
  32452. * Set the index buffer of this mesh
  32453. * @param indices defines the source data
  32454. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32455. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32456. * @returns the current mesh
  32457. */
  32458. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32459. if (totalVertices === void 0) { totalVertices = null; }
  32460. if (updatable === void 0) { updatable = false; }
  32461. if (!this._geometry) {
  32462. var vertexData = new BABYLON.VertexData();
  32463. vertexData.indices = indices;
  32464. var scene = this.getScene();
  32465. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32466. }
  32467. else {
  32468. this._geometry.setIndices(indices, totalVertices, updatable);
  32469. }
  32470. return this;
  32471. };
  32472. /**
  32473. * Update the current index buffer
  32474. * @param indices defines the source data
  32475. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32476. * @returns the current mesh
  32477. */
  32478. Mesh.prototype.updateIndices = function (indices, offset) {
  32479. if (!this._geometry) {
  32480. return this;
  32481. }
  32482. this._geometry.updateIndices(indices, offset);
  32483. return this;
  32484. };
  32485. /**
  32486. * Invert the geometry to move from a right handed system to a left handed one.
  32487. * @returns the current mesh
  32488. */
  32489. Mesh.prototype.toLeftHanded = function () {
  32490. if (!this._geometry) {
  32491. return this;
  32492. }
  32493. this._geometry.toLeftHanded();
  32494. return this;
  32495. };
  32496. /** @hidden */
  32497. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32498. if (!this._geometry) {
  32499. return this;
  32500. }
  32501. var engine = this.getScene().getEngine();
  32502. // Wireframe
  32503. var indexToBind;
  32504. if (this._unIndexed) {
  32505. indexToBind = null;
  32506. }
  32507. else {
  32508. switch (fillMode) {
  32509. case BABYLON.Material.PointFillMode:
  32510. indexToBind = null;
  32511. break;
  32512. case BABYLON.Material.WireFrameFillMode:
  32513. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32514. break;
  32515. default:
  32516. case BABYLON.Material.TriangleFillMode:
  32517. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32518. break;
  32519. }
  32520. }
  32521. // VBOs
  32522. this._geometry._bind(effect, indexToBind);
  32523. return this;
  32524. };
  32525. /** @hidden */
  32526. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32527. if (alternate === void 0) { alternate = false; }
  32528. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32529. return this;
  32530. }
  32531. if (this._onBeforeDrawObservable) {
  32532. this._onBeforeDrawObservable.notifyObservers(this);
  32533. }
  32534. var scene = this.getScene();
  32535. var engine = scene.getEngine();
  32536. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32537. // or triangles as points
  32538. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32539. }
  32540. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32541. // Triangles as wireframe
  32542. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32543. }
  32544. else {
  32545. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32546. }
  32547. if (scene._isAlternateRenderingEnabled && !alternate) {
  32548. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32549. if (!effect || !scene.activeCamera) {
  32550. return this;
  32551. }
  32552. scene._switchToAlternateCameraConfiguration(true);
  32553. this._effectiveMaterial.bindView(effect);
  32554. this._effectiveMaterial.bindViewProjection(effect);
  32555. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32556. this._draw(subMesh, fillMode, instancesCount, true);
  32557. engine.setViewport(scene.activeCamera.viewport);
  32558. scene._switchToAlternateCameraConfiguration(false);
  32559. this._effectiveMaterial.bindView(effect);
  32560. this._effectiveMaterial.bindViewProjection(effect);
  32561. }
  32562. return this;
  32563. };
  32564. /**
  32565. * Registers for this mesh a javascript function called just before the rendering process
  32566. * @param func defines the function to call before rendering this mesh
  32567. * @returns the current mesh
  32568. */
  32569. Mesh.prototype.registerBeforeRender = function (func) {
  32570. this.onBeforeRenderObservable.add(func);
  32571. return this;
  32572. };
  32573. /**
  32574. * Disposes a previously registered javascript function called before the rendering
  32575. * @param func defines the function to remove
  32576. * @returns the current mesh
  32577. */
  32578. Mesh.prototype.unregisterBeforeRender = function (func) {
  32579. this.onBeforeRenderObservable.removeCallback(func);
  32580. return this;
  32581. };
  32582. /**
  32583. * Registers for this mesh a javascript function called just after the rendering is complete
  32584. * @param func defines the function to call after rendering this mesh
  32585. * @returns the current mesh
  32586. */
  32587. Mesh.prototype.registerAfterRender = function (func) {
  32588. this.onAfterRenderObservable.add(func);
  32589. return this;
  32590. };
  32591. /**
  32592. * Disposes a previously registered javascript function called after the rendering.
  32593. * @param func defines the function to remove
  32594. * @returns the current mesh
  32595. */
  32596. Mesh.prototype.unregisterAfterRender = function (func) {
  32597. this.onAfterRenderObservable.removeCallback(func);
  32598. return this;
  32599. };
  32600. /** @hidden */
  32601. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32602. var scene = this.getScene();
  32603. var batchCache = this._instanceDataStorage.batchCache;
  32604. batchCache.mustReturn = false;
  32605. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32606. batchCache.visibleInstances[subMeshId] = null;
  32607. if (this._instanceDataStorage.visibleInstances) {
  32608. var visibleInstances = this._instanceDataStorage.visibleInstances;
  32609. var currentRenderId = scene.getRenderId();
  32610. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  32611. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  32612. var selfRenderId = this._renderId;
  32613. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32614. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  32615. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32616. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  32617. }
  32618. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  32619. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32620. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  32621. batchCache.mustReturn = true;
  32622. return batchCache;
  32623. }
  32624. if (currentRenderId !== selfRenderId) {
  32625. batchCache.renderSelf[subMeshId] = false;
  32626. }
  32627. }
  32628. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  32629. }
  32630. return batchCache;
  32631. };
  32632. /** @hidden */
  32633. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32634. var visibleInstances = batch.visibleInstances[subMesh._id];
  32635. if (!visibleInstances) {
  32636. return this;
  32637. }
  32638. var matricesCount = visibleInstances.length + 1;
  32639. var bufferSize = matricesCount * 16 * 4;
  32640. var instanceStorage = this._instanceDataStorage;
  32641. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  32642. var instancesBuffer = instanceStorage.instancesBuffer;
  32643. while (instanceStorage.instancesBufferSize < bufferSize) {
  32644. instanceStorage.instancesBufferSize *= 2;
  32645. }
  32646. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32647. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  32648. }
  32649. var offset = 0;
  32650. var instancesCount = 0;
  32651. var world = this.getWorldMatrix();
  32652. if (batch.renderSelf[subMesh._id]) {
  32653. world.copyToArray(instanceStorage.instancesData, offset);
  32654. offset += 16;
  32655. instancesCount++;
  32656. }
  32657. if (visibleInstances) {
  32658. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32659. var instance = visibleInstances[instanceIndex];
  32660. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  32661. offset += 16;
  32662. instancesCount++;
  32663. }
  32664. }
  32665. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32666. if (instancesBuffer) {
  32667. instancesBuffer.dispose();
  32668. }
  32669. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  32670. instanceStorage.instancesBuffer = instancesBuffer;
  32671. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32672. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32673. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32674. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32675. }
  32676. else {
  32677. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  32678. }
  32679. this._bind(subMesh, effect, fillMode);
  32680. this._draw(subMesh, fillMode, instancesCount);
  32681. engine.unbindInstanceAttributes();
  32682. return this;
  32683. };
  32684. /** @hidden */
  32685. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32686. var scene = this.getScene();
  32687. var engine = scene.getEngine();
  32688. if (hardwareInstancedRendering) {
  32689. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32690. }
  32691. else {
  32692. if (batch.renderSelf[subMesh._id]) {
  32693. // Draw
  32694. if (onBeforeDraw) {
  32695. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32696. }
  32697. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  32698. }
  32699. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32700. if (visibleInstancesForSubMesh) {
  32701. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32702. var instance = visibleInstancesForSubMesh[instanceIndex];
  32703. // World
  32704. var world = instance.getWorldMatrix();
  32705. if (onBeforeDraw) {
  32706. onBeforeDraw(true, world, effectiveMaterial);
  32707. }
  32708. // Draw
  32709. this._draw(subMesh, fillMode);
  32710. }
  32711. }
  32712. }
  32713. return this;
  32714. };
  32715. /**
  32716. * 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
  32717. * @param subMesh defines the subMesh to render
  32718. * @param enableAlphaMode defines if alpha mode can be changed
  32719. * @returns the current mesh
  32720. */
  32721. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32722. if (this._checkOcclusionQuery()) {
  32723. return this;
  32724. }
  32725. var scene = this.getScene();
  32726. // Managing instances
  32727. var batch = this._getInstancesRenderList(subMesh._id);
  32728. if (batch.mustReturn) {
  32729. return this;
  32730. }
  32731. // Checking geometry state
  32732. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32733. return this;
  32734. }
  32735. if (this._onBeforeRenderObservable) {
  32736. this._onBeforeRenderObservable.notifyObservers(this);
  32737. }
  32738. var engine = scene.getEngine();
  32739. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32740. // Material
  32741. var material = subMesh.getMaterial();
  32742. if (!material) {
  32743. return this;
  32744. }
  32745. this._effectiveMaterial = material;
  32746. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32747. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32748. return this;
  32749. }
  32750. }
  32751. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32752. return this;
  32753. }
  32754. // Alpha mode
  32755. if (enableAlphaMode) {
  32756. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32757. }
  32758. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32759. var step = _a[_i];
  32760. step.action(this, subMesh, batch);
  32761. }
  32762. var effect;
  32763. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32764. effect = subMesh.effect;
  32765. }
  32766. else {
  32767. effect = this._effectiveMaterial.getEffect();
  32768. }
  32769. if (!effect) {
  32770. return this;
  32771. }
  32772. var sideOrientation = this.overrideMaterialSideOrientation;
  32773. if (sideOrientation == null) {
  32774. sideOrientation = this._effectiveMaterial.sideOrientation;
  32775. if (this._getWorldMatrixDeterminant() < 0) {
  32776. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32777. }
  32778. }
  32779. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32780. if (this._effectiveMaterial.forceDepthWrite) {
  32781. engine.setDepthWrite(true);
  32782. }
  32783. // Bind
  32784. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32785. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32786. this._bind(subMesh, effect, fillMode);
  32787. }
  32788. var world = this.getWorldMatrix();
  32789. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32790. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32791. }
  32792. else {
  32793. this._effectiveMaterial.bind(world, this);
  32794. }
  32795. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32796. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32797. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32798. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32799. }
  32800. // Draw
  32801. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32802. // Unbind
  32803. this._effectiveMaterial.unbind();
  32804. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32805. var step = _c[_b];
  32806. step.action(this, subMesh, batch);
  32807. }
  32808. if (this._onAfterRenderObservable) {
  32809. this._onAfterRenderObservable.notifyObservers(this);
  32810. }
  32811. return this;
  32812. };
  32813. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32814. if (isInstance && effectiveMaterial) {
  32815. effectiveMaterial.bindOnlyWorldMatrix(world);
  32816. }
  32817. };
  32818. /**
  32819. * Normalize matrix weights so that all vertices have a total weight set to 1
  32820. */
  32821. Mesh.prototype.cleanMatrixWeights = function () {
  32822. var epsilon = 1e-3;
  32823. var noInfluenceBoneIndex = 0.0;
  32824. if (this.skeleton) {
  32825. noInfluenceBoneIndex = this.skeleton.bones.length;
  32826. }
  32827. else {
  32828. return;
  32829. }
  32830. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32831. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32832. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32833. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32834. var influencers = this.numBoneInfluencers;
  32835. var size = matricesWeights.length;
  32836. for (var i = 0; i < size; i += 4) {
  32837. var weight = 0.0;
  32838. var firstZeroWeight = -1;
  32839. for (var j = 0; j < 4; j++) {
  32840. var w = matricesWeights[i + j];
  32841. weight += w;
  32842. if (w < epsilon && firstZeroWeight < 0) {
  32843. firstZeroWeight = j;
  32844. }
  32845. }
  32846. if (matricesWeightsExtra) {
  32847. for (var j = 0; j < 4; j++) {
  32848. var w = matricesWeightsExtra[i + j];
  32849. weight += w;
  32850. if (w < epsilon && firstZeroWeight < 0) {
  32851. firstZeroWeight = j + 4;
  32852. }
  32853. }
  32854. }
  32855. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32856. firstZeroWeight = influencers - 1;
  32857. }
  32858. if (weight > epsilon) {
  32859. var mweight = 1.0 / weight;
  32860. for (var j = 0; j < 4; j++) {
  32861. matricesWeights[i + j] *= mweight;
  32862. }
  32863. if (matricesWeightsExtra) {
  32864. for (var j = 0; j < 4; j++) {
  32865. matricesWeightsExtra[i + j] *= mweight;
  32866. }
  32867. }
  32868. }
  32869. else {
  32870. if (firstZeroWeight >= 4) {
  32871. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32872. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32873. }
  32874. else {
  32875. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32876. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32877. }
  32878. }
  32879. }
  32880. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32881. if (matricesIndicesExtra) {
  32882. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32883. }
  32884. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32885. if (matricesWeightsExtra) {
  32886. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32887. }
  32888. };
  32889. /** @hidden */
  32890. Mesh.prototype._checkDelayState = function () {
  32891. var scene = this.getScene();
  32892. if (this._geometry) {
  32893. this._geometry.load(scene);
  32894. }
  32895. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32896. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32897. this._queueLoad(scene);
  32898. }
  32899. return this;
  32900. };
  32901. Mesh.prototype._queueLoad = function (scene) {
  32902. var _this = this;
  32903. scene._addPendingData(this);
  32904. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32905. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32906. if (data instanceof ArrayBuffer) {
  32907. _this._delayLoadingFunction(data, _this);
  32908. }
  32909. else {
  32910. _this._delayLoadingFunction(JSON.parse(data), _this);
  32911. }
  32912. _this.instances.forEach(function (instance) {
  32913. instance._syncSubMeshes();
  32914. });
  32915. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32916. scene._removePendingData(_this);
  32917. }, function () { }, scene.database, getBinaryData);
  32918. return this;
  32919. };
  32920. /**
  32921. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32922. * A mesh is in the frustum if its bounding box intersects the frustum
  32923. * @param frustumPlanes defines the frustum to test
  32924. * @returns true if the mesh is in the frustum planes
  32925. */
  32926. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32927. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32928. return false;
  32929. }
  32930. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32931. return false;
  32932. }
  32933. this._checkDelayState();
  32934. return true;
  32935. };
  32936. /**
  32937. * Sets the mesh material by the material or multiMaterial `id` property
  32938. * @param id is a string identifying the material or the multiMaterial
  32939. * @returns the current mesh
  32940. */
  32941. Mesh.prototype.setMaterialByID = function (id) {
  32942. var materials = this.getScene().materials;
  32943. var index;
  32944. for (index = materials.length - 1; index > -1; index--) {
  32945. if (materials[index].id === id) {
  32946. this.material = materials[index];
  32947. return this;
  32948. }
  32949. }
  32950. // Multi
  32951. var multiMaterials = this.getScene().multiMaterials;
  32952. for (index = multiMaterials.length - 1; index > -1; index--) {
  32953. if (multiMaterials[index].id === id) {
  32954. this.material = multiMaterials[index];
  32955. return this;
  32956. }
  32957. }
  32958. return this;
  32959. };
  32960. /**
  32961. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32962. * @returns an array of IAnimatable
  32963. */
  32964. Mesh.prototype.getAnimatables = function () {
  32965. var results = new Array();
  32966. if (this.material) {
  32967. results.push(this.material);
  32968. }
  32969. if (this.skeleton) {
  32970. results.push(this.skeleton);
  32971. }
  32972. return results;
  32973. };
  32974. /**
  32975. * Modifies the mesh geometry according to the passed transformation matrix.
  32976. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32977. * The mesh normals are modified using the same transformation.
  32978. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32979. * @param transform defines the transform matrix to use
  32980. * @see http://doc.babylonjs.com/resources/baking_transformations
  32981. * @returns the current mesh
  32982. */
  32983. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32984. // Position
  32985. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32986. return this;
  32987. }
  32988. var submeshes = this.subMeshes.splice(0);
  32989. this._resetPointsArrayCache();
  32990. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32991. var temp = new Array();
  32992. var index;
  32993. for (index = 0; index < data.length; index += 3) {
  32994. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32995. }
  32996. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32997. // Normals
  32998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32999. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33000. temp = [];
  33001. for (index = 0; index < data.length; index += 3) {
  33002. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33003. }
  33004. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33005. }
  33006. // flip faces?
  33007. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33008. this.flipFaces();
  33009. }
  33010. // Restore submeshes
  33011. this.releaseSubMeshes();
  33012. this.subMeshes = submeshes;
  33013. return this;
  33014. };
  33015. /**
  33016. * Modifies the mesh geometry according to its own current World Matrix.
  33017. * The mesh World Matrix is then reset.
  33018. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33019. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33020. * @see http://doc.babylonjs.com/resources/baking_transformations
  33021. * @returns the current mesh
  33022. */
  33023. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33024. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33025. this.scaling.copyFromFloats(1, 1, 1);
  33026. this.position.copyFromFloats(0, 0, 0);
  33027. this.rotation.copyFromFloats(0, 0, 0);
  33028. //only if quaternion is already set
  33029. if (this.rotationQuaternion) {
  33030. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33031. }
  33032. this._worldMatrix = BABYLON.Matrix.Identity();
  33033. return this;
  33034. };
  33035. Object.defineProperty(Mesh.prototype, "_positions", {
  33036. // Cache
  33037. /** @hidden */
  33038. get: function () {
  33039. if (this._geometry) {
  33040. return this._geometry._positions;
  33041. }
  33042. return null;
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. /** @hidden */
  33048. Mesh.prototype._resetPointsArrayCache = function () {
  33049. if (this._geometry) {
  33050. this._geometry._resetPointsArrayCache();
  33051. }
  33052. return this;
  33053. };
  33054. /** @hidden */
  33055. Mesh.prototype._generatePointsArray = function () {
  33056. if (this._geometry) {
  33057. return this._geometry._generatePointsArray();
  33058. }
  33059. return false;
  33060. };
  33061. /**
  33062. * Returns a new Mesh object generated from the current mesh properties.
  33063. * This method must not get confused with createInstance()
  33064. * @param name is a string, the name given to the new mesh
  33065. * @param newParent can be any Node object (default `null`)
  33066. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33067. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33068. * @returns a new mesh
  33069. */
  33070. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33071. if (name === void 0) { name = ""; }
  33072. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33073. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33074. };
  33075. /**
  33076. * Releases resources associated with this mesh.
  33077. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33078. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33079. */
  33080. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33081. var _this = this;
  33082. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33083. this.morphTargetManager = null;
  33084. if (this._geometry) {
  33085. this._geometry.releaseForMesh(this, true);
  33086. }
  33087. if (this._onBeforeDrawObservable) {
  33088. this._onBeforeDrawObservable.clear();
  33089. }
  33090. if (this._onBeforeRenderObservable) {
  33091. this._onBeforeRenderObservable.clear();
  33092. }
  33093. if (this._onAfterRenderObservable) {
  33094. this._onAfterRenderObservable.clear();
  33095. }
  33096. // Sources
  33097. var meshes = this.getScene().meshes;
  33098. meshes.forEach(function (abstractMesh) {
  33099. var mesh = abstractMesh;
  33100. if (mesh._source && mesh._source === _this) {
  33101. mesh._source = null;
  33102. }
  33103. });
  33104. this._source = null;
  33105. // Instances
  33106. if (this._instanceDataStorage.instancesBuffer) {
  33107. this._instanceDataStorage.instancesBuffer.dispose();
  33108. this._instanceDataStorage.instancesBuffer = null;
  33109. }
  33110. while (this.instances.length) {
  33111. this.instances[0].dispose();
  33112. }
  33113. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33114. };
  33115. /**
  33116. * Modifies the mesh geometry according to a displacement map.
  33117. * 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.
  33118. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33119. * @param url is a string, the URL from the image file is to be downloaded.
  33120. * @param minHeight is the lower limit of the displacement.
  33121. * @param maxHeight is the upper limit of the displacement.
  33122. * @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.
  33123. * @param uvOffset is an optional vector2 used to offset UV.
  33124. * @param uvScale is an optional vector2 used to scale UV.
  33125. * @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.
  33126. * @returns the Mesh.
  33127. */
  33128. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33129. var _this = this;
  33130. if (forceUpdate === void 0) { forceUpdate = false; }
  33131. var scene = this.getScene();
  33132. var onload = function (img) {
  33133. // Getting height map data
  33134. var canvas = document.createElement("canvas");
  33135. var context = canvas.getContext("2d");
  33136. var heightMapWidth = img.width;
  33137. var heightMapHeight = img.height;
  33138. canvas.width = heightMapWidth;
  33139. canvas.height = heightMapHeight;
  33140. context.drawImage(img, 0, 0);
  33141. // Create VertexData from map data
  33142. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33143. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33144. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33145. //execute success callback, if set
  33146. if (onSuccess) {
  33147. onSuccess(_this);
  33148. }
  33149. };
  33150. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33151. return this;
  33152. };
  33153. /**
  33154. * Modifies the mesh geometry according to a displacementMap buffer.
  33155. * 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.
  33156. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33157. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33158. * @param heightMapWidth is the width of the buffer image.
  33159. * @param heightMapHeight is the height of the buffer image.
  33160. * @param minHeight is the lower limit of the displacement.
  33161. * @param maxHeight is the upper limit of the displacement.
  33162. * @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.
  33163. * @param uvOffset is an optional vector2 used to offset UV.
  33164. * @param uvScale is an optional vector2 used to scale UV.
  33165. * @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.
  33166. * @returns the Mesh.
  33167. */
  33168. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33169. if (forceUpdate === void 0) { forceUpdate = false; }
  33170. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33171. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33172. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33173. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33174. return this;
  33175. }
  33176. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33177. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33178. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33179. var position = BABYLON.Vector3.Zero();
  33180. var normal = BABYLON.Vector3.Zero();
  33181. var uv = BABYLON.Vector2.Zero();
  33182. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33183. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33184. for (var index = 0; index < positions.length; index += 3) {
  33185. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33186. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33187. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33188. // Compute height
  33189. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33190. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33191. var pos = (u + v * heightMapWidth) * 4;
  33192. var r = buffer[pos] / 255.0;
  33193. var g = buffer[pos + 1] / 255.0;
  33194. var b = buffer[pos + 2] / 255.0;
  33195. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33196. normal.normalize();
  33197. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33198. position = position.add(normal);
  33199. position.toArray(positions, index);
  33200. }
  33201. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33202. if (forceUpdate) {
  33203. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33204. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33205. }
  33206. else {
  33207. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33208. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33209. }
  33210. return this;
  33211. };
  33212. /**
  33213. * Modify the mesh to get a flat shading rendering.
  33214. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33215. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33216. * @returns current mesh
  33217. */
  33218. Mesh.prototype.convertToFlatShadedMesh = function () {
  33219. var kinds = this.getVerticesDataKinds();
  33220. var vbs = {};
  33221. var data = {};
  33222. var newdata = {};
  33223. var updatableNormals = false;
  33224. var kindIndex;
  33225. var kind;
  33226. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33227. kind = kinds[kindIndex];
  33228. var vertexBuffer = this.getVertexBuffer(kind);
  33229. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33230. updatableNormals = vertexBuffer.isUpdatable();
  33231. kinds.splice(kindIndex, 1);
  33232. kindIndex--;
  33233. continue;
  33234. }
  33235. vbs[kind] = vertexBuffer;
  33236. data[kind] = vbs[kind].getData();
  33237. newdata[kind] = [];
  33238. }
  33239. // Save previous submeshes
  33240. var previousSubmeshes = this.subMeshes.slice(0);
  33241. var indices = this.getIndices();
  33242. var totalIndices = this.getTotalIndices();
  33243. // Generating unique vertices per face
  33244. var index;
  33245. for (index = 0; index < totalIndices; index++) {
  33246. var vertexIndex = indices[index];
  33247. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33248. kind = kinds[kindIndex];
  33249. var stride = vbs[kind].getStrideSize();
  33250. for (var offset = 0; offset < stride; offset++) {
  33251. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33252. }
  33253. }
  33254. }
  33255. // Updating faces & normal
  33256. var normals = [];
  33257. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33258. for (index = 0; index < totalIndices; index += 3) {
  33259. indices[index] = index;
  33260. indices[index + 1] = index + 1;
  33261. indices[index + 2] = index + 2;
  33262. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33263. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33264. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33265. var p1p2 = p1.subtract(p2);
  33266. var p3p2 = p3.subtract(p2);
  33267. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33268. // Store same normals for every vertex
  33269. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33270. normals.push(normal.x);
  33271. normals.push(normal.y);
  33272. normals.push(normal.z);
  33273. }
  33274. }
  33275. this.setIndices(indices);
  33276. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33277. // Updating vertex buffers
  33278. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33279. kind = kinds[kindIndex];
  33280. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33281. }
  33282. // Updating submeshes
  33283. this.releaseSubMeshes();
  33284. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33285. var previousOne = previousSubmeshes[submeshIndex];
  33286. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33287. }
  33288. this.synchronizeInstances();
  33289. return this;
  33290. };
  33291. /**
  33292. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33293. * In other words, more vertices, no more indices and a single bigger VBO.
  33294. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33295. * @returns current mesh
  33296. */
  33297. Mesh.prototype.convertToUnIndexedMesh = function () {
  33298. var kinds = this.getVerticesDataKinds();
  33299. var vbs = {};
  33300. var data = {};
  33301. var newdata = {};
  33302. var kindIndex;
  33303. var kind;
  33304. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33305. kind = kinds[kindIndex];
  33306. var vertexBuffer = this.getVertexBuffer(kind);
  33307. vbs[kind] = vertexBuffer;
  33308. data[kind] = vbs[kind].getData();
  33309. newdata[kind] = [];
  33310. }
  33311. // Save previous submeshes
  33312. var previousSubmeshes = this.subMeshes.slice(0);
  33313. var indices = this.getIndices();
  33314. var totalIndices = this.getTotalIndices();
  33315. // Generating unique vertices per face
  33316. var index;
  33317. for (index = 0; index < totalIndices; index++) {
  33318. var vertexIndex = indices[index];
  33319. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33320. kind = kinds[kindIndex];
  33321. var stride = vbs[kind].getStrideSize();
  33322. for (var offset = 0; offset < stride; offset++) {
  33323. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33324. }
  33325. }
  33326. }
  33327. // Updating indices
  33328. for (index = 0; index < totalIndices; index += 3) {
  33329. indices[index] = index;
  33330. indices[index + 1] = index + 1;
  33331. indices[index + 2] = index + 2;
  33332. }
  33333. this.setIndices(indices);
  33334. // Updating vertex buffers
  33335. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33336. kind = kinds[kindIndex];
  33337. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33338. }
  33339. // Updating submeshes
  33340. this.releaseSubMeshes();
  33341. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33342. var previousOne = previousSubmeshes[submeshIndex];
  33343. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33344. }
  33345. this._unIndexed = true;
  33346. this.synchronizeInstances();
  33347. return this;
  33348. };
  33349. /**
  33350. * Inverses facet orientations.
  33351. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33352. * @param flipNormals will also inverts the normals
  33353. * @returns current mesh
  33354. */
  33355. Mesh.prototype.flipFaces = function (flipNormals) {
  33356. if (flipNormals === void 0) { flipNormals = false; }
  33357. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33358. var i;
  33359. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33360. for (i = 0; i < vertex_data.normals.length; i++) {
  33361. vertex_data.normals[i] *= -1;
  33362. }
  33363. }
  33364. if (vertex_data.indices) {
  33365. var temp;
  33366. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33367. // reassign indices
  33368. temp = vertex_data.indices[i + 1];
  33369. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33370. vertex_data.indices[i + 2] = temp;
  33371. }
  33372. }
  33373. vertex_data.applyToMesh(this);
  33374. return this;
  33375. };
  33376. // Instances
  33377. /**
  33378. * Creates a new InstancedMesh object from the mesh model.
  33379. * Warning : this method is not supported for Line mesh and LineSystem
  33380. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33381. * @param name defines the name of the new instance
  33382. * @returns a new InstancedMesh
  33383. */
  33384. Mesh.prototype.createInstance = function (name) {
  33385. return new BABYLON.InstancedMesh(name, this);
  33386. };
  33387. /**
  33388. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33389. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33390. * @returns the current mesh
  33391. */
  33392. Mesh.prototype.synchronizeInstances = function () {
  33393. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33394. var instance = this.instances[instanceIndex];
  33395. instance._syncSubMeshes();
  33396. }
  33397. return this;
  33398. };
  33399. /**
  33400. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33401. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33402. * This should be used together with the simplification to avoid disappearing triangles.
  33403. * @param successCallback an optional success callback to be called after the optimization finished.
  33404. * @returns the current mesh
  33405. */
  33406. Mesh.prototype.optimizeIndices = function (successCallback) {
  33407. var _this = this;
  33408. var indices = this.getIndices();
  33409. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33410. if (!positions || !indices) {
  33411. return this;
  33412. }
  33413. var vectorPositions = new Array();
  33414. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33415. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33416. }
  33417. var dupes = new Array();
  33418. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33419. var realPos = vectorPositions.length - 1 - iteration;
  33420. var testedPosition = vectorPositions[realPos];
  33421. for (var j = 0; j < realPos; ++j) {
  33422. var againstPosition = vectorPositions[j];
  33423. if (testedPosition.equals(againstPosition)) {
  33424. dupes[realPos] = j;
  33425. break;
  33426. }
  33427. }
  33428. }, function () {
  33429. for (var i = 0; i < indices.length; ++i) {
  33430. indices[i] = dupes[indices[i]] || indices[i];
  33431. }
  33432. //indices are now reordered
  33433. var originalSubMeshes = _this.subMeshes.slice(0);
  33434. _this.setIndices(indices);
  33435. _this.subMeshes = originalSubMeshes;
  33436. if (successCallback) {
  33437. successCallback(_this);
  33438. }
  33439. });
  33440. return this;
  33441. };
  33442. /**
  33443. * Serialize current mesh
  33444. * @param serializationObject defines the object which will receive the serialization data
  33445. */
  33446. Mesh.prototype.serialize = function (serializationObject) {
  33447. serializationObject.name = this.name;
  33448. serializationObject.id = this.id;
  33449. serializationObject.type = this.getClassName();
  33450. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33451. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33452. }
  33453. serializationObject.position = this.position.asArray();
  33454. if (this.rotationQuaternion) {
  33455. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33456. }
  33457. else if (this.rotation) {
  33458. serializationObject.rotation = this.rotation.asArray();
  33459. }
  33460. serializationObject.scaling = this.scaling.asArray();
  33461. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33462. serializationObject.isEnabled = this.isEnabled(false);
  33463. serializationObject.isVisible = this.isVisible;
  33464. serializationObject.infiniteDistance = this.infiniteDistance;
  33465. serializationObject.pickable = this.isPickable;
  33466. serializationObject.receiveShadows = this.receiveShadows;
  33467. serializationObject.billboardMode = this.billboardMode;
  33468. serializationObject.visibility = this.visibility;
  33469. serializationObject.checkCollisions = this.checkCollisions;
  33470. serializationObject.isBlocker = this.isBlocker;
  33471. // Parent
  33472. if (this.parent) {
  33473. serializationObject.parentId = this.parent.id;
  33474. }
  33475. // Geometry
  33476. serializationObject.isUnIndexed = this.isUnIndexed;
  33477. var geometry = this._geometry;
  33478. if (geometry) {
  33479. var geometryId = geometry.id;
  33480. serializationObject.geometryId = geometryId;
  33481. // SubMeshes
  33482. serializationObject.subMeshes = [];
  33483. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33484. var subMesh = this.subMeshes[subIndex];
  33485. serializationObject.subMeshes.push({
  33486. materialIndex: subMesh.materialIndex,
  33487. verticesStart: subMesh.verticesStart,
  33488. verticesCount: subMesh.verticesCount,
  33489. indexStart: subMesh.indexStart,
  33490. indexCount: subMesh.indexCount
  33491. });
  33492. }
  33493. }
  33494. // Material
  33495. if (this.material) {
  33496. serializationObject.materialId = this.material.id;
  33497. }
  33498. else {
  33499. this.material = null;
  33500. }
  33501. // Morph targets
  33502. if (this.morphTargetManager) {
  33503. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33504. }
  33505. // Skeleton
  33506. if (this.skeleton) {
  33507. serializationObject.skeletonId = this.skeleton.id;
  33508. }
  33509. // Physics
  33510. //TODO implement correct serialization for physics impostors.
  33511. var impostor = this.getPhysicsImpostor();
  33512. if (impostor) {
  33513. serializationObject.physicsMass = impostor.getParam("mass");
  33514. serializationObject.physicsFriction = impostor.getParam("friction");
  33515. serializationObject.physicsRestitution = impostor.getParam("mass");
  33516. serializationObject.physicsImpostor = impostor.type;
  33517. }
  33518. // Metadata
  33519. if (this.metadata) {
  33520. serializationObject.metadata = this.metadata;
  33521. }
  33522. // Instances
  33523. serializationObject.instances = [];
  33524. for (var index = 0; index < this.instances.length; index++) {
  33525. var instance = this.instances[index];
  33526. if (instance.doNotSerialize) {
  33527. continue;
  33528. }
  33529. var serializationInstance = {
  33530. name: instance.name,
  33531. id: instance.id,
  33532. position: instance.position.asArray(),
  33533. scaling: instance.scaling.asArray()
  33534. };
  33535. if (instance.parent) {
  33536. serializationInstance.parentId = instance.parent.id;
  33537. }
  33538. if (instance.rotationQuaternion) {
  33539. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33540. }
  33541. else if (instance.rotation) {
  33542. serializationInstance.rotation = instance.rotation.asArray();
  33543. }
  33544. serializationObject.instances.push(serializationInstance);
  33545. // Animations
  33546. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33547. serializationInstance.ranges = instance.serializeAnimationRanges();
  33548. }
  33549. //
  33550. // Animations
  33551. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33552. serializationObject.ranges = this.serializeAnimationRanges();
  33553. // Layer mask
  33554. serializationObject.layerMask = this.layerMask;
  33555. // Alpha
  33556. serializationObject.alphaIndex = this.alphaIndex;
  33557. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33558. // Overlay
  33559. serializationObject.overlayAlpha = this.overlayAlpha;
  33560. serializationObject.overlayColor = this.overlayColor.asArray();
  33561. serializationObject.renderOverlay = this.renderOverlay;
  33562. // Fog
  33563. serializationObject.applyFog = this.applyFog;
  33564. // Action Manager
  33565. if (this.actionManager) {
  33566. serializationObject.actions = this.actionManager.serialize(this.name);
  33567. }
  33568. };
  33569. /** @hidden */
  33570. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33571. if (!this.geometry) {
  33572. return;
  33573. }
  33574. this._markSubMeshesAsAttributesDirty();
  33575. var morphTargetManager = this._morphTargetManager;
  33576. if (morphTargetManager && morphTargetManager.vertexCount) {
  33577. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33578. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33579. this.morphTargetManager = null;
  33580. return;
  33581. }
  33582. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33583. var morphTarget = morphTargetManager.getActiveTarget(index);
  33584. var positions = morphTarget.getPositions();
  33585. if (!positions) {
  33586. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33587. return;
  33588. }
  33589. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33590. var normals = morphTarget.getNormals();
  33591. if (normals) {
  33592. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33593. }
  33594. var tangents = morphTarget.getTangents();
  33595. if (tangents) {
  33596. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33597. }
  33598. }
  33599. }
  33600. else {
  33601. var index = 0;
  33602. // Positions
  33603. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33604. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33605. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33606. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33607. }
  33608. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33609. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33610. }
  33611. index++;
  33612. }
  33613. }
  33614. };
  33615. // Statics
  33616. /**
  33617. * Returns a new Mesh object parsed from the source provided.
  33618. * @param parsedMesh is the source
  33619. * @param scene defines the hosting scene
  33620. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33621. * @returns a new Mesh
  33622. */
  33623. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33624. var mesh;
  33625. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33626. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33627. }
  33628. else {
  33629. mesh = new Mesh(parsedMesh.name, scene);
  33630. }
  33631. mesh.id = parsedMesh.id;
  33632. if (BABYLON.Tags) {
  33633. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33634. }
  33635. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33636. if (parsedMesh.metadata !== undefined) {
  33637. mesh.metadata = parsedMesh.metadata;
  33638. }
  33639. if (parsedMesh.rotationQuaternion) {
  33640. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33641. }
  33642. else if (parsedMesh.rotation) {
  33643. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33644. }
  33645. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33646. if (parsedMesh.localMatrix) {
  33647. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33648. }
  33649. else if (parsedMesh.pivotMatrix) {
  33650. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33651. }
  33652. mesh.setEnabled(parsedMesh.isEnabled);
  33653. mesh.isVisible = parsedMesh.isVisible;
  33654. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33655. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33656. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33657. if (parsedMesh.applyFog !== undefined) {
  33658. mesh.applyFog = parsedMesh.applyFog;
  33659. }
  33660. if (parsedMesh.pickable !== undefined) {
  33661. mesh.isPickable = parsedMesh.pickable;
  33662. }
  33663. if (parsedMesh.alphaIndex !== undefined) {
  33664. mesh.alphaIndex = parsedMesh.alphaIndex;
  33665. }
  33666. mesh.receiveShadows = parsedMesh.receiveShadows;
  33667. mesh.billboardMode = parsedMesh.billboardMode;
  33668. if (parsedMesh.visibility !== undefined) {
  33669. mesh.visibility = parsedMesh.visibility;
  33670. }
  33671. mesh.checkCollisions = parsedMesh.checkCollisions;
  33672. if (parsedMesh.isBlocker !== undefined) {
  33673. mesh.isBlocker = parsedMesh.isBlocker;
  33674. }
  33675. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33676. // freezeWorldMatrix
  33677. if (parsedMesh.freezeWorldMatrix) {
  33678. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33679. }
  33680. // Parent
  33681. if (parsedMesh.parentId) {
  33682. mesh._waitingParentId = parsedMesh.parentId;
  33683. }
  33684. // Actions
  33685. if (parsedMesh.actions !== undefined) {
  33686. mesh._waitingActions = parsedMesh.actions;
  33687. }
  33688. // Overlay
  33689. if (parsedMesh.overlayAlpha !== undefined) {
  33690. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33691. }
  33692. if (parsedMesh.overlayColor !== undefined) {
  33693. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33694. }
  33695. if (parsedMesh.renderOverlay !== undefined) {
  33696. mesh.renderOverlay = parsedMesh.renderOverlay;
  33697. }
  33698. // Geometry
  33699. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33700. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33701. if (parsedMesh.delayLoadingFile) {
  33702. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33703. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33704. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33705. if (parsedMesh._binaryInfo) {
  33706. mesh._binaryInfo = parsedMesh._binaryInfo;
  33707. }
  33708. mesh._delayInfo = [];
  33709. if (parsedMesh.hasUVs) {
  33710. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33711. }
  33712. if (parsedMesh.hasUVs2) {
  33713. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33714. }
  33715. if (parsedMesh.hasUVs3) {
  33716. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33717. }
  33718. if (parsedMesh.hasUVs4) {
  33719. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33720. }
  33721. if (parsedMesh.hasUVs5) {
  33722. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33723. }
  33724. if (parsedMesh.hasUVs6) {
  33725. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33726. }
  33727. if (parsedMesh.hasColors) {
  33728. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33729. }
  33730. if (parsedMesh.hasMatricesIndices) {
  33731. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33732. }
  33733. if (parsedMesh.hasMatricesWeights) {
  33734. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33735. }
  33736. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33737. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33738. mesh._checkDelayState();
  33739. }
  33740. }
  33741. else {
  33742. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33743. }
  33744. // Material
  33745. if (parsedMesh.materialId) {
  33746. mesh.setMaterialByID(parsedMesh.materialId);
  33747. }
  33748. else {
  33749. mesh.material = null;
  33750. }
  33751. // Morph targets
  33752. if (parsedMesh.morphTargetManagerId > -1) {
  33753. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33754. }
  33755. // Skeleton
  33756. if (parsedMesh.skeletonId > -1) {
  33757. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33758. if (parsedMesh.numBoneInfluencers) {
  33759. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33760. }
  33761. }
  33762. // Animations
  33763. if (parsedMesh.animations) {
  33764. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33765. var parsedAnimation = parsedMesh.animations[animationIndex];
  33766. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33767. }
  33768. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33769. }
  33770. if (parsedMesh.autoAnimate) {
  33771. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33772. }
  33773. // Layer Mask
  33774. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33775. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33776. }
  33777. else {
  33778. mesh.layerMask = 0x0FFFFFFF;
  33779. }
  33780. // Physics
  33781. if (parsedMesh.physicsImpostor) {
  33782. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33783. mass: parsedMesh.physicsMass,
  33784. friction: parsedMesh.physicsFriction,
  33785. restitution: parsedMesh.physicsRestitution
  33786. }, scene);
  33787. }
  33788. // Instances
  33789. if (parsedMesh.instances) {
  33790. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33791. var parsedInstance = parsedMesh.instances[index];
  33792. var instance = mesh.createInstance(parsedInstance.name);
  33793. if (parsedInstance.id) {
  33794. instance.id = parsedInstance.id;
  33795. }
  33796. if (BABYLON.Tags) {
  33797. if (parsedInstance.tags) {
  33798. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33799. }
  33800. else {
  33801. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33802. }
  33803. }
  33804. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33805. if (parsedInstance.parentId) {
  33806. instance._waitingParentId = parsedInstance.parentId;
  33807. }
  33808. if (parsedInstance.rotationQuaternion) {
  33809. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33810. }
  33811. else if (parsedInstance.rotation) {
  33812. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33813. }
  33814. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33815. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33816. instance.checkCollisions = parsedInstance.checkCollisions;
  33817. }
  33818. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33819. instance.isPickable = parsedInstance.pickable;
  33820. }
  33821. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33822. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33823. }
  33824. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33825. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33826. }
  33827. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33828. instance.alphaIndex = parsedInstance.alphaIndex;
  33829. }
  33830. // Physics
  33831. if (parsedInstance.physicsImpostor) {
  33832. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33833. mass: parsedInstance.physicsMass,
  33834. friction: parsedInstance.physicsFriction,
  33835. restitution: parsedInstance.physicsRestitution
  33836. }, scene);
  33837. }
  33838. // Animation
  33839. if (parsedInstance.animations) {
  33840. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33841. parsedAnimation = parsedInstance.animations[animationIndex];
  33842. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33843. }
  33844. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33845. if (parsedInstance.autoAnimate) {
  33846. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33847. }
  33848. }
  33849. }
  33850. }
  33851. return mesh;
  33852. };
  33853. /**
  33854. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33855. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33856. * @param name defines the name of the mesh to create
  33857. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33858. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33859. * @param closePath creates a seam between the first and the last points of each path of the path array
  33860. * @param offset is taken in account only if the `pathArray` is containing a single path
  33861. * @param scene defines the hosting scene
  33862. * @param updatable defines if the mesh must be flagged as updatable
  33863. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33864. * @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)
  33865. * @returns a new Mesh
  33866. */
  33867. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33868. if (closeArray === void 0) { closeArray = false; }
  33869. if (updatable === void 0) { updatable = false; }
  33870. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33871. pathArray: pathArray,
  33872. closeArray: closeArray,
  33873. closePath: closePath,
  33874. offset: offset,
  33875. updatable: updatable,
  33876. sideOrientation: sideOrientation,
  33877. instance: instance
  33878. }, scene);
  33879. };
  33880. /**
  33881. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33882. * @param name defines the name of the mesh to create
  33883. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33884. * @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
  33885. * @param scene defines the hosting scene
  33886. * @param updatable defines if the mesh must be flagged as updatable
  33887. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33888. * @returns a new Mesh
  33889. */
  33890. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33891. if (scene === void 0) { scene = null; }
  33892. var options = {
  33893. radius: radius,
  33894. tessellation: tessellation,
  33895. sideOrientation: sideOrientation,
  33896. updatable: updatable
  33897. };
  33898. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33899. };
  33900. /**
  33901. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33902. * @param name defines the name of the mesh to create
  33903. * @param size sets the size (float) of each box side (default 1)
  33904. * @param scene defines the hosting scene
  33905. * @param updatable defines if the mesh must be flagged as updatable
  33906. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33907. * @returns a new Mesh
  33908. */
  33909. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33910. if (scene === void 0) { scene = null; }
  33911. var options = {
  33912. size: size,
  33913. sideOrientation: sideOrientation,
  33914. updatable: updatable
  33915. };
  33916. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33917. };
  33918. /**
  33919. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33920. * @param name defines the name of the mesh to create
  33921. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33922. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33923. * @param scene defines the hosting scene
  33924. * @param updatable defines if the mesh must be flagged as updatable
  33925. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33926. * @returns a new Mesh
  33927. */
  33928. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33929. var options = {
  33930. segments: segments,
  33931. diameterX: diameter,
  33932. diameterY: diameter,
  33933. diameterZ: diameter,
  33934. sideOrientation: sideOrientation,
  33935. updatable: updatable
  33936. };
  33937. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33938. };
  33939. /**
  33940. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33941. * @param name defines the name of the mesh to create
  33942. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33943. * @param diameterTop set the top cap diameter (floats, default 1)
  33944. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33945. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33946. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33947. * @param scene defines the hosting scene
  33948. * @param updatable defines if the mesh must be flagged as updatable
  33949. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33950. * @returns a new Mesh
  33951. */
  33952. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33953. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33954. if (scene !== undefined) {
  33955. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33956. updatable = scene;
  33957. }
  33958. scene = subdivisions;
  33959. subdivisions = 1;
  33960. }
  33961. var options = {
  33962. height: height,
  33963. diameterTop: diameterTop,
  33964. diameterBottom: diameterBottom,
  33965. tessellation: tessellation,
  33966. subdivisions: subdivisions,
  33967. sideOrientation: sideOrientation,
  33968. updatable: updatable
  33969. };
  33970. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33971. };
  33972. // Torus (Code from SharpDX.org)
  33973. /**
  33974. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33975. * @param name defines the name of the mesh to create
  33976. * @param diameter sets the diameter size (float) of the torus (default 1)
  33977. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33978. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33979. * @param scene defines the hosting scene
  33980. * @param updatable defines if the mesh must be flagged as updatable
  33981. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33982. * @returns a new Mesh
  33983. */
  33984. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33985. var options = {
  33986. diameter: diameter,
  33987. thickness: thickness,
  33988. tessellation: tessellation,
  33989. sideOrientation: sideOrientation,
  33990. updatable: updatable
  33991. };
  33992. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33993. };
  33994. /**
  33995. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33996. * @param name defines the name of the mesh to create
  33997. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33998. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33999. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34000. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34001. * @param p the number of windings on X axis (positive integers, default 2)
  34002. * @param q the number of windings on Y axis (positive integers, default 3)
  34003. * @param scene defines the hosting scene
  34004. * @param updatable defines if the mesh must be flagged as updatable
  34005. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34006. * @returns a new Mesh
  34007. */
  34008. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34009. var options = {
  34010. radius: radius,
  34011. tube: tube,
  34012. radialSegments: radialSegments,
  34013. tubularSegments: tubularSegments,
  34014. p: p,
  34015. q: q,
  34016. sideOrientation: sideOrientation,
  34017. updatable: updatable
  34018. };
  34019. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34020. };
  34021. /**
  34022. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34023. * @param name defines the name of the mesh to create
  34024. * @param points is an array successive Vector3
  34025. * @param scene defines the hosting scene
  34026. * @param updatable defines if the mesh must be flagged as updatable
  34027. * @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).
  34028. * @returns a new Mesh
  34029. */
  34030. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34031. if (scene === void 0) { scene = null; }
  34032. if (updatable === void 0) { updatable = false; }
  34033. if (instance === void 0) { instance = null; }
  34034. var options = {
  34035. points: points,
  34036. updatable: updatable,
  34037. instance: instance
  34038. };
  34039. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34040. };
  34041. /**
  34042. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34043. * @param name defines the name of the mesh to create
  34044. * @param points is an array successive Vector3
  34045. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34046. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34047. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34048. * @param scene defines the hosting scene
  34049. * @param updatable defines if the mesh must be flagged as updatable
  34050. * @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)
  34051. * @returns a new Mesh
  34052. */
  34053. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34054. if (scene === void 0) { scene = null; }
  34055. var options = {
  34056. points: points,
  34057. dashSize: dashSize,
  34058. gapSize: gapSize,
  34059. dashNb: dashNb,
  34060. updatable: updatable,
  34061. instance: instance
  34062. };
  34063. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34064. };
  34065. /**
  34066. * Creates a polygon mesh.
  34067. * Please consider using the same method from the MeshBuilder class instead.
  34068. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34069. * 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.
  34070. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34072. * Remember you can only change the shape positions, not their number when updating a polygon.
  34073. */
  34074. /**
  34075. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34076. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34077. * @param name defines the name of the mesh to create
  34078. * @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
  34079. * @param scene defines the hosting scene
  34080. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34081. * @param updatable defines if the mesh must be flagged as updatable
  34082. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34083. * @returns a new Mesh
  34084. */
  34085. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34086. var options = {
  34087. shape: shape,
  34088. holes: holes,
  34089. updatable: updatable,
  34090. sideOrientation: sideOrientation
  34091. };
  34092. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34093. };
  34094. /**
  34095. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34096. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34097. * @param name defines the name of the mesh to create
  34098. * @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
  34099. * @param depth defines the height of extrusion
  34100. * @param scene defines the hosting scene
  34101. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34102. * @param updatable defines if the mesh must be flagged as updatable
  34103. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34104. * @returns a new Mesh
  34105. */
  34106. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34107. var options = {
  34108. shape: shape,
  34109. holes: holes,
  34110. depth: depth,
  34111. updatable: updatable,
  34112. sideOrientation: sideOrientation
  34113. };
  34114. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34115. };
  34116. /**
  34117. * Creates an extruded shape mesh.
  34118. * 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
  34119. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34120. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34121. * @param name defines the name of the mesh to create
  34122. * @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
  34123. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34124. * @param scale is the value to scale the shape
  34125. * @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
  34126. * @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
  34127. * @param scene defines the hosting scene
  34128. * @param updatable defines if the mesh must be flagged as updatable
  34129. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34130. * @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)
  34131. * @returns a new Mesh
  34132. */
  34133. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34134. if (scene === void 0) { scene = null; }
  34135. var options = {
  34136. shape: shape,
  34137. path: path,
  34138. scale: scale,
  34139. rotation: rotation,
  34140. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34141. sideOrientation: sideOrientation,
  34142. instance: instance,
  34143. updatable: updatable
  34144. };
  34145. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34146. };
  34147. /**
  34148. * Creates an custom extruded shape mesh.
  34149. * The custom extrusion is a parametric shape.
  34150. * It has no predefined shape. Its final shape will depend on the input parameters.
  34151. * Please consider using the same method from the MeshBuilder class instead
  34152. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34153. * @param name defines the name of the mesh to create
  34154. * @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
  34155. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34156. * @param scaleFunction is a custom Javascript function called on each path point
  34157. * @param rotationFunction is a custom Javascript function called on each path point
  34158. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34159. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34160. * @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
  34161. * @param scene defines the hosting scene
  34162. * @param updatable defines if the mesh must be flagged as updatable
  34163. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34164. * @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)
  34165. * @returns a new Mesh
  34166. */
  34167. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34168. var options = {
  34169. shape: shape,
  34170. path: path,
  34171. scaleFunction: scaleFunction,
  34172. rotationFunction: rotationFunction,
  34173. ribbonCloseArray: ribbonCloseArray,
  34174. ribbonClosePath: ribbonClosePath,
  34175. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34176. sideOrientation: sideOrientation,
  34177. instance: instance,
  34178. updatable: updatable
  34179. };
  34180. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34181. };
  34182. /**
  34183. * Creates lathe mesh.
  34184. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34185. * Please consider using the same method from the MeshBuilder class instead
  34186. * @param name defines the name of the mesh to create
  34187. * @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
  34188. * @param radius is the radius value of the lathe
  34189. * @param tessellation is the side number of the lathe.
  34190. * @param scene defines the hosting scene
  34191. * @param updatable defines if the mesh must be flagged as updatable
  34192. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34193. * @returns a new Mesh
  34194. */
  34195. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34196. var options = {
  34197. shape: shape,
  34198. radius: radius,
  34199. tessellation: tessellation,
  34200. sideOrientation: sideOrientation,
  34201. updatable: updatable
  34202. };
  34203. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34204. };
  34205. /**
  34206. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34207. * @param name defines the name of the mesh to create
  34208. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34209. * @param scene defines the hosting scene
  34210. * @param updatable defines if the mesh must be flagged as updatable
  34211. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34212. * @returns a new Mesh
  34213. */
  34214. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34215. var options = {
  34216. size: size,
  34217. width: size,
  34218. height: size,
  34219. sideOrientation: sideOrientation,
  34220. updatable: updatable
  34221. };
  34222. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34223. };
  34224. /**
  34225. * Creates a ground mesh.
  34226. * Please consider using the same method from the MeshBuilder class instead
  34227. * @param name defines the name of the mesh to create
  34228. * @param width set the width of the ground
  34229. * @param height set the height of the ground
  34230. * @param subdivisions sets the number of subdivisions per side
  34231. * @param scene defines the hosting scene
  34232. * @param updatable defines if the mesh must be flagged as updatable
  34233. * @returns a new Mesh
  34234. */
  34235. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34236. var options = {
  34237. width: width,
  34238. height: height,
  34239. subdivisions: subdivisions,
  34240. updatable: updatable
  34241. };
  34242. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34243. };
  34244. /**
  34245. * Creates a tiled ground mesh.
  34246. * Please consider using the same method from the MeshBuilder class instead
  34247. * @param name defines the name of the mesh to create
  34248. * @param xmin set the ground minimum X coordinate
  34249. * @param zmin set the ground minimum Y coordinate
  34250. * @param xmax set the ground maximum X coordinate
  34251. * @param zmax set the ground maximum Z coordinate
  34252. * @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
  34253. * @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
  34254. * @param scene defines the hosting scene
  34255. * @param updatable defines if the mesh must be flagged as updatable
  34256. * @returns a new Mesh
  34257. */
  34258. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34259. var options = {
  34260. xmin: xmin,
  34261. zmin: zmin,
  34262. xmax: xmax,
  34263. zmax: zmax,
  34264. subdivisions: subdivisions,
  34265. precision: precision,
  34266. updatable: updatable
  34267. };
  34268. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34269. };
  34270. /**
  34271. * Creates a ground mesh from a height map.
  34272. * Please consider using the same method from the MeshBuilder class instead
  34273. * @see http://doc.babylonjs.com/babylon101/height_map
  34274. * @param name defines the name of the mesh to create
  34275. * @param url sets the URL of the height map image resource
  34276. * @param width set the ground width size
  34277. * @param height set the ground height size
  34278. * @param subdivisions sets the number of subdivision per side
  34279. * @param minHeight is the minimum altitude on the ground
  34280. * @param maxHeight is the maximum altitude on the ground
  34281. * @param scene defines the hosting scene
  34282. * @param updatable defines if the mesh must be flagged as updatable
  34283. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34284. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34285. * @returns a new Mesh
  34286. */
  34287. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34288. var options = {
  34289. width: width,
  34290. height: height,
  34291. subdivisions: subdivisions,
  34292. minHeight: minHeight,
  34293. maxHeight: maxHeight,
  34294. updatable: updatable,
  34295. onReady: onReady,
  34296. alphaFilter: alphaFilter
  34297. };
  34298. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34299. };
  34300. /**
  34301. * Creates a tube mesh.
  34302. * The tube is a parametric shape.
  34303. * It has no predefined shape. Its final shape will depend on the input parameters.
  34304. * Please consider using the same method from the MeshBuilder class instead
  34305. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34306. * @param name defines the name of the mesh to create
  34307. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34308. * @param radius sets the tube radius size
  34309. * @param tessellation is the number of sides on the tubular surface
  34310. * @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
  34311. * @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
  34312. * @param scene defines the hosting scene
  34313. * @param updatable defines if the mesh must be flagged as updatable
  34314. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34315. * @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)
  34316. * @returns a new Mesh
  34317. */
  34318. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34319. var options = {
  34320. path: path,
  34321. radius: radius,
  34322. tessellation: tessellation,
  34323. radiusFunction: radiusFunction,
  34324. arc: 1,
  34325. cap: cap,
  34326. updatable: updatable,
  34327. sideOrientation: sideOrientation,
  34328. instance: instance
  34329. };
  34330. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34331. };
  34332. /**
  34333. * Creates a polyhedron mesh.
  34334. * Please consider using the same method from the MeshBuilder class instead.
  34335. * * 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
  34336. * * The parameter `size` (positive float, default 1) sets the polygon size
  34337. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34338. * * 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`
  34339. * * 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
  34340. * * 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)`)
  34341. * * 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
  34342. * * 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
  34343. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34344. * * 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
  34345. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34346. * @param name defines the name of the mesh to create
  34347. * @param options defines the options used to create the mesh
  34348. * @param scene defines the hosting scene
  34349. * @returns a new Mesh
  34350. */
  34351. Mesh.CreatePolyhedron = function (name, options, scene) {
  34352. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34353. };
  34354. /**
  34355. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34356. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34357. * * 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`)
  34358. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34359. * * 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
  34360. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34361. * * 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
  34362. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34363. * @param name defines the name of the mesh
  34364. * @param options defines the options used to create the mesh
  34365. * @param scene defines the hosting scene
  34366. * @returns a new Mesh
  34367. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34368. */
  34369. Mesh.CreateIcoSphere = function (name, options, scene) {
  34370. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34371. };
  34372. /**
  34373. * Creates a decal mesh.
  34374. * Please consider using the same method from the MeshBuilder class instead.
  34375. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34376. * @param name defines the name of the mesh
  34377. * @param sourceMesh defines the mesh receiving the decal
  34378. * @param position sets the position of the decal in world coordinates
  34379. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34380. * @param size sets the decal scaling
  34381. * @param angle sets the angle to rotate the decal
  34382. * @returns a new Mesh
  34383. */
  34384. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34385. var options = {
  34386. position: position,
  34387. normal: normal,
  34388. size: size,
  34389. angle: angle
  34390. };
  34391. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34392. };
  34393. // Skeletons
  34394. /**
  34395. * Prepare internal position array for software CPU skinning
  34396. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34397. */
  34398. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34399. if (!this._sourcePositions) {
  34400. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34401. if (!source) {
  34402. return this._sourcePositions;
  34403. }
  34404. this._sourcePositions = new Float32Array(source);
  34405. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34406. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34407. }
  34408. }
  34409. return this._sourcePositions;
  34410. };
  34411. /**
  34412. * Prepare internal normal array for software CPU skinning
  34413. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34414. */
  34415. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34416. if (!this._sourceNormals) {
  34417. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34418. if (!source) {
  34419. return this._sourceNormals;
  34420. }
  34421. this._sourceNormals = new Float32Array(source);
  34422. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34423. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34424. }
  34425. }
  34426. return this._sourceNormals;
  34427. };
  34428. /**
  34429. * Updates the vertex buffer by applying transformation from the bones
  34430. * @param skeleton defines the skeleton to apply to current mesh
  34431. * @returns the current mesh
  34432. */
  34433. Mesh.prototype.applySkeleton = function (skeleton) {
  34434. if (!this.geometry) {
  34435. return this;
  34436. }
  34437. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34438. return this;
  34439. }
  34440. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34441. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34442. return this;
  34443. }
  34444. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34445. return this;
  34446. }
  34447. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34448. return this;
  34449. }
  34450. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34451. return this;
  34452. }
  34453. if (!this._sourcePositions) {
  34454. var submeshes = this.subMeshes.slice();
  34455. this.setPositionsForCPUSkinning();
  34456. this.subMeshes = submeshes;
  34457. }
  34458. if (!this._sourceNormals) {
  34459. this.setNormalsForCPUSkinning();
  34460. }
  34461. // positionsData checks for not being Float32Array will only pass at most once
  34462. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34463. if (!positionsData) {
  34464. return this;
  34465. }
  34466. if (!(positionsData instanceof Float32Array)) {
  34467. positionsData = new Float32Array(positionsData);
  34468. }
  34469. // normalsData checks for not being Float32Array will only pass at most once
  34470. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34471. if (!normalsData) {
  34472. return this;
  34473. }
  34474. if (!(normalsData instanceof Float32Array)) {
  34475. normalsData = new Float32Array(normalsData);
  34476. }
  34477. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34478. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34479. if (!matricesWeightsData || !matricesIndicesData) {
  34480. return this;
  34481. }
  34482. var needExtras = this.numBoneInfluencers > 4;
  34483. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34484. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34485. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34486. var tempVector3 = BABYLON.Vector3.Zero();
  34487. var finalMatrix = new BABYLON.Matrix();
  34488. var tempMatrix = new BABYLON.Matrix();
  34489. var matWeightIdx = 0;
  34490. var inf;
  34491. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34492. var weight;
  34493. for (inf = 0; inf < 4; inf++) {
  34494. weight = matricesWeightsData[matWeightIdx + inf];
  34495. if (weight > 0) {
  34496. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34497. finalMatrix.addToSelf(tempMatrix);
  34498. }
  34499. }
  34500. if (needExtras) {
  34501. for (inf = 0; inf < 4; inf++) {
  34502. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34503. if (weight > 0) {
  34504. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34505. finalMatrix.addToSelf(tempMatrix);
  34506. }
  34507. }
  34508. }
  34509. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34510. tempVector3.toArray(positionsData, index);
  34511. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34512. tempVector3.toArray(normalsData, index);
  34513. finalMatrix.reset();
  34514. }
  34515. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34516. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34517. return this;
  34518. };
  34519. // Tools
  34520. /**
  34521. * 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
  34522. * @param meshes defines the list of meshes to scan
  34523. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34524. */
  34525. Mesh.MinMax = function (meshes) {
  34526. var minVector = null;
  34527. var maxVector = null;
  34528. meshes.forEach(function (mesh, index, array) {
  34529. var boundingInfo = mesh.getBoundingInfo();
  34530. var boundingBox = boundingInfo.boundingBox;
  34531. if (!minVector || !maxVector) {
  34532. minVector = boundingBox.minimumWorld;
  34533. maxVector = boundingBox.maximumWorld;
  34534. }
  34535. else {
  34536. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34537. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34538. }
  34539. });
  34540. if (!minVector || !maxVector) {
  34541. return {
  34542. min: BABYLON.Vector3.Zero(),
  34543. max: BABYLON.Vector3.Zero()
  34544. };
  34545. }
  34546. return {
  34547. min: minVector,
  34548. max: maxVector
  34549. };
  34550. };
  34551. /**
  34552. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34553. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34554. * @returns a vector3
  34555. */
  34556. Mesh.Center = function (meshesOrMinMaxVector) {
  34557. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34558. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34559. };
  34560. /**
  34561. * Merge the array of meshes into a single mesh for performance reasons.
  34562. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34563. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34564. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34565. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34566. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34567. * @returns a new mesh
  34568. */
  34569. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34570. if (disposeSource === void 0) { disposeSource = true; }
  34571. var index;
  34572. if (!allow32BitsIndices) {
  34573. var totalVertices = 0;
  34574. // Counting vertices
  34575. for (index = 0; index < meshes.length; index++) {
  34576. if (meshes[index]) {
  34577. totalVertices += meshes[index].getTotalVertices();
  34578. if (totalVertices > 65536) {
  34579. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34580. return null;
  34581. }
  34582. }
  34583. }
  34584. }
  34585. // Merge
  34586. var vertexData = null;
  34587. var otherVertexData;
  34588. var indiceArray = new Array();
  34589. var source = null;
  34590. for (index = 0; index < meshes.length; index++) {
  34591. if (meshes[index]) {
  34592. var wm = meshes[index].computeWorldMatrix(true);
  34593. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34594. otherVertexData.transform(wm);
  34595. if (vertexData) {
  34596. vertexData.merge(otherVertexData, allow32BitsIndices);
  34597. }
  34598. else {
  34599. vertexData = otherVertexData;
  34600. source = meshes[index];
  34601. }
  34602. if (subdivideWithSubMeshes) {
  34603. indiceArray.push(meshes[index].getTotalIndices());
  34604. }
  34605. }
  34606. }
  34607. source = source;
  34608. if (!meshSubclass) {
  34609. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34610. }
  34611. vertexData.applyToMesh(meshSubclass);
  34612. // Setting properties
  34613. meshSubclass.material = source.material;
  34614. meshSubclass.checkCollisions = source.checkCollisions;
  34615. // Cleaning
  34616. if (disposeSource) {
  34617. for (index = 0; index < meshes.length; index++) {
  34618. if (meshes[index]) {
  34619. meshes[index].dispose();
  34620. }
  34621. }
  34622. }
  34623. // Subdivide
  34624. if (subdivideWithSubMeshes) {
  34625. //-- removal of global submesh
  34626. meshSubclass.releaseSubMeshes();
  34627. index = 0;
  34628. var offset = 0;
  34629. //-- apply subdivision according to index table
  34630. while (index < indiceArray.length) {
  34631. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34632. offset += indiceArray[index];
  34633. index++;
  34634. }
  34635. }
  34636. return meshSubclass;
  34637. };
  34638. // Consts
  34639. /**
  34640. * Mesh side orientation : usually the external or front surface
  34641. */
  34642. Mesh.FRONTSIDE = 0;
  34643. /**
  34644. * Mesh side orientation : usually the internal or back surface
  34645. */
  34646. Mesh.BACKSIDE = 1;
  34647. /**
  34648. * Mesh side orientation : both internal and external or front and back surfaces
  34649. */
  34650. Mesh.DOUBLESIDE = 2;
  34651. /**
  34652. * Mesh side orientation : by default, `FRONTSIDE`
  34653. */
  34654. Mesh.DEFAULTSIDE = 0;
  34655. /**
  34656. * Mesh cap setting : no cap
  34657. */
  34658. Mesh.NO_CAP = 0;
  34659. /**
  34660. * Mesh cap setting : one cap at the beginning of the mesh
  34661. */
  34662. Mesh.CAP_START = 1;
  34663. /**
  34664. * Mesh cap setting : one cap at the end of the mesh
  34665. */
  34666. Mesh.CAP_END = 2;
  34667. /**
  34668. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34669. */
  34670. Mesh.CAP_ALL = 3;
  34671. return Mesh;
  34672. }(BABYLON.AbstractMesh));
  34673. BABYLON.Mesh = Mesh;
  34674. })(BABYLON || (BABYLON = {}));
  34675. //# sourceMappingURL=babylon.mesh.js.map
  34676. var BABYLON;
  34677. (function (BABYLON) {
  34678. /**
  34679. * Base class for submeshes
  34680. */
  34681. var BaseSubMesh = /** @class */ (function () {
  34682. function BaseSubMesh() {
  34683. }
  34684. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34685. /**
  34686. * Gets associated effect
  34687. */
  34688. get: function () {
  34689. return this._materialEffect;
  34690. },
  34691. enumerable: true,
  34692. configurable: true
  34693. });
  34694. /**
  34695. * Sets associated effect (effect used to render this submesh)
  34696. * @param effect defines the effect to associate with
  34697. * @param defines defines the set of defines used to compile this effect
  34698. */
  34699. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34700. if (defines === void 0) { defines = null; }
  34701. if (this._materialEffect === effect) {
  34702. if (!effect) {
  34703. this._materialDefines = null;
  34704. }
  34705. return;
  34706. }
  34707. this._materialDefines = defines;
  34708. this._materialEffect = effect;
  34709. };
  34710. return BaseSubMesh;
  34711. }());
  34712. BABYLON.BaseSubMesh = BaseSubMesh;
  34713. /**
  34714. * Defines a subdivision inside a mesh
  34715. */
  34716. var SubMesh = /** @class */ (function (_super) {
  34717. __extends(SubMesh, _super);
  34718. /**
  34719. * Creates a new submesh
  34720. * @param materialIndex defines the material index to use
  34721. * @param verticesStart defines vertex index start
  34722. * @param verticesCount defines vertices count
  34723. * @param indexStart defines index start
  34724. * @param indexCount defines indices count
  34725. * @param mesh defines the parent mesh
  34726. * @param renderingMesh defines an optional rendering mesh
  34727. * @param createBoundingBox defines if bounding box should be created for this submesh
  34728. */
  34729. function SubMesh(
  34730. /** the material index to use */
  34731. materialIndex,
  34732. /** vertex index start */
  34733. verticesStart,
  34734. /** vertices count */
  34735. verticesCount,
  34736. /** index start */
  34737. indexStart,
  34738. /** indices count */
  34739. indexCount, mesh, renderingMesh, createBoundingBox) {
  34740. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34741. var _this = _super.call(this) || this;
  34742. _this.materialIndex = materialIndex;
  34743. _this.verticesStart = verticesStart;
  34744. _this.verticesCount = verticesCount;
  34745. _this.indexStart = indexStart;
  34746. _this.indexCount = indexCount;
  34747. /** @hidden */
  34748. _this._renderId = 0;
  34749. _this._mesh = mesh;
  34750. _this._renderingMesh = renderingMesh || mesh;
  34751. mesh.subMeshes.push(_this);
  34752. _this._trianglePlanes = [];
  34753. _this._id = mesh.subMeshes.length - 1;
  34754. if (createBoundingBox) {
  34755. _this.refreshBoundingInfo();
  34756. mesh.computeWorldMatrix(true);
  34757. }
  34758. return _this;
  34759. }
  34760. /**
  34761. * Add a new submesh to a mesh
  34762. * @param materialIndex defines the material index to use
  34763. * @param verticesStart defines vertex index start
  34764. * @param verticesCount defines vertices count
  34765. * @param indexStart defines index start
  34766. * @param indexCount defines indices count
  34767. * @param mesh defines the parent mesh
  34768. * @param renderingMesh defines an optional rendering mesh
  34769. * @param createBoundingBox defines if bounding box should be created for this submesh
  34770. * @returns the new submesh
  34771. */
  34772. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34773. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34774. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34775. };
  34776. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34777. /**
  34778. * Returns true if this submesh covers the entire parent mesh
  34779. * @ignorenaming
  34780. */
  34781. get: function () {
  34782. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. /**
  34788. * Returns the submesh BoudingInfo object
  34789. * @returns current bounding info (or mesh's one if the submesh is global)
  34790. */
  34791. SubMesh.prototype.getBoundingInfo = function () {
  34792. if (this.IsGlobal) {
  34793. return this._mesh.getBoundingInfo();
  34794. }
  34795. return this._boundingInfo;
  34796. };
  34797. /**
  34798. * Sets the submesh BoundingInfo
  34799. * @param boundingInfo defines the new bounding info to use
  34800. * @returns the SubMesh
  34801. */
  34802. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34803. this._boundingInfo = boundingInfo;
  34804. return this;
  34805. };
  34806. /**
  34807. * Returns the mesh of the current submesh
  34808. * @return the parent mesh
  34809. */
  34810. SubMesh.prototype.getMesh = function () {
  34811. return this._mesh;
  34812. };
  34813. /**
  34814. * Returns the rendering mesh of the submesh
  34815. * @returns the rendering mesh (could be different from parent mesh)
  34816. */
  34817. SubMesh.prototype.getRenderingMesh = function () {
  34818. return this._renderingMesh;
  34819. };
  34820. /**
  34821. * Returns the submesh material
  34822. * @returns null or the current material
  34823. */
  34824. SubMesh.prototype.getMaterial = function () {
  34825. var rootMaterial = this._renderingMesh.material;
  34826. if (rootMaterial === null || rootMaterial === undefined) {
  34827. return this._mesh.getScene().defaultMaterial;
  34828. }
  34829. else if (rootMaterial.getSubMaterial) {
  34830. var multiMaterial = rootMaterial;
  34831. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34832. if (this._currentMaterial !== effectiveMaterial) {
  34833. this._currentMaterial = effectiveMaterial;
  34834. this._materialDefines = null;
  34835. }
  34836. return effectiveMaterial;
  34837. }
  34838. return rootMaterial;
  34839. };
  34840. // Methods
  34841. /**
  34842. * Sets a new updated BoundingInfo object to the submesh
  34843. * @returns the SubMesh
  34844. */
  34845. SubMesh.prototype.refreshBoundingInfo = function () {
  34846. this._lastColliderWorldVertices = null;
  34847. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34848. return this;
  34849. }
  34850. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34851. if (!data) {
  34852. this._boundingInfo = this._mesh.getBoundingInfo();
  34853. return this;
  34854. }
  34855. var indices = this._renderingMesh.getIndices();
  34856. var extend;
  34857. //is this the only submesh?
  34858. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34859. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34860. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34861. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34862. }
  34863. else {
  34864. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34865. }
  34866. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34867. return this;
  34868. };
  34869. /** @hidden */
  34870. SubMesh.prototype._checkCollision = function (collider) {
  34871. var boundingInfo = this.getBoundingInfo();
  34872. return boundingInfo._checkCollision(collider);
  34873. };
  34874. /**
  34875. * Updates the submesh BoundingInfo
  34876. * @param world defines the world matrix to use to update the bounding info
  34877. * @returns the submesh
  34878. */
  34879. SubMesh.prototype.updateBoundingInfo = function (world) {
  34880. var boundingInfo = this.getBoundingInfo();
  34881. if (!boundingInfo) {
  34882. this.refreshBoundingInfo();
  34883. boundingInfo = this.getBoundingInfo();
  34884. }
  34885. boundingInfo.update(world);
  34886. return this;
  34887. };
  34888. /**
  34889. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34890. * @param frustumPlanes defines the frustum planes
  34891. * @returns true if the submesh is intersecting with the frustum
  34892. */
  34893. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34894. var boundingInfo = this.getBoundingInfo();
  34895. if (!boundingInfo) {
  34896. return false;
  34897. }
  34898. return boundingInfo.isInFrustum(frustumPlanes);
  34899. };
  34900. /**
  34901. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  34902. * @param frustumPlanes defines the frustum planes
  34903. * @returns true if the submesh is inside the frustum
  34904. */
  34905. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34906. var boundingInfo = this.getBoundingInfo();
  34907. if (!boundingInfo) {
  34908. return false;
  34909. }
  34910. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34911. };
  34912. /**
  34913. * Renders the submesh
  34914. * @param enableAlphaMode defines if alpha needs to be used
  34915. * @returns the submesh
  34916. */
  34917. SubMesh.prototype.render = function (enableAlphaMode) {
  34918. this._renderingMesh.render(this, enableAlphaMode);
  34919. return this;
  34920. };
  34921. /**
  34922. * @hidden
  34923. */
  34924. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  34925. if (!this._linesIndexBuffer) {
  34926. var linesIndices = [];
  34927. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34928. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34929. }
  34930. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34931. this._linesIndexCount = linesIndices.length;
  34932. }
  34933. return this._linesIndexBuffer;
  34934. };
  34935. /**
  34936. * Checks if the submesh intersects with a ray
  34937. * @param ray defines the ray to test
  34938. * @returns true is the passed ray intersects the submesh bounding box
  34939. */
  34940. SubMesh.prototype.canIntersects = function (ray) {
  34941. var boundingInfo = this.getBoundingInfo();
  34942. if (!boundingInfo) {
  34943. return false;
  34944. }
  34945. return ray.intersectsBox(boundingInfo.boundingBox);
  34946. };
  34947. /**
  34948. * Intersects current submesh with a ray
  34949. * @param ray defines the ray to test
  34950. * @param positions defines mesh's positions array
  34951. * @param indices defines mesh's indices array
  34952. * @param fastCheck defines if only bounding info should be used
  34953. * @returns intersection info or null if no intersection
  34954. */
  34955. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34956. var intersectInfo = null;
  34957. var material = this.getMaterial();
  34958. if (!material) {
  34959. return null;
  34960. }
  34961. switch (material.fillMode) {
  34962. case BABYLON.Material.PointListDrawMode:
  34963. case BABYLON.Material.LineListDrawMode:
  34964. case BABYLON.Material.LineLoopDrawMode:
  34965. case BABYLON.Material.LineStripDrawMode:
  34966. case BABYLON.Material.TriangleFanDrawMode:
  34967. case BABYLON.Material.TriangleStripDrawMode:
  34968. return null;
  34969. }
  34970. // LineMesh first as it's also a Mesh...
  34971. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34972. var lineMesh = this._mesh;
  34973. // Line test
  34974. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34975. var p0 = positions[indices[index]];
  34976. var p1 = positions[indices[index + 1]];
  34977. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34978. if (length < 0) {
  34979. continue;
  34980. }
  34981. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34982. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34983. if (fastCheck) {
  34984. break;
  34985. }
  34986. }
  34987. }
  34988. }
  34989. else {
  34990. // Triangles test
  34991. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34992. var p0 = positions[indices[index]];
  34993. var p1 = positions[indices[index + 1]];
  34994. var p2 = positions[indices[index + 2]];
  34995. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34996. if (currentIntersectInfo) {
  34997. if (currentIntersectInfo.distance < 0) {
  34998. continue;
  34999. }
  35000. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35001. intersectInfo = currentIntersectInfo;
  35002. intersectInfo.faceId = index / 3;
  35003. if (fastCheck) {
  35004. break;
  35005. }
  35006. }
  35007. }
  35008. }
  35009. }
  35010. return intersectInfo;
  35011. };
  35012. /** @hidden */
  35013. SubMesh.prototype._rebuild = function () {
  35014. if (this._linesIndexBuffer) {
  35015. this._linesIndexBuffer = null;
  35016. }
  35017. };
  35018. // Clone
  35019. /**
  35020. * Creates a new submesh from the passed mesh
  35021. * @param newMesh defines the new hosting mesh
  35022. * @param newRenderingMesh defines an optional rendering mesh
  35023. * @returns the new submesh
  35024. */
  35025. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35026. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35027. if (!this.IsGlobal) {
  35028. var boundingInfo = this.getBoundingInfo();
  35029. if (!boundingInfo) {
  35030. return result;
  35031. }
  35032. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35033. }
  35034. return result;
  35035. };
  35036. // Dispose
  35037. /**
  35038. * Release associated resources
  35039. */
  35040. SubMesh.prototype.dispose = function () {
  35041. if (this._linesIndexBuffer) {
  35042. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35043. this._linesIndexBuffer = null;
  35044. }
  35045. // Remove from mesh
  35046. var index = this._mesh.subMeshes.indexOf(this);
  35047. this._mesh.subMeshes.splice(index, 1);
  35048. };
  35049. // Statics
  35050. /**
  35051. * Creates a new submesh from indices data
  35052. * @param materialIndex the index of the main mesh material
  35053. * @param startIndex the index where to start the copy in the mesh indices array
  35054. * @param indexCount the number of indices to copy then from the startIndex
  35055. * @param mesh the main mesh to create the submesh from
  35056. * @param renderingMesh the optional rendering mesh
  35057. * @returns a new submesh
  35058. */
  35059. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35060. var minVertexIndex = Number.MAX_VALUE;
  35061. var maxVertexIndex = -Number.MAX_VALUE;
  35062. renderingMesh = (renderingMesh || mesh);
  35063. var indices = renderingMesh.getIndices();
  35064. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35065. var vertexIndex = indices[index];
  35066. if (vertexIndex < minVertexIndex)
  35067. minVertexIndex = vertexIndex;
  35068. if (vertexIndex > maxVertexIndex)
  35069. maxVertexIndex = vertexIndex;
  35070. }
  35071. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35072. };
  35073. return SubMesh;
  35074. }(BaseSubMesh));
  35075. BABYLON.SubMesh = SubMesh;
  35076. })(BABYLON || (BABYLON = {}));
  35077. //# sourceMappingURL=babylon.subMesh.js.map
  35078. var __assign = (this && this.__assign) || function () {
  35079. __assign = Object.assign || function(t) {
  35080. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35081. s = arguments[i];
  35082. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35083. t[p] = s[p];
  35084. }
  35085. return t;
  35086. };
  35087. return __assign.apply(this, arguments);
  35088. };
  35089. var BABYLON;
  35090. (function (BABYLON) {
  35091. /**
  35092. * Manages the defines for the Material
  35093. */
  35094. var MaterialDefines = /** @class */ (function () {
  35095. function MaterialDefines() {
  35096. this._isDirty = true;
  35097. /** @hidden */
  35098. this._areLightsDirty = true;
  35099. /** @hidden */
  35100. this._areAttributesDirty = true;
  35101. /** @hidden */
  35102. this._areTexturesDirty = true;
  35103. /** @hidden */
  35104. this._areFresnelDirty = true;
  35105. /** @hidden */
  35106. this._areMiscDirty = true;
  35107. /** @hidden */
  35108. this._areImageProcessingDirty = true;
  35109. /** @hidden */
  35110. this._normals = false;
  35111. /** @hidden */
  35112. this._uvs = false;
  35113. /** @hidden */
  35114. this._needNormals = false;
  35115. /** @hidden */
  35116. this._needUVs = false;
  35117. }
  35118. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35119. /**
  35120. * Specifies if the material needs to be re-calculated
  35121. */
  35122. get: function () {
  35123. return this._isDirty;
  35124. },
  35125. enumerable: true,
  35126. configurable: true
  35127. });
  35128. /**
  35129. * Marks the material to indicate that it has been re-calculated
  35130. */
  35131. MaterialDefines.prototype.markAsProcessed = function () {
  35132. this._isDirty = false;
  35133. this._areAttributesDirty = false;
  35134. this._areTexturesDirty = false;
  35135. this._areFresnelDirty = false;
  35136. this._areLightsDirty = false;
  35137. this._areMiscDirty = false;
  35138. this._areImageProcessingDirty = false;
  35139. };
  35140. /**
  35141. * Marks the material to indicate that it needs to be re-calculated
  35142. */
  35143. MaterialDefines.prototype.markAsUnprocessed = function () {
  35144. this._isDirty = true;
  35145. };
  35146. /**
  35147. * Marks the material to indicate all of its defines need to be re-calculated
  35148. */
  35149. MaterialDefines.prototype.markAllAsDirty = function () {
  35150. this._areTexturesDirty = true;
  35151. this._areAttributesDirty = true;
  35152. this._areLightsDirty = true;
  35153. this._areFresnelDirty = true;
  35154. this._areMiscDirty = true;
  35155. this._areImageProcessingDirty = true;
  35156. this._isDirty = true;
  35157. };
  35158. /**
  35159. * Marks the material to indicate that image processing needs to be re-calculated
  35160. */
  35161. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35162. this._areImageProcessingDirty = true;
  35163. this._isDirty = true;
  35164. };
  35165. /**
  35166. * Marks the material to indicate the lights need to be re-calculated
  35167. */
  35168. MaterialDefines.prototype.markAsLightDirty = function () {
  35169. this._areLightsDirty = true;
  35170. this._isDirty = true;
  35171. };
  35172. /**
  35173. * Marks the attribute state as changed
  35174. */
  35175. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35176. this._areAttributesDirty = true;
  35177. this._isDirty = true;
  35178. };
  35179. /**
  35180. * Marks the texture state as changed
  35181. */
  35182. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35183. this._areTexturesDirty = true;
  35184. this._isDirty = true;
  35185. };
  35186. /**
  35187. * Marks the fresnel state as changed
  35188. */
  35189. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35190. this._areFresnelDirty = true;
  35191. this._isDirty = true;
  35192. };
  35193. /**
  35194. * Marks the misc state as changed
  35195. */
  35196. MaterialDefines.prototype.markAsMiscDirty = function () {
  35197. this._areMiscDirty = true;
  35198. this._isDirty = true;
  35199. };
  35200. /**
  35201. * Rebuilds the material defines
  35202. */
  35203. MaterialDefines.prototype.rebuild = function () {
  35204. if (this._keys) {
  35205. delete this._keys;
  35206. }
  35207. this._keys = [];
  35208. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35209. var key = _a[_i];
  35210. if (key[0] === "_") {
  35211. continue;
  35212. }
  35213. this._keys.push(key);
  35214. }
  35215. };
  35216. /**
  35217. * Specifies if two material defines are equal
  35218. * @param other - A material define instance to compare to
  35219. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35220. */
  35221. MaterialDefines.prototype.isEqual = function (other) {
  35222. if (this._keys.length !== other._keys.length) {
  35223. return false;
  35224. }
  35225. for (var index = 0; index < this._keys.length; index++) {
  35226. var prop = this._keys[index];
  35227. if (this[prop] !== other[prop]) {
  35228. return false;
  35229. }
  35230. }
  35231. return true;
  35232. };
  35233. /**
  35234. * Clones this instance's defines to another instance
  35235. * @param other - material defines to clone values to
  35236. */
  35237. MaterialDefines.prototype.cloneTo = function (other) {
  35238. if (this._keys.length !== other._keys.length) {
  35239. other._keys = this._keys.slice(0);
  35240. }
  35241. for (var index = 0; index < this._keys.length; index++) {
  35242. var prop = this._keys[index];
  35243. other[prop] = this[prop];
  35244. }
  35245. };
  35246. /**
  35247. * Resets the material define values
  35248. */
  35249. MaterialDefines.prototype.reset = function () {
  35250. for (var index = 0; index < this._keys.length; index++) {
  35251. var prop = this._keys[index];
  35252. var type = typeof this[prop];
  35253. switch (type) {
  35254. case "number":
  35255. this[prop] = 0;
  35256. break;
  35257. case "string":
  35258. this[prop] = "";
  35259. break;
  35260. default:
  35261. this[prop] = false;
  35262. break;
  35263. }
  35264. }
  35265. };
  35266. /**
  35267. * Converts the material define values to a string
  35268. * @returns - String of material define information
  35269. */
  35270. MaterialDefines.prototype.toString = function () {
  35271. var result = "";
  35272. for (var index = 0; index < this._keys.length; index++) {
  35273. var prop = this._keys[index];
  35274. var value = this[prop];
  35275. var type = typeof value;
  35276. switch (type) {
  35277. case "number":
  35278. case "string":
  35279. result += "#define " + prop + " " + value + "\n";
  35280. break;
  35281. default:
  35282. if (value) {
  35283. result += "#define " + prop + "\n";
  35284. }
  35285. break;
  35286. }
  35287. }
  35288. return result;
  35289. };
  35290. return MaterialDefines;
  35291. }());
  35292. BABYLON.MaterialDefines = MaterialDefines;
  35293. /**
  35294. * Base class for the main features of a material in Babylon.js
  35295. */
  35296. var Material = /** @class */ (function () {
  35297. /**
  35298. * Creates a material instance
  35299. * @param name defines the name of the material
  35300. * @param scene defines the scene to reference
  35301. * @param doNotAdd specifies if the material should be added to the scene
  35302. */
  35303. function Material(name, scene, doNotAdd) {
  35304. /**
  35305. * Specifies if the ready state should be checked on each call
  35306. */
  35307. this.checkReadyOnEveryCall = false;
  35308. /**
  35309. * Specifies if the ready state should be checked once
  35310. */
  35311. this.checkReadyOnlyOnce = false;
  35312. /**
  35313. * The state of the material
  35314. */
  35315. this.state = "";
  35316. /**
  35317. * The alpha value of the material
  35318. */
  35319. this._alpha = 1.0;
  35320. /**
  35321. * Specifies if back face culling is enabled
  35322. */
  35323. this._backFaceCulling = true;
  35324. /**
  35325. * Specifies if the material should be serialized
  35326. */
  35327. this.doNotSerialize = false;
  35328. /**
  35329. * Specifies if the effect should be stored on sub meshes
  35330. */
  35331. this.storeEffectOnSubMeshes = false;
  35332. /**
  35333. * An event triggered when the material is disposed
  35334. */
  35335. this.onDisposeObservable = new BABYLON.Observable();
  35336. /**
  35337. * Stores the value of the alpha mode
  35338. */
  35339. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35340. /**
  35341. * Stores the state of the need depth pre-pass value
  35342. */
  35343. this._needDepthPrePass = false;
  35344. /**
  35345. * Specifies if depth writing should be disabled
  35346. */
  35347. this.disableDepthWrite = false;
  35348. /**
  35349. * Specifies if depth writing should be forced
  35350. */
  35351. this.forceDepthWrite = false;
  35352. /**
  35353. * Specifies if there should be a separate pass for culling
  35354. */
  35355. this.separateCullingPass = false;
  35356. /**
  35357. * Stores the state specifing if fog should be enabled
  35358. */
  35359. this._fogEnabled = true;
  35360. /**
  35361. * Stores the size of points
  35362. */
  35363. this.pointSize = 1.0;
  35364. /**
  35365. * Stores the z offset value
  35366. */
  35367. this.zOffset = 0;
  35368. /**
  35369. * @hidden
  35370. * Specifies if the material was previously ready
  35371. */
  35372. this._wasPreviouslyReady = false;
  35373. /**
  35374. * Stores the fill mode state
  35375. */
  35376. this._fillMode = Material.TriangleFillMode;
  35377. this.name = name;
  35378. this.id = name || BABYLON.Tools.RandomId();
  35379. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35380. this.uniqueId = this._scene.getUniqueId();
  35381. if (this._scene.useRightHandedSystem) {
  35382. this.sideOrientation = Material.ClockWiseSideOrientation;
  35383. }
  35384. else {
  35385. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35386. }
  35387. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35388. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35389. if (!doNotAdd) {
  35390. this._scene.materials.push(this);
  35391. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35392. }
  35393. }
  35394. Object.defineProperty(Material, "TriangleFillMode", {
  35395. /**
  35396. * Returns the triangle fill mode
  35397. */
  35398. get: function () {
  35399. return Material._TriangleFillMode;
  35400. },
  35401. enumerable: true,
  35402. configurable: true
  35403. });
  35404. Object.defineProperty(Material, "WireFrameFillMode", {
  35405. /**
  35406. * Returns the wireframe mode
  35407. */
  35408. get: function () {
  35409. return Material._WireFrameFillMode;
  35410. },
  35411. enumerable: true,
  35412. configurable: true
  35413. });
  35414. Object.defineProperty(Material, "PointFillMode", {
  35415. /**
  35416. * Returns the point fill mode
  35417. */
  35418. get: function () {
  35419. return Material._PointFillMode;
  35420. },
  35421. enumerable: true,
  35422. configurable: true
  35423. });
  35424. Object.defineProperty(Material, "PointListDrawMode", {
  35425. /**
  35426. * Returns the point list draw mode
  35427. */
  35428. get: function () {
  35429. return Material._PointListDrawMode;
  35430. },
  35431. enumerable: true,
  35432. configurable: true
  35433. });
  35434. Object.defineProperty(Material, "LineListDrawMode", {
  35435. /**
  35436. * Returns the line list draw mode
  35437. */
  35438. get: function () {
  35439. return Material._LineListDrawMode;
  35440. },
  35441. enumerable: true,
  35442. configurable: true
  35443. });
  35444. Object.defineProperty(Material, "LineLoopDrawMode", {
  35445. /**
  35446. * Returns the line loop draw mode
  35447. */
  35448. get: function () {
  35449. return Material._LineLoopDrawMode;
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(Material, "LineStripDrawMode", {
  35455. /**
  35456. * Returns the line strip draw mode
  35457. */
  35458. get: function () {
  35459. return Material._LineStripDrawMode;
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35465. /**
  35466. * Returns the triangle strip draw mode
  35467. */
  35468. get: function () {
  35469. return Material._TriangleStripDrawMode;
  35470. },
  35471. enumerable: true,
  35472. configurable: true
  35473. });
  35474. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35475. /**
  35476. * Returns the triangle fan draw mode
  35477. */
  35478. get: function () {
  35479. return Material._TriangleFanDrawMode;
  35480. },
  35481. enumerable: true,
  35482. configurable: true
  35483. });
  35484. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35485. /**
  35486. * Returns the clock-wise side orientation
  35487. */
  35488. get: function () {
  35489. return Material._ClockWiseSideOrientation;
  35490. },
  35491. enumerable: true,
  35492. configurable: true
  35493. });
  35494. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35495. /**
  35496. * Returns the counter clock-wise side orientation
  35497. */
  35498. get: function () {
  35499. return Material._CounterClockWiseSideOrientation;
  35500. },
  35501. enumerable: true,
  35502. configurable: true
  35503. });
  35504. Object.defineProperty(Material.prototype, "alpha", {
  35505. /**
  35506. * Gets the alpha value of the material
  35507. */
  35508. get: function () {
  35509. return this._alpha;
  35510. },
  35511. /**
  35512. * Sets the alpha value of the material
  35513. */
  35514. set: function (value) {
  35515. if (this._alpha === value) {
  35516. return;
  35517. }
  35518. this._alpha = value;
  35519. this.markAsDirty(Material.MiscDirtyFlag);
  35520. },
  35521. enumerable: true,
  35522. configurable: true
  35523. });
  35524. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35525. /**
  35526. * Gets the back-face culling state
  35527. */
  35528. get: function () {
  35529. return this._backFaceCulling;
  35530. },
  35531. /**
  35532. * Sets the back-face culling state
  35533. */
  35534. set: function (value) {
  35535. if (this._backFaceCulling === value) {
  35536. return;
  35537. }
  35538. this._backFaceCulling = value;
  35539. this.markAsDirty(Material.TextureDirtyFlag);
  35540. },
  35541. enumerable: true,
  35542. configurable: true
  35543. });
  35544. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35545. /**
  35546. * Gets a boolean indicating that current material needs to register RTT
  35547. */
  35548. get: function () {
  35549. return false;
  35550. },
  35551. enumerable: true,
  35552. configurable: true
  35553. });
  35554. Object.defineProperty(Material.prototype, "onDispose", {
  35555. /**
  35556. * Called during a dispose event
  35557. */
  35558. set: function (callback) {
  35559. if (this._onDisposeObserver) {
  35560. this.onDisposeObservable.remove(this._onDisposeObserver);
  35561. }
  35562. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35563. },
  35564. enumerable: true,
  35565. configurable: true
  35566. });
  35567. Object.defineProperty(Material.prototype, "onBindObservable", {
  35568. /**
  35569. * An event triggered when the material is bound
  35570. */
  35571. get: function () {
  35572. if (!this._onBindObservable) {
  35573. this._onBindObservable = new BABYLON.Observable();
  35574. }
  35575. return this._onBindObservable;
  35576. },
  35577. enumerable: true,
  35578. configurable: true
  35579. });
  35580. Object.defineProperty(Material.prototype, "onBind", {
  35581. /**
  35582. * Called during a bind event
  35583. */
  35584. set: function (callback) {
  35585. if (this._onBindObserver) {
  35586. this.onBindObservable.remove(this._onBindObserver);
  35587. }
  35588. this._onBindObserver = this.onBindObservable.add(callback);
  35589. },
  35590. enumerable: true,
  35591. configurable: true
  35592. });
  35593. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35594. /**
  35595. * An event triggered when the material is unbound
  35596. */
  35597. get: function () {
  35598. if (!this._onUnBindObservable) {
  35599. this._onUnBindObservable = new BABYLON.Observable();
  35600. }
  35601. return this._onUnBindObservable;
  35602. },
  35603. enumerable: true,
  35604. configurable: true
  35605. });
  35606. Object.defineProperty(Material.prototype, "alphaMode", {
  35607. /**
  35608. * Gets the value of the alpha mode
  35609. */
  35610. get: function () {
  35611. return this._alphaMode;
  35612. },
  35613. /**
  35614. * Sets the value of the alpha mode.
  35615. *
  35616. * | Value | Type | Description |
  35617. * | --- | --- | --- |
  35618. * | 0 | ALPHA_DISABLE | |
  35619. * | 1 | ALPHA_ADD | |
  35620. * | 2 | ALPHA_COMBINE | |
  35621. * | 3 | ALPHA_SUBTRACT | |
  35622. * | 4 | ALPHA_MULTIPLY | |
  35623. * | 5 | ALPHA_MAXIMIZED | |
  35624. * | 6 | ALPHA_ONEONE | |
  35625. * | 7 | ALPHA_PREMULTIPLIED | |
  35626. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35627. * | 9 | ALPHA_INTERPOLATE | |
  35628. * | 10 | ALPHA_SCREENMODE | |
  35629. *
  35630. */
  35631. set: function (value) {
  35632. if (this._alphaMode === value) {
  35633. return;
  35634. }
  35635. this._alphaMode = value;
  35636. this.markAsDirty(Material.TextureDirtyFlag);
  35637. },
  35638. enumerable: true,
  35639. configurable: true
  35640. });
  35641. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35642. /**
  35643. * Gets the depth pre-pass value
  35644. */
  35645. get: function () {
  35646. return this._needDepthPrePass;
  35647. },
  35648. /**
  35649. * Sets the need depth pre-pass value
  35650. */
  35651. set: function (value) {
  35652. if (this._needDepthPrePass === value) {
  35653. return;
  35654. }
  35655. this._needDepthPrePass = value;
  35656. if (this._needDepthPrePass) {
  35657. this.checkReadyOnEveryCall = true;
  35658. }
  35659. },
  35660. enumerable: true,
  35661. configurable: true
  35662. });
  35663. Object.defineProperty(Material.prototype, "fogEnabled", {
  35664. /**
  35665. * Gets the value of the fog enabled state
  35666. */
  35667. get: function () {
  35668. return this._fogEnabled;
  35669. },
  35670. /**
  35671. * Sets the state for enabling fog
  35672. */
  35673. set: function (value) {
  35674. if (this._fogEnabled === value) {
  35675. return;
  35676. }
  35677. this._fogEnabled = value;
  35678. this.markAsDirty(Material.MiscDirtyFlag);
  35679. },
  35680. enumerable: true,
  35681. configurable: true
  35682. });
  35683. Object.defineProperty(Material.prototype, "wireframe", {
  35684. /**
  35685. * Gets a value specifying if wireframe mode is enabled
  35686. */
  35687. get: function () {
  35688. switch (this._fillMode) {
  35689. case Material.WireFrameFillMode:
  35690. case Material.LineListDrawMode:
  35691. case Material.LineLoopDrawMode:
  35692. case Material.LineStripDrawMode:
  35693. return true;
  35694. }
  35695. return this._scene.forceWireframe;
  35696. },
  35697. /**
  35698. * Sets the state of wireframe mode
  35699. */
  35700. set: function (value) {
  35701. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35702. },
  35703. enumerable: true,
  35704. configurable: true
  35705. });
  35706. Object.defineProperty(Material.prototype, "pointsCloud", {
  35707. /**
  35708. * Gets the value specifying if point clouds are enabled
  35709. */
  35710. get: function () {
  35711. switch (this._fillMode) {
  35712. case Material.PointFillMode:
  35713. case Material.PointListDrawMode:
  35714. return true;
  35715. }
  35716. return this._scene.forcePointsCloud;
  35717. },
  35718. /**
  35719. * Sets the state of point cloud mode
  35720. */
  35721. set: function (value) {
  35722. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35723. },
  35724. enumerable: true,
  35725. configurable: true
  35726. });
  35727. Object.defineProperty(Material.prototype, "fillMode", {
  35728. /**
  35729. * Gets the material fill mode
  35730. */
  35731. get: function () {
  35732. return this._fillMode;
  35733. },
  35734. /**
  35735. * Sets the material fill mode
  35736. */
  35737. set: function (value) {
  35738. if (this._fillMode === value) {
  35739. return;
  35740. }
  35741. this._fillMode = value;
  35742. this.markAsDirty(Material.MiscDirtyFlag);
  35743. },
  35744. enumerable: true,
  35745. configurable: true
  35746. });
  35747. /**
  35748. * Returns a string representation of the current material
  35749. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35750. * @returns a string with material information
  35751. */
  35752. Material.prototype.toString = function (fullDetails) {
  35753. var ret = "Name: " + this.name;
  35754. if (fullDetails) {
  35755. }
  35756. return ret;
  35757. };
  35758. /**
  35759. * Gets the class name of the material
  35760. * @returns a string with the class name of the material
  35761. */
  35762. Material.prototype.getClassName = function () {
  35763. return "Material";
  35764. };
  35765. Object.defineProperty(Material.prototype, "isFrozen", {
  35766. /**
  35767. * Specifies if updates for the material been locked
  35768. */
  35769. get: function () {
  35770. return this.checkReadyOnlyOnce;
  35771. },
  35772. enumerable: true,
  35773. configurable: true
  35774. });
  35775. /**
  35776. * Locks updates for the material
  35777. */
  35778. Material.prototype.freeze = function () {
  35779. this.checkReadyOnlyOnce = true;
  35780. };
  35781. /**
  35782. * Unlocks updates for the material
  35783. */
  35784. Material.prototype.unfreeze = function () {
  35785. this.checkReadyOnlyOnce = false;
  35786. };
  35787. /**
  35788. * Specifies if the material is ready to be used
  35789. * @param mesh defines the mesh to check
  35790. * @param useInstances specifies if instances should be used
  35791. * @returns a boolean indicating if the material is ready to be used
  35792. */
  35793. Material.prototype.isReady = function (mesh, useInstances) {
  35794. return true;
  35795. };
  35796. /**
  35797. * Specifies that the submesh is ready to be used
  35798. * @param mesh defines the mesh to check
  35799. * @param subMesh defines which submesh to check
  35800. * @param useInstances specifies that instances should be used
  35801. * @returns a boolean indicating that the submesh is ready or not
  35802. */
  35803. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35804. return false;
  35805. };
  35806. /**
  35807. * Returns the material effect
  35808. * @returns the effect associated with the material
  35809. */
  35810. Material.prototype.getEffect = function () {
  35811. return this._effect;
  35812. };
  35813. /**
  35814. * Returns the current scene
  35815. * @returns a Scene
  35816. */
  35817. Material.prototype.getScene = function () {
  35818. return this._scene;
  35819. };
  35820. /**
  35821. * Specifies if the material will require alpha blending
  35822. * @returns a boolean specifying if alpha blending is needed
  35823. */
  35824. Material.prototype.needAlphaBlending = function () {
  35825. return (this.alpha < 1.0);
  35826. };
  35827. /**
  35828. * Specifies if the mesh will require alpha blending
  35829. * @param mesh defines the mesh to check
  35830. * @returns a boolean specifying if alpha blending is needed for the mesh
  35831. */
  35832. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35833. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35834. };
  35835. /**
  35836. * Specifies if this material should be rendered in alpha test mode
  35837. * @returns a boolean specifying if an alpha test is needed.
  35838. */
  35839. Material.prototype.needAlphaTesting = function () {
  35840. return false;
  35841. };
  35842. /**
  35843. * Gets the texture used for the alpha test
  35844. * @returns the texture to use for alpha testing
  35845. */
  35846. Material.prototype.getAlphaTestTexture = function () {
  35847. return null;
  35848. };
  35849. /**
  35850. * Marks the material to indicate that it needs to be re-calculated
  35851. */
  35852. Material.prototype.markDirty = function () {
  35853. this._wasPreviouslyReady = false;
  35854. };
  35855. /** @hidden */
  35856. Material.prototype._preBind = function (effect, overrideOrientation) {
  35857. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35858. var engine = this._scene.getEngine();
  35859. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35860. var reverse = orientation === Material.ClockWiseSideOrientation;
  35861. engine.enableEffect(effect ? effect : this._effect);
  35862. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35863. return reverse;
  35864. };
  35865. /**
  35866. * Binds the material to the mesh
  35867. * @param world defines the world transformation matrix
  35868. * @param mesh defines the mesh to bind the material to
  35869. */
  35870. Material.prototype.bind = function (world, mesh) {
  35871. };
  35872. /**
  35873. * Binds the submesh to the material
  35874. * @param world defines the world transformation matrix
  35875. * @param mesh defines the mesh containing the submesh
  35876. * @param subMesh defines the submesh to bind the material to
  35877. */
  35878. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35879. };
  35880. /**
  35881. * Binds the world matrix to the material
  35882. * @param world defines the world transformation matrix
  35883. */
  35884. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35885. };
  35886. /**
  35887. * Binds the scene's uniform buffer to the effect.
  35888. * @param effect defines the effect to bind to the scene uniform buffer
  35889. * @param sceneUbo defines the uniform buffer storing scene data
  35890. */
  35891. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35892. sceneUbo.bindToEffect(effect, "Scene");
  35893. };
  35894. /**
  35895. * Binds the view matrix to the effect
  35896. * @param effect defines the effect to bind the view matrix to
  35897. */
  35898. Material.prototype.bindView = function (effect) {
  35899. if (!this._useUBO) {
  35900. effect.setMatrix("view", this.getScene().getViewMatrix());
  35901. }
  35902. else {
  35903. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35904. }
  35905. };
  35906. /**
  35907. * Binds the view projection matrix to the effect
  35908. * @param effect defines the effect to bind the view projection matrix to
  35909. */
  35910. Material.prototype.bindViewProjection = function (effect) {
  35911. if (!this._useUBO) {
  35912. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35913. }
  35914. else {
  35915. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35916. }
  35917. };
  35918. /**
  35919. * Specifies if material alpha testing should be turned on for the mesh
  35920. * @param mesh defines the mesh to check
  35921. */
  35922. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35923. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35924. };
  35925. /**
  35926. * Processes to execute after binding the material to a mesh
  35927. * @param mesh defines the rendered mesh
  35928. */
  35929. Material.prototype._afterBind = function (mesh) {
  35930. this._scene._cachedMaterial = this;
  35931. if (mesh) {
  35932. this._scene._cachedVisibility = mesh.visibility;
  35933. }
  35934. else {
  35935. this._scene._cachedVisibility = 1;
  35936. }
  35937. if (this._onBindObservable && mesh) {
  35938. this._onBindObservable.notifyObservers(mesh);
  35939. }
  35940. if (this.disableDepthWrite) {
  35941. var engine = this._scene.getEngine();
  35942. this._cachedDepthWriteState = engine.getDepthWrite();
  35943. engine.setDepthWrite(false);
  35944. }
  35945. };
  35946. /**
  35947. * Unbinds the material from the mesh
  35948. */
  35949. Material.prototype.unbind = function () {
  35950. if (this._onUnBindObservable) {
  35951. this._onUnBindObservable.notifyObservers(this);
  35952. }
  35953. if (this.disableDepthWrite) {
  35954. var engine = this._scene.getEngine();
  35955. engine.setDepthWrite(this._cachedDepthWriteState);
  35956. }
  35957. };
  35958. /**
  35959. * Gets the active textures from the material
  35960. * @returns an array of textures
  35961. */
  35962. Material.prototype.getActiveTextures = function () {
  35963. return [];
  35964. };
  35965. /**
  35966. * Specifies if the material uses a texture
  35967. * @param texture defines the texture to check against the material
  35968. * @returns a boolean specifying if the material uses the texture
  35969. */
  35970. Material.prototype.hasTexture = function (texture) {
  35971. return false;
  35972. };
  35973. /**
  35974. * Makes a duplicate of the material, and gives it a new name
  35975. * @param name defines the new name for the duplicated material
  35976. * @returns the cloned material
  35977. */
  35978. Material.prototype.clone = function (name) {
  35979. return null;
  35980. };
  35981. /**
  35982. * Gets the meshes bound to the material
  35983. * @returns an array of meshes bound to the material
  35984. */
  35985. Material.prototype.getBindedMeshes = function () {
  35986. var result = new Array();
  35987. for (var index = 0; index < this._scene.meshes.length; index++) {
  35988. var mesh = this._scene.meshes[index];
  35989. if (mesh.material === this) {
  35990. result.push(mesh);
  35991. }
  35992. }
  35993. return result;
  35994. };
  35995. /**
  35996. * Force shader compilation
  35997. * @param mesh defines the mesh associated with this material
  35998. * @param onCompiled defines a function to execute once the material is compiled
  35999. * @param options defines the options to configure the compilation
  36000. */
  36001. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36002. var _this = this;
  36003. var localOptions = __assign({ clipPlane: false }, options);
  36004. var subMesh = new BABYLON.BaseSubMesh();
  36005. var scene = this.getScene();
  36006. var checkReady = function () {
  36007. if (!_this._scene || !_this._scene.getEngine()) {
  36008. return;
  36009. }
  36010. if (subMesh._materialDefines) {
  36011. subMesh._materialDefines._renderId = -1;
  36012. }
  36013. var clipPlaneState = scene.clipPlane;
  36014. if (localOptions.clipPlane) {
  36015. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36016. }
  36017. if (_this.storeEffectOnSubMeshes) {
  36018. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36019. if (onCompiled) {
  36020. onCompiled(_this);
  36021. }
  36022. }
  36023. else {
  36024. setTimeout(checkReady, 16);
  36025. }
  36026. }
  36027. else {
  36028. if (_this.isReady(mesh)) {
  36029. if (onCompiled) {
  36030. onCompiled(_this);
  36031. }
  36032. }
  36033. else {
  36034. setTimeout(checkReady, 16);
  36035. }
  36036. }
  36037. if (localOptions.clipPlane) {
  36038. scene.clipPlane = clipPlaneState;
  36039. }
  36040. };
  36041. checkReady();
  36042. };
  36043. /**
  36044. * Force shader compilation
  36045. * @param mesh defines the mesh that will use this material
  36046. * @param options defines additional options for compiling the shaders
  36047. * @returns a promise that resolves when the compilation completes
  36048. */
  36049. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36050. var _this = this;
  36051. return new Promise(function (resolve) {
  36052. _this.forceCompilation(mesh, function () {
  36053. resolve();
  36054. }, options);
  36055. });
  36056. };
  36057. /**
  36058. * Marks a define in the material to indicate that it needs to be re-computed
  36059. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36060. */
  36061. Material.prototype.markAsDirty = function (flag) {
  36062. if (flag & Material.TextureDirtyFlag) {
  36063. this._markAllSubMeshesAsTexturesDirty();
  36064. }
  36065. if (flag & Material.LightDirtyFlag) {
  36066. this._markAllSubMeshesAsLightsDirty();
  36067. }
  36068. if (flag & Material.FresnelDirtyFlag) {
  36069. this._markAllSubMeshesAsFresnelDirty();
  36070. }
  36071. if (flag & Material.AttributesDirtyFlag) {
  36072. this._markAllSubMeshesAsAttributesDirty();
  36073. }
  36074. if (flag & Material.MiscDirtyFlag) {
  36075. this._markAllSubMeshesAsMiscDirty();
  36076. }
  36077. this.getScene().resetCachedMaterial();
  36078. };
  36079. /**
  36080. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36081. * @param func defines a function which checks material defines against the submeshes
  36082. */
  36083. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36084. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36085. var mesh = _a[_i];
  36086. if (!mesh.subMeshes) {
  36087. continue;
  36088. }
  36089. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36090. var subMesh = _c[_b];
  36091. if (subMesh.getMaterial() !== this) {
  36092. continue;
  36093. }
  36094. if (!subMesh._materialDefines) {
  36095. continue;
  36096. }
  36097. func(subMesh._materialDefines);
  36098. }
  36099. }
  36100. };
  36101. /**
  36102. * Indicates that image processing needs to be re-calculated for all submeshes
  36103. */
  36104. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36105. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36106. };
  36107. /**
  36108. * Indicates that textures need to be re-calculated for all submeshes
  36109. */
  36110. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36111. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36112. };
  36113. /**
  36114. * Indicates that fresnel needs to be re-calculated for all submeshes
  36115. */
  36116. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36117. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36118. };
  36119. /**
  36120. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36121. */
  36122. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36123. this._markAllSubMeshesAsDirty(function (defines) {
  36124. defines.markAsFresnelDirty();
  36125. defines.markAsMiscDirty();
  36126. });
  36127. };
  36128. /**
  36129. * Indicates that lights need to be re-calculated for all submeshes
  36130. */
  36131. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36132. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36133. };
  36134. /**
  36135. * Indicates that attributes need to be re-calculated for all submeshes
  36136. */
  36137. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36138. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36139. };
  36140. /**
  36141. * Indicates that misc needs to be re-calculated for all submeshes
  36142. */
  36143. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36144. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36145. };
  36146. /**
  36147. * Indicates that textures and misc need to be re-calculated for all submeshes
  36148. */
  36149. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36150. this._markAllSubMeshesAsDirty(function (defines) {
  36151. defines.markAsTexturesDirty();
  36152. defines.markAsMiscDirty();
  36153. });
  36154. };
  36155. /**
  36156. * Disposes the material
  36157. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36158. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36159. */
  36160. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36161. // Animations
  36162. this.getScene().stopAnimation(this);
  36163. this.getScene().freeProcessedMaterials();
  36164. // Remove from scene
  36165. var index = this._scene.materials.indexOf(this);
  36166. if (index >= 0) {
  36167. this._scene.materials.splice(index, 1);
  36168. }
  36169. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36170. // Remove from meshes
  36171. for (index = 0; index < this._scene.meshes.length; index++) {
  36172. var mesh = this._scene.meshes[index];
  36173. if (mesh.material === this) {
  36174. mesh.material = null;
  36175. if (mesh.geometry) {
  36176. var geometry = (mesh.geometry);
  36177. if (this.storeEffectOnSubMeshes) {
  36178. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36179. var subMesh = _a[_i];
  36180. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36181. if (forceDisposeEffect && subMesh._materialEffect) {
  36182. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36183. }
  36184. }
  36185. }
  36186. else {
  36187. geometry._releaseVertexArrayObject(this._effect);
  36188. }
  36189. }
  36190. }
  36191. }
  36192. this._uniformBuffer.dispose();
  36193. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36194. if (forceDisposeEffect && this._effect) {
  36195. if (!this.storeEffectOnSubMeshes) {
  36196. this._scene.getEngine()._releaseEffect(this._effect);
  36197. }
  36198. this._effect = null;
  36199. }
  36200. // Callback
  36201. this.onDisposeObservable.notifyObservers(this);
  36202. this.onDisposeObservable.clear();
  36203. if (this._onBindObservable) {
  36204. this._onBindObservable.clear();
  36205. }
  36206. if (this._onUnBindObservable) {
  36207. this._onUnBindObservable.clear();
  36208. }
  36209. };
  36210. /**
  36211. * Serializes this material
  36212. * @returns the serialized material object
  36213. */
  36214. Material.prototype.serialize = function () {
  36215. return BABYLON.SerializationHelper.Serialize(this);
  36216. };
  36217. /**
  36218. * Creates a MultiMaterial from parsed MultiMaterial data.
  36219. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36220. * @param scene defines the hosting scene
  36221. * @returns a new MultiMaterial
  36222. */
  36223. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36224. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36225. multiMaterial.id = parsedMultiMaterial.id;
  36226. if (BABYLON.Tags) {
  36227. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36228. }
  36229. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36230. var subMatId = parsedMultiMaterial.materials[matIndex];
  36231. if (subMatId) {
  36232. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36233. }
  36234. else {
  36235. multiMaterial.subMaterials.push(null);
  36236. }
  36237. }
  36238. return multiMaterial;
  36239. };
  36240. /**
  36241. * Creates a material from parsed material data
  36242. * @param parsedMaterial defines parsed material data
  36243. * @param scene defines the hosting scene
  36244. * @param rootUrl defines the root URL to use to load textures
  36245. * @returns a new material
  36246. */
  36247. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36248. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36249. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36250. }
  36251. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36252. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36253. if (!BABYLON.LegacyPBRMaterial) {
  36254. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36255. return;
  36256. }
  36257. }
  36258. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36259. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36260. };
  36261. // Triangle views
  36262. Material._TriangleFillMode = 0;
  36263. Material._WireFrameFillMode = 1;
  36264. Material._PointFillMode = 2;
  36265. // Draw modes
  36266. Material._PointListDrawMode = 3;
  36267. Material._LineListDrawMode = 4;
  36268. Material._LineLoopDrawMode = 5;
  36269. Material._LineStripDrawMode = 6;
  36270. Material._TriangleStripDrawMode = 7;
  36271. Material._TriangleFanDrawMode = 8;
  36272. /**
  36273. * Stores the clock-wise side orientation
  36274. */
  36275. Material._ClockWiseSideOrientation = 0;
  36276. /**
  36277. * Stores the counter clock-wise side orientation
  36278. */
  36279. Material._CounterClockWiseSideOrientation = 1;
  36280. /**
  36281. * The dirty texture flag value
  36282. */
  36283. Material.TextureDirtyFlag = 1;
  36284. /**
  36285. * The dirty light flag value
  36286. */
  36287. Material.LightDirtyFlag = 2;
  36288. /**
  36289. * The dirty fresnel flag value
  36290. */
  36291. Material.FresnelDirtyFlag = 4;
  36292. /**
  36293. * The dirty attribute flag value
  36294. */
  36295. Material.AttributesDirtyFlag = 8;
  36296. /**
  36297. * The dirty misc flag value
  36298. */
  36299. Material.MiscDirtyFlag = 16;
  36300. /**
  36301. * The all dirty flag value
  36302. */
  36303. Material.AllDirtyFlag = 31;
  36304. __decorate([
  36305. BABYLON.serialize()
  36306. ], Material.prototype, "id", void 0);
  36307. __decorate([
  36308. BABYLON.serialize()
  36309. ], Material.prototype, "uniqueId", void 0);
  36310. __decorate([
  36311. BABYLON.serialize()
  36312. ], Material.prototype, "name", void 0);
  36313. __decorate([
  36314. BABYLON.serialize()
  36315. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36316. __decorate([
  36317. BABYLON.serialize()
  36318. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36319. __decorate([
  36320. BABYLON.serialize()
  36321. ], Material.prototype, "state", void 0);
  36322. __decorate([
  36323. BABYLON.serialize("alpha")
  36324. ], Material.prototype, "_alpha", void 0);
  36325. __decorate([
  36326. BABYLON.serialize("backFaceCulling")
  36327. ], Material.prototype, "_backFaceCulling", void 0);
  36328. __decorate([
  36329. BABYLON.serialize()
  36330. ], Material.prototype, "sideOrientation", void 0);
  36331. __decorate([
  36332. BABYLON.serialize("alphaMode")
  36333. ], Material.prototype, "_alphaMode", void 0);
  36334. __decorate([
  36335. BABYLON.serialize()
  36336. ], Material.prototype, "_needDepthPrePass", void 0);
  36337. __decorate([
  36338. BABYLON.serialize()
  36339. ], Material.prototype, "disableDepthWrite", void 0);
  36340. __decorate([
  36341. BABYLON.serialize()
  36342. ], Material.prototype, "forceDepthWrite", void 0);
  36343. __decorate([
  36344. BABYLON.serialize()
  36345. ], Material.prototype, "separateCullingPass", void 0);
  36346. __decorate([
  36347. BABYLON.serialize("fogEnabled")
  36348. ], Material.prototype, "_fogEnabled", void 0);
  36349. __decorate([
  36350. BABYLON.serialize()
  36351. ], Material.prototype, "pointSize", void 0);
  36352. __decorate([
  36353. BABYLON.serialize()
  36354. ], Material.prototype, "zOffset", void 0);
  36355. __decorate([
  36356. BABYLON.serialize()
  36357. ], Material.prototype, "wireframe", null);
  36358. __decorate([
  36359. BABYLON.serialize()
  36360. ], Material.prototype, "pointsCloud", null);
  36361. __decorate([
  36362. BABYLON.serialize()
  36363. ], Material.prototype, "fillMode", null);
  36364. return Material;
  36365. }());
  36366. BABYLON.Material = Material;
  36367. })(BABYLON || (BABYLON = {}));
  36368. //# sourceMappingURL=babylon.material.js.map
  36369. var BABYLON;
  36370. (function (BABYLON) {
  36371. /**
  36372. * Uniform buffer objects.
  36373. *
  36374. * Handles blocks of uniform on the GPU.
  36375. *
  36376. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36377. *
  36378. * For more information, please refer to :
  36379. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36380. */
  36381. var UniformBuffer = /** @class */ (function () {
  36382. /**
  36383. * Instantiates a new Uniform buffer objects.
  36384. *
  36385. * Handles blocks of uniform on the GPU.
  36386. *
  36387. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36388. *
  36389. * For more information, please refer to :
  36390. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36391. * @param engine Define the engine the buffer is associated with
  36392. * @param data Define the data contained in the buffer
  36393. * @param dynamic Define if the buffer is updatable
  36394. */
  36395. function UniformBuffer(engine, data, dynamic) {
  36396. this._engine = engine;
  36397. this._noUBO = !engine.supportsUniformBuffers;
  36398. this._dynamic = dynamic;
  36399. this._data = data || [];
  36400. this._uniformLocations = {};
  36401. this._uniformSizes = {};
  36402. this._uniformLocationPointer = 0;
  36403. this._needSync = false;
  36404. if (this._noUBO) {
  36405. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36406. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36407. this.updateFloat = this._updateFloatForEffect;
  36408. this.updateFloat2 = this._updateFloat2ForEffect;
  36409. this.updateFloat3 = this._updateFloat3ForEffect;
  36410. this.updateFloat4 = this._updateFloat4ForEffect;
  36411. this.updateMatrix = this._updateMatrixForEffect;
  36412. this.updateVector3 = this._updateVector3ForEffect;
  36413. this.updateVector4 = this._updateVector4ForEffect;
  36414. this.updateColor3 = this._updateColor3ForEffect;
  36415. this.updateColor4 = this._updateColor4ForEffect;
  36416. }
  36417. else {
  36418. this._engine._uniformBuffers.push(this);
  36419. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36420. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36421. this.updateFloat = this._updateFloatForUniform;
  36422. this.updateFloat2 = this._updateFloat2ForUniform;
  36423. this.updateFloat3 = this._updateFloat3ForUniform;
  36424. this.updateFloat4 = this._updateFloat4ForUniform;
  36425. this.updateMatrix = this._updateMatrixForUniform;
  36426. this.updateVector3 = this._updateVector3ForUniform;
  36427. this.updateVector4 = this._updateVector4ForUniform;
  36428. this.updateColor3 = this._updateColor3ForUniform;
  36429. this.updateColor4 = this._updateColor4ForUniform;
  36430. }
  36431. }
  36432. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36433. /**
  36434. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36435. * or just falling back on setUniformXXX calls.
  36436. */
  36437. get: function () {
  36438. return !this._noUBO;
  36439. },
  36440. enumerable: true,
  36441. configurable: true
  36442. });
  36443. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36444. /**
  36445. * Indicates if the WebGL underlying uniform buffer is in sync
  36446. * with the javascript cache data.
  36447. */
  36448. get: function () {
  36449. return !this._needSync;
  36450. },
  36451. enumerable: true,
  36452. configurable: true
  36453. });
  36454. /**
  36455. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36456. * Also, a dynamic UniformBuffer will disable cache verification and always
  36457. * update the underlying WebGL uniform buffer to the GPU.
  36458. * @returns if Dynamic, otherwise false
  36459. */
  36460. UniformBuffer.prototype.isDynamic = function () {
  36461. return this._dynamic !== undefined;
  36462. };
  36463. /**
  36464. * The data cache on JS side.
  36465. * @returns the underlying data as a float array
  36466. */
  36467. UniformBuffer.prototype.getData = function () {
  36468. return this._bufferData;
  36469. };
  36470. /**
  36471. * The underlying WebGL Uniform buffer.
  36472. * @returns the webgl buffer
  36473. */
  36474. UniformBuffer.prototype.getBuffer = function () {
  36475. return this._buffer;
  36476. };
  36477. /**
  36478. * std140 layout specifies how to align data within an UBO structure.
  36479. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36480. * for specs.
  36481. */
  36482. UniformBuffer.prototype._fillAlignment = function (size) {
  36483. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36484. // and 4x4 matrices
  36485. // TODO : change if other types are used
  36486. var alignment;
  36487. if (size <= 2) {
  36488. alignment = size;
  36489. }
  36490. else {
  36491. alignment = 4;
  36492. }
  36493. if ((this._uniformLocationPointer % alignment) !== 0) {
  36494. var oldPointer = this._uniformLocationPointer;
  36495. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36496. var diff = this._uniformLocationPointer - oldPointer;
  36497. for (var i = 0; i < diff; i++) {
  36498. this._data.push(0);
  36499. }
  36500. }
  36501. };
  36502. /**
  36503. * Adds an uniform in the buffer.
  36504. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36505. * for the layout to be correct !
  36506. * @param name Name of the uniform, as used in the uniform block in the shader.
  36507. * @param size Data size, or data directly.
  36508. */
  36509. UniformBuffer.prototype.addUniform = function (name, size) {
  36510. if (this._noUBO) {
  36511. return;
  36512. }
  36513. if (this._uniformLocations[name] !== undefined) {
  36514. // Already existing uniform
  36515. return;
  36516. }
  36517. // This function must be called in the order of the shader layout !
  36518. // size can be the size of the uniform, or data directly
  36519. var data;
  36520. if (size instanceof Array) {
  36521. data = size;
  36522. size = data.length;
  36523. }
  36524. else {
  36525. size = size;
  36526. data = [];
  36527. // Fill with zeros
  36528. for (var i = 0; i < size; i++) {
  36529. data.push(0);
  36530. }
  36531. }
  36532. this._fillAlignment(size);
  36533. this._uniformSizes[name] = size;
  36534. this._uniformLocations[name] = this._uniformLocationPointer;
  36535. this._uniformLocationPointer += size;
  36536. for (var i = 0; i < size; i++) {
  36537. this._data.push(data[i]);
  36538. }
  36539. this._needSync = true;
  36540. };
  36541. /**
  36542. * Adds a Matrix 4x4 to the uniform buffer.
  36543. * @param name Name of the uniform, as used in the uniform block in the shader.
  36544. * @param mat A 4x4 matrix.
  36545. */
  36546. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36547. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36548. };
  36549. /**
  36550. * Adds a vec2 to the uniform buffer.
  36551. * @param name Name of the uniform, as used in the uniform block in the shader.
  36552. * @param x Define the x component value of the vec2
  36553. * @param y Define the y component value of the vec2
  36554. */
  36555. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36556. var temp = [x, y];
  36557. this.addUniform(name, temp);
  36558. };
  36559. /**
  36560. * Adds a vec3 to the uniform buffer.
  36561. * @param name Name of the uniform, as used in the uniform block in the shader.
  36562. * @param x Define the x component value of the vec3
  36563. * @param y Define the y component value of the vec3
  36564. * @param z Define the z component value of the vec3
  36565. */
  36566. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36567. var temp = [x, y, z];
  36568. this.addUniform(name, temp);
  36569. };
  36570. /**
  36571. * Adds a vec3 to the uniform buffer.
  36572. * @param name Name of the uniform, as used in the uniform block in the shader.
  36573. * @param color Define the vec3 from a Color
  36574. */
  36575. UniformBuffer.prototype.addColor3 = function (name, color) {
  36576. var temp = new Array();
  36577. color.toArray(temp);
  36578. this.addUniform(name, temp);
  36579. };
  36580. /**
  36581. * Adds a vec4 to the uniform buffer.
  36582. * @param name Name of the uniform, as used in the uniform block in the shader.
  36583. * @param color Define the rgb components from a Color
  36584. * @param alpha Define the a component of the vec4
  36585. */
  36586. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36587. var temp = new Array();
  36588. color.toArray(temp);
  36589. temp.push(alpha);
  36590. this.addUniform(name, temp);
  36591. };
  36592. /**
  36593. * Adds a vec3 to the uniform buffer.
  36594. * @param name Name of the uniform, as used in the uniform block in the shader.
  36595. * @param vector Define the vec3 components from a Vector
  36596. */
  36597. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36598. var temp = new Array();
  36599. vector.toArray(temp);
  36600. this.addUniform(name, temp);
  36601. };
  36602. /**
  36603. * Adds a Matrix 3x3 to the uniform buffer.
  36604. * @param name Name of the uniform, as used in the uniform block in the shader.
  36605. */
  36606. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36607. this.addUniform(name, 12);
  36608. };
  36609. /**
  36610. * Adds a Matrix 2x2 to the uniform buffer.
  36611. * @param name Name of the uniform, as used in the uniform block in the shader.
  36612. */
  36613. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36614. this.addUniform(name, 8);
  36615. };
  36616. /**
  36617. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36618. */
  36619. UniformBuffer.prototype.create = function () {
  36620. if (this._noUBO) {
  36621. return;
  36622. }
  36623. if (this._buffer) {
  36624. return; // nothing to do
  36625. }
  36626. // See spec, alignment must be filled as a vec4
  36627. this._fillAlignment(4);
  36628. this._bufferData = new Float32Array(this._data);
  36629. this._rebuild();
  36630. this._needSync = true;
  36631. };
  36632. /** @hidden */
  36633. UniformBuffer.prototype._rebuild = function () {
  36634. if (this._noUBO) {
  36635. return;
  36636. }
  36637. if (this._dynamic) {
  36638. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36639. }
  36640. else {
  36641. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36642. }
  36643. };
  36644. /**
  36645. * Updates the WebGL Uniform Buffer on the GPU.
  36646. * If the `dynamic` flag is set to true, no cache comparison is done.
  36647. * Otherwise, the buffer will be updated only if the cache differs.
  36648. */
  36649. UniformBuffer.prototype.update = function () {
  36650. if (!this._buffer) {
  36651. this.create();
  36652. return;
  36653. }
  36654. if (!this._dynamic && !this._needSync) {
  36655. return;
  36656. }
  36657. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36658. this._needSync = false;
  36659. };
  36660. /**
  36661. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36662. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36663. * @param data Define the flattened data
  36664. * @param size Define the size of the data.
  36665. */
  36666. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36667. var location = this._uniformLocations[uniformName];
  36668. if (location === undefined) {
  36669. if (this._buffer) {
  36670. // Cannot add an uniform if the buffer is already created
  36671. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36672. return;
  36673. }
  36674. this.addUniform(uniformName, size);
  36675. location = this._uniformLocations[uniformName];
  36676. }
  36677. if (!this._buffer) {
  36678. this.create();
  36679. }
  36680. if (!this._dynamic) {
  36681. // Cache for static uniform buffers
  36682. var changed = false;
  36683. for (var i = 0; i < size; i++) {
  36684. if (this._bufferData[location + i] !== data[i]) {
  36685. changed = true;
  36686. this._bufferData[location + i] = data[i];
  36687. }
  36688. }
  36689. this._needSync = this._needSync || changed;
  36690. }
  36691. else {
  36692. // No cache for dynamic
  36693. for (var i = 0; i < size; i++) {
  36694. this._bufferData[location + i] = data[i];
  36695. }
  36696. }
  36697. };
  36698. // Update methods
  36699. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36700. // To match std140, matrix must be realigned
  36701. for (var i = 0; i < 3; i++) {
  36702. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36703. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36704. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36705. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36706. }
  36707. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36708. };
  36709. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36710. this._currentEffect.setMatrix3x3(name, matrix);
  36711. };
  36712. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36713. this._currentEffect.setMatrix2x2(name, matrix);
  36714. };
  36715. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36716. // To match std140, matrix must be realigned
  36717. for (var i = 0; i < 2; i++) {
  36718. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36719. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36720. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36721. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36722. }
  36723. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36724. };
  36725. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36726. this._currentEffect.setFloat(name, x);
  36727. };
  36728. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36729. UniformBuffer._tempBuffer[0] = x;
  36730. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36731. };
  36732. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36733. if (suffix === void 0) { suffix = ""; }
  36734. this._currentEffect.setFloat2(name + suffix, x, y);
  36735. };
  36736. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36737. if (suffix === void 0) { suffix = ""; }
  36738. UniformBuffer._tempBuffer[0] = x;
  36739. UniformBuffer._tempBuffer[1] = y;
  36740. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36741. };
  36742. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36743. if (suffix === void 0) { suffix = ""; }
  36744. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36745. };
  36746. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36747. if (suffix === void 0) { suffix = ""; }
  36748. UniformBuffer._tempBuffer[0] = x;
  36749. UniformBuffer._tempBuffer[1] = y;
  36750. UniformBuffer._tempBuffer[2] = z;
  36751. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36752. };
  36753. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36754. if (suffix === void 0) { suffix = ""; }
  36755. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36756. };
  36757. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36758. if (suffix === void 0) { suffix = ""; }
  36759. UniformBuffer._tempBuffer[0] = x;
  36760. UniformBuffer._tempBuffer[1] = y;
  36761. UniformBuffer._tempBuffer[2] = z;
  36762. UniformBuffer._tempBuffer[3] = w;
  36763. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36764. };
  36765. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36766. this._currentEffect.setMatrix(name, mat);
  36767. };
  36768. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36769. this.updateUniform(name, mat.toArray(), 16);
  36770. };
  36771. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36772. this._currentEffect.setVector3(name, vector);
  36773. };
  36774. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36775. vector.toArray(UniformBuffer._tempBuffer);
  36776. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36777. };
  36778. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36779. this._currentEffect.setVector4(name, vector);
  36780. };
  36781. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36782. vector.toArray(UniformBuffer._tempBuffer);
  36783. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36784. };
  36785. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36786. if (suffix === void 0) { suffix = ""; }
  36787. this._currentEffect.setColor3(name + suffix, color);
  36788. };
  36789. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36790. if (suffix === void 0) { suffix = ""; }
  36791. color.toArray(UniformBuffer._tempBuffer);
  36792. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36793. };
  36794. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36795. if (suffix === void 0) { suffix = ""; }
  36796. this._currentEffect.setColor4(name + suffix, color, alpha);
  36797. };
  36798. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36799. if (suffix === void 0) { suffix = ""; }
  36800. color.toArray(UniformBuffer._tempBuffer);
  36801. UniformBuffer._tempBuffer[3] = alpha;
  36802. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36803. };
  36804. /**
  36805. * Sets a sampler uniform on the effect.
  36806. * @param name Define the name of the sampler.
  36807. * @param texture Define the texture to set in the sampler
  36808. */
  36809. UniformBuffer.prototype.setTexture = function (name, texture) {
  36810. this._currentEffect.setTexture(name, texture);
  36811. };
  36812. /**
  36813. * Directly updates the value of the uniform in the cache AND on the GPU.
  36814. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36815. * @param data Define the flattened data
  36816. */
  36817. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36818. this.updateUniform(uniformName, data, data.length);
  36819. this.update();
  36820. };
  36821. /**
  36822. * Binds this uniform buffer to an effect.
  36823. * @param effect Define the effect to bind the buffer to
  36824. * @param name Name of the uniform block in the shader.
  36825. */
  36826. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36827. this._currentEffect = effect;
  36828. if (this._noUBO || !this._buffer) {
  36829. return;
  36830. }
  36831. effect.bindUniformBuffer(this._buffer, name);
  36832. };
  36833. /**
  36834. * Disposes the uniform buffer.
  36835. */
  36836. UniformBuffer.prototype.dispose = function () {
  36837. if (this._noUBO) {
  36838. return;
  36839. }
  36840. var index = this._engine._uniformBuffers.indexOf(this);
  36841. if (index !== -1) {
  36842. this._engine._uniformBuffers.splice(index, 1);
  36843. }
  36844. if (!this._buffer) {
  36845. return;
  36846. }
  36847. if (this._engine._releaseBuffer(this._buffer)) {
  36848. this._buffer = null;
  36849. }
  36850. };
  36851. // Pool for avoiding memory leaks
  36852. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36853. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36854. return UniformBuffer;
  36855. }());
  36856. BABYLON.UniformBuffer = UniformBuffer;
  36857. })(BABYLON || (BABYLON = {}));
  36858. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36859. var BABYLON;
  36860. (function (BABYLON) {
  36861. /**
  36862. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36863. */
  36864. var VertexData = /** @class */ (function () {
  36865. function VertexData() {
  36866. }
  36867. /**
  36868. * Uses the passed data array to set the set the values for the specified kind of data
  36869. * @param data a linear array of floating numbers
  36870. * @param kind the type of data that is being set, eg positions, colors etc
  36871. */
  36872. VertexData.prototype.set = function (data, kind) {
  36873. switch (kind) {
  36874. case BABYLON.VertexBuffer.PositionKind:
  36875. this.positions = data;
  36876. break;
  36877. case BABYLON.VertexBuffer.NormalKind:
  36878. this.normals = data;
  36879. break;
  36880. case BABYLON.VertexBuffer.TangentKind:
  36881. this.tangents = data;
  36882. break;
  36883. case BABYLON.VertexBuffer.UVKind:
  36884. this.uvs = data;
  36885. break;
  36886. case BABYLON.VertexBuffer.UV2Kind:
  36887. this.uvs2 = data;
  36888. break;
  36889. case BABYLON.VertexBuffer.UV3Kind:
  36890. this.uvs3 = data;
  36891. break;
  36892. case BABYLON.VertexBuffer.UV4Kind:
  36893. this.uvs4 = data;
  36894. break;
  36895. case BABYLON.VertexBuffer.UV5Kind:
  36896. this.uvs5 = data;
  36897. break;
  36898. case BABYLON.VertexBuffer.UV6Kind:
  36899. this.uvs6 = data;
  36900. break;
  36901. case BABYLON.VertexBuffer.ColorKind:
  36902. this.colors = data;
  36903. break;
  36904. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36905. this.matricesIndices = data;
  36906. break;
  36907. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36908. this.matricesWeights = data;
  36909. break;
  36910. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36911. this.matricesIndicesExtra = data;
  36912. break;
  36913. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36914. this.matricesWeightsExtra = data;
  36915. break;
  36916. }
  36917. };
  36918. /**
  36919. * Associates the vertexData to the passed Mesh.
  36920. * Sets it as updatable or not (default `false`)
  36921. * @param mesh the mesh the vertexData is applied to
  36922. * @param updatable when used and having the value true allows new data to update the vertexData
  36923. * @returns the VertexData
  36924. */
  36925. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36926. this._applyTo(mesh, updatable);
  36927. return this;
  36928. };
  36929. /**
  36930. * Associates the vertexData to the passed Geometry.
  36931. * Sets it as updatable or not (default `false`)
  36932. * @param geometry the geometry the vertexData is applied to
  36933. * @param updatable when used and having the value true allows new data to update the vertexData
  36934. * @returns VertexData
  36935. */
  36936. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36937. this._applyTo(geometry, updatable);
  36938. return this;
  36939. };
  36940. /**
  36941. * Updates the associated mesh
  36942. * @param mesh the mesh to be updated
  36943. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36944. * @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
  36945. * @returns VertexData
  36946. */
  36947. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36948. this._update(mesh);
  36949. return this;
  36950. };
  36951. /**
  36952. * Updates the associated geometry
  36953. * @param geometry the geometry to be updated
  36954. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36955. * @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
  36956. * @returns VertexData.
  36957. */
  36958. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36959. this._update(geometry);
  36960. return this;
  36961. };
  36962. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36963. if (updatable === void 0) { updatable = false; }
  36964. if (this.positions) {
  36965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36966. }
  36967. if (this.normals) {
  36968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36969. }
  36970. if (this.tangents) {
  36971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36972. }
  36973. if (this.uvs) {
  36974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36975. }
  36976. if (this.uvs2) {
  36977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36978. }
  36979. if (this.uvs3) {
  36980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36981. }
  36982. if (this.uvs4) {
  36983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36984. }
  36985. if (this.uvs5) {
  36986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36987. }
  36988. if (this.uvs6) {
  36989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36990. }
  36991. if (this.colors) {
  36992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36993. }
  36994. if (this.matricesIndices) {
  36995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36996. }
  36997. if (this.matricesWeights) {
  36998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36999. }
  37000. if (this.matricesIndicesExtra) {
  37001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37002. }
  37003. if (this.matricesWeightsExtra) {
  37004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37005. }
  37006. if (this.indices) {
  37007. meshOrGeometry.setIndices(this.indices, null, updatable);
  37008. }
  37009. else {
  37010. meshOrGeometry.setIndices([], null);
  37011. }
  37012. return this;
  37013. };
  37014. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37015. if (this.positions) {
  37016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37017. }
  37018. if (this.normals) {
  37019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37020. }
  37021. if (this.tangents) {
  37022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37023. }
  37024. if (this.uvs) {
  37025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37026. }
  37027. if (this.uvs2) {
  37028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37029. }
  37030. if (this.uvs3) {
  37031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37032. }
  37033. if (this.uvs4) {
  37034. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37035. }
  37036. if (this.uvs5) {
  37037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37038. }
  37039. if (this.uvs6) {
  37040. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37041. }
  37042. if (this.colors) {
  37043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37044. }
  37045. if (this.matricesIndices) {
  37046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37047. }
  37048. if (this.matricesWeights) {
  37049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37050. }
  37051. if (this.matricesIndicesExtra) {
  37052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37053. }
  37054. if (this.matricesWeightsExtra) {
  37055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37056. }
  37057. if (this.indices) {
  37058. meshOrGeometry.setIndices(this.indices, null);
  37059. }
  37060. return this;
  37061. };
  37062. /**
  37063. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37064. * @param matrix the transforming matrix
  37065. * @returns the VertexData
  37066. */
  37067. VertexData.prototype.transform = function (matrix) {
  37068. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37069. var transformed = BABYLON.Vector3.Zero();
  37070. var index;
  37071. if (this.positions) {
  37072. var position = BABYLON.Vector3.Zero();
  37073. for (index = 0; index < this.positions.length; index += 3) {
  37074. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37075. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37076. this.positions[index] = transformed.x;
  37077. this.positions[index + 1] = transformed.y;
  37078. this.positions[index + 2] = transformed.z;
  37079. }
  37080. }
  37081. if (this.normals) {
  37082. var normal = BABYLON.Vector3.Zero();
  37083. for (index = 0; index < this.normals.length; index += 3) {
  37084. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37085. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37086. this.normals[index] = transformed.x;
  37087. this.normals[index + 1] = transformed.y;
  37088. this.normals[index + 2] = transformed.z;
  37089. }
  37090. }
  37091. if (this.tangents) {
  37092. var tangent = BABYLON.Vector4.Zero();
  37093. var tangentTransformed = BABYLON.Vector4.Zero();
  37094. for (index = 0; index < this.tangents.length; index += 4) {
  37095. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37096. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37097. this.tangents[index] = tangentTransformed.x;
  37098. this.tangents[index + 1] = tangentTransformed.y;
  37099. this.tangents[index + 2] = tangentTransformed.z;
  37100. this.tangents[index + 3] = tangentTransformed.w;
  37101. }
  37102. }
  37103. if (flip && this.indices) {
  37104. for (index = 0; index < this.indices.length; index += 3) {
  37105. var tmp = this.indices[index + 1];
  37106. this.indices[index + 1] = this.indices[index + 2];
  37107. this.indices[index + 2] = tmp;
  37108. }
  37109. }
  37110. return this;
  37111. };
  37112. /**
  37113. * Merges the passed VertexData into the current one
  37114. * @param other the VertexData to be merged into the current one
  37115. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37116. * @returns the modified VertexData
  37117. */
  37118. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37119. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37120. this._validate();
  37121. other._validate();
  37122. if (!this.normals !== !other.normals ||
  37123. !this.tangents !== !other.tangents ||
  37124. !this.uvs !== !other.uvs ||
  37125. !this.uvs2 !== !other.uvs2 ||
  37126. !this.uvs3 !== !other.uvs3 ||
  37127. !this.uvs4 !== !other.uvs4 ||
  37128. !this.uvs5 !== !other.uvs5 ||
  37129. !this.uvs6 !== !other.uvs6 ||
  37130. !this.colors !== !other.colors ||
  37131. !this.matricesIndices !== !other.matricesIndices ||
  37132. !this.matricesWeights !== !other.matricesWeights ||
  37133. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37134. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37135. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37136. }
  37137. if (other.indices) {
  37138. if (!this.indices) {
  37139. this.indices = [];
  37140. }
  37141. var offset = this.positions ? this.positions.length / 3 : 0;
  37142. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37143. if (isSrcTypedArray) {
  37144. var len = this.indices.length + other.indices.length;
  37145. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37146. temp.set(this.indices);
  37147. var decal = this.indices.length;
  37148. for (var index = 0; index < other.indices.length; index++) {
  37149. temp[decal + index] = other.indices[index] + offset;
  37150. }
  37151. this.indices = temp;
  37152. }
  37153. else {
  37154. for (var index = 0; index < other.indices.length; index++) {
  37155. this.indices.push(other.indices[index] + offset);
  37156. }
  37157. }
  37158. }
  37159. this.positions = this._mergeElement(this.positions, other.positions);
  37160. this.normals = this._mergeElement(this.normals, other.normals);
  37161. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37162. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37163. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37164. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37165. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37166. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37167. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37168. this.colors = this._mergeElement(this.colors, other.colors);
  37169. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37170. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37171. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37172. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37173. return this;
  37174. };
  37175. VertexData.prototype._mergeElement = function (source, other) {
  37176. if (!source) {
  37177. return other;
  37178. }
  37179. if (!other) {
  37180. return source;
  37181. }
  37182. var len = other.length + source.length;
  37183. var isSrcTypedArray = source instanceof Float32Array;
  37184. var isOthTypedArray = other instanceof Float32Array;
  37185. // use non-loop method when the source is Float32Array
  37186. if (isSrcTypedArray) {
  37187. var ret32 = new Float32Array(len);
  37188. ret32.set(source);
  37189. ret32.set(other, source.length);
  37190. return ret32;
  37191. // source is number[], when other is also use concat
  37192. }
  37193. else if (!isOthTypedArray) {
  37194. return source.concat(other);
  37195. // source is a number[], but other is a Float32Array, loop required
  37196. }
  37197. else {
  37198. var ret = source.slice(0); // copy source to a separate array
  37199. for (var i = 0, len = other.length; i < len; i++) {
  37200. ret.push(other[i]);
  37201. }
  37202. return ret;
  37203. }
  37204. };
  37205. VertexData.prototype._validate = function () {
  37206. if (!this.positions) {
  37207. throw new Error("Positions are required");
  37208. }
  37209. var getElementCount = function (kind, values) {
  37210. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37211. if ((values.length % stride) !== 0) {
  37212. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37213. }
  37214. return values.length / stride;
  37215. };
  37216. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37217. var validateElementCount = function (kind, values) {
  37218. var elementCount = getElementCount(kind, values);
  37219. if (elementCount !== positionsElementCount) {
  37220. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37221. }
  37222. };
  37223. if (this.normals)
  37224. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37225. if (this.tangents)
  37226. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37227. if (this.uvs)
  37228. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37229. if (this.uvs2)
  37230. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37231. if (this.uvs3)
  37232. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37233. if (this.uvs4)
  37234. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37235. if (this.uvs5)
  37236. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37237. if (this.uvs6)
  37238. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37239. if (this.colors)
  37240. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37241. if (this.matricesIndices)
  37242. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37243. if (this.matricesWeights)
  37244. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37245. if (this.matricesIndicesExtra)
  37246. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37247. if (this.matricesWeightsExtra)
  37248. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37249. };
  37250. /**
  37251. * Serializes the VertexData
  37252. * @returns a serialized object
  37253. */
  37254. VertexData.prototype.serialize = function () {
  37255. var serializationObject = this.serialize();
  37256. if (this.positions) {
  37257. serializationObject.positions = this.positions;
  37258. }
  37259. if (this.normals) {
  37260. serializationObject.normals = this.normals;
  37261. }
  37262. if (this.tangents) {
  37263. serializationObject.tangents = this.tangents;
  37264. }
  37265. if (this.uvs) {
  37266. serializationObject.uvs = this.uvs;
  37267. }
  37268. if (this.uvs2) {
  37269. serializationObject.uvs2 = this.uvs2;
  37270. }
  37271. if (this.uvs3) {
  37272. serializationObject.uvs3 = this.uvs3;
  37273. }
  37274. if (this.uvs4) {
  37275. serializationObject.uvs4 = this.uvs4;
  37276. }
  37277. if (this.uvs5) {
  37278. serializationObject.uvs5 = this.uvs5;
  37279. }
  37280. if (this.uvs6) {
  37281. serializationObject.uvs6 = this.uvs6;
  37282. }
  37283. if (this.colors) {
  37284. serializationObject.colors = this.colors;
  37285. }
  37286. if (this.matricesIndices) {
  37287. serializationObject.matricesIndices = this.matricesIndices;
  37288. serializationObject.matricesIndices._isExpanded = true;
  37289. }
  37290. if (this.matricesWeights) {
  37291. serializationObject.matricesWeights = this.matricesWeights;
  37292. }
  37293. if (this.matricesIndicesExtra) {
  37294. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37295. serializationObject.matricesIndicesExtra._isExpanded = true;
  37296. }
  37297. if (this.matricesWeightsExtra) {
  37298. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37299. }
  37300. serializationObject.indices = this.indices;
  37301. return serializationObject;
  37302. };
  37303. // Statics
  37304. /**
  37305. * Extracts the vertexData from a mesh
  37306. * @param mesh the mesh from which to extract the VertexData
  37307. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37308. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37309. * @returns the object VertexData associated to the passed mesh
  37310. */
  37311. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37312. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37313. };
  37314. /**
  37315. * Extracts the vertexData from the geometry
  37316. * @param geometry the geometry from which to extract the VertexData
  37317. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37318. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37319. * @returns the object VertexData associated to the passed mesh
  37320. */
  37321. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37322. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37323. };
  37324. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37325. var result = new VertexData();
  37326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37327. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37328. }
  37329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37330. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37331. }
  37332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37333. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37334. }
  37335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37336. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37337. }
  37338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37339. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37340. }
  37341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37342. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37343. }
  37344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37345. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37346. }
  37347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37348. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37349. }
  37350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37351. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37352. }
  37353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37354. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37355. }
  37356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37357. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37358. }
  37359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37360. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37361. }
  37362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37363. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37364. }
  37365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37366. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37367. }
  37368. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37369. return result;
  37370. };
  37371. /**
  37372. * Creates the VertexData for a Ribbon
  37373. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37374. * * pathArray array of paths, each of which an array of successive Vector3
  37375. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37376. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37377. * * 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
  37378. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37379. * * 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)
  37380. * * 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)
  37381. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37382. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37383. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37384. * @returns the VertexData of the ribbon
  37385. */
  37386. VertexData.CreateRibbon = function (options) {
  37387. var pathArray = options.pathArray;
  37388. var closeArray = options.closeArray || false;
  37389. var closePath = options.closePath || false;
  37390. var invertUV = options.invertUV || false;
  37391. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37392. var offset = options.offset || defaultOffset;
  37393. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37394. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37395. var customUV = options.uvs;
  37396. var customColors = options.colors;
  37397. var positions = [];
  37398. var indices = [];
  37399. var normals = [];
  37400. var uvs = [];
  37401. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37402. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37403. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37404. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37405. var minlg; // minimal length among all paths from pathArray
  37406. var lg = []; // array of path lengths : nb of vertex per path
  37407. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37408. var p; // path iterator
  37409. var i; // point iterator
  37410. var j; // point iterator
  37411. // if single path in pathArray
  37412. if (pathArray.length < 2) {
  37413. var ar1 = [];
  37414. var ar2 = [];
  37415. for (i = 0; i < pathArray[0].length - offset; i++) {
  37416. ar1.push(pathArray[0][i]);
  37417. ar2.push(pathArray[0][i + offset]);
  37418. }
  37419. pathArray = [ar1, ar2];
  37420. }
  37421. // positions and horizontal distances (u)
  37422. var idc = 0;
  37423. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37424. var path;
  37425. var l;
  37426. minlg = pathArray[0].length;
  37427. var vectlg;
  37428. var dist;
  37429. for (p = 0; p < pathArray.length; p++) {
  37430. uTotalDistance[p] = 0;
  37431. us[p] = [0];
  37432. path = pathArray[p];
  37433. l = path.length;
  37434. minlg = (minlg < l) ? minlg : l;
  37435. j = 0;
  37436. while (j < l) {
  37437. positions.push(path[j].x, path[j].y, path[j].z);
  37438. if (j > 0) {
  37439. vectlg = path[j].subtract(path[j - 1]).length();
  37440. dist = vectlg + uTotalDistance[p];
  37441. us[p].push(dist);
  37442. uTotalDistance[p] = dist;
  37443. }
  37444. j++;
  37445. }
  37446. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37447. j--;
  37448. positions.push(path[0].x, path[0].y, path[0].z);
  37449. vectlg = path[j].subtract(path[0]).length();
  37450. dist = vectlg + uTotalDistance[p];
  37451. us[p].push(dist);
  37452. uTotalDistance[p] = dist;
  37453. }
  37454. lg[p] = l + closePathCorr;
  37455. idx[p] = idc;
  37456. idc += (l + closePathCorr);
  37457. }
  37458. // vertical distances (v)
  37459. var path1;
  37460. var path2;
  37461. var vertex1 = null;
  37462. var vertex2 = null;
  37463. for (i = 0; i < minlg + closePathCorr; i++) {
  37464. vTotalDistance[i] = 0;
  37465. vs[i] = [0];
  37466. for (p = 0; p < pathArray.length - 1; p++) {
  37467. path1 = pathArray[p];
  37468. path2 = pathArray[p + 1];
  37469. if (i === minlg) { // closePath
  37470. vertex1 = path1[0];
  37471. vertex2 = path2[0];
  37472. }
  37473. else {
  37474. vertex1 = path1[i];
  37475. vertex2 = path2[i];
  37476. }
  37477. vectlg = vertex2.subtract(vertex1).length();
  37478. dist = vectlg + vTotalDistance[i];
  37479. vs[i].push(dist);
  37480. vTotalDistance[i] = dist;
  37481. }
  37482. if (closeArray && vertex2 && vertex1) {
  37483. path1 = pathArray[p];
  37484. path2 = pathArray[0];
  37485. if (i === minlg) { // closePath
  37486. vertex2 = path2[0];
  37487. }
  37488. vectlg = vertex2.subtract(vertex1).length();
  37489. dist = vectlg + vTotalDistance[i];
  37490. vTotalDistance[i] = dist;
  37491. }
  37492. }
  37493. // uvs
  37494. var u;
  37495. var v;
  37496. if (customUV) {
  37497. for (p = 0; p < customUV.length; p++) {
  37498. uvs.push(customUV[p].x, customUV[p].y);
  37499. }
  37500. }
  37501. else {
  37502. for (p = 0; p < pathArray.length; p++) {
  37503. for (i = 0; i < minlg + closePathCorr; i++) {
  37504. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37505. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37506. if (invertUV) {
  37507. uvs.push(v, u);
  37508. }
  37509. else {
  37510. uvs.push(u, v);
  37511. }
  37512. }
  37513. }
  37514. }
  37515. // indices
  37516. p = 0; // path index
  37517. var pi = 0; // positions array index
  37518. var l1 = lg[p] - 1; // path1 length
  37519. var l2 = lg[p + 1] - 1; // path2 length
  37520. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37521. var shft = idx[1] - idx[0]; // shift
  37522. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37523. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37524. // 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
  37525. indices.push(pi, pi + shft, pi + 1);
  37526. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37527. pi += 1;
  37528. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37529. p++;
  37530. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37531. shft = idx[0] - idx[p];
  37532. l1 = lg[p] - 1;
  37533. l2 = lg[0] - 1;
  37534. }
  37535. else {
  37536. shft = idx[p + 1] - idx[p];
  37537. l1 = lg[p] - 1;
  37538. l2 = lg[p + 1] - 1;
  37539. }
  37540. pi = idx[p];
  37541. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37542. }
  37543. }
  37544. // normals
  37545. VertexData.ComputeNormals(positions, indices, normals);
  37546. if (closePath) { // update both the first and last vertex normals to their average value
  37547. var indexFirst = 0;
  37548. var indexLast = 0;
  37549. for (p = 0; p < pathArray.length; p++) {
  37550. indexFirst = idx[p] * 3;
  37551. if (p + 1 < pathArray.length) {
  37552. indexLast = (idx[p + 1] - 1) * 3;
  37553. }
  37554. else {
  37555. indexLast = normals.length - 3;
  37556. }
  37557. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37558. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37559. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37560. normals[indexLast] = normals[indexFirst];
  37561. normals[indexLast + 1] = normals[indexFirst + 1];
  37562. normals[indexLast + 2] = normals[indexFirst + 2];
  37563. }
  37564. }
  37565. // sides
  37566. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37567. // Colors
  37568. var colors = null;
  37569. if (customColors) {
  37570. colors = new Float32Array(customColors.length * 4);
  37571. for (var c = 0; c < customColors.length; c++) {
  37572. colors[c * 4] = customColors[c].r;
  37573. colors[c * 4 + 1] = customColors[c].g;
  37574. colors[c * 4 + 2] = customColors[c].b;
  37575. colors[c * 4 + 3] = customColors[c].a;
  37576. }
  37577. }
  37578. // Result
  37579. var vertexData = new VertexData();
  37580. var positions32 = new Float32Array(positions);
  37581. var normals32 = new Float32Array(normals);
  37582. var uvs32 = new Float32Array(uvs);
  37583. vertexData.indices = indices;
  37584. vertexData.positions = positions32;
  37585. vertexData.normals = normals32;
  37586. vertexData.uvs = uvs32;
  37587. if (colors) {
  37588. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37589. }
  37590. if (closePath) {
  37591. vertexData._idx = idx;
  37592. }
  37593. return vertexData;
  37594. };
  37595. /**
  37596. * Creates the VertexData for a box
  37597. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37598. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37599. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37600. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37601. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37602. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37603. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37604. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37605. * * 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)
  37606. * * 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)
  37607. * @returns the VertexData of the box
  37608. */
  37609. VertexData.CreateBox = function (options) {
  37610. var normalsSource = [
  37611. new BABYLON.Vector3(0, 0, 1),
  37612. new BABYLON.Vector3(0, 0, -1),
  37613. new BABYLON.Vector3(1, 0, 0),
  37614. new BABYLON.Vector3(-1, 0, 0),
  37615. new BABYLON.Vector3(0, 1, 0),
  37616. new BABYLON.Vector3(0, -1, 0)
  37617. ];
  37618. var indices = [];
  37619. var positions = [];
  37620. var normals = [];
  37621. var uvs = [];
  37622. var width = options.width || options.size || 1;
  37623. var height = options.height || options.size || 1;
  37624. var depth = options.depth || options.size || 1;
  37625. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37626. var faceUV = options.faceUV || new Array(6);
  37627. var faceColors = options.faceColors;
  37628. var colors = [];
  37629. // default face colors and UV if undefined
  37630. for (var f = 0; f < 6; f++) {
  37631. if (faceUV[f] === undefined) {
  37632. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37633. }
  37634. if (faceColors && faceColors[f] === undefined) {
  37635. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37636. }
  37637. }
  37638. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37639. // Create each face in turn.
  37640. for (var index = 0; index < normalsSource.length; index++) {
  37641. var normal = normalsSource[index];
  37642. // Get two vectors perpendicular to the face normal and to each other.
  37643. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37644. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37645. // Six indices (two triangles) per face.
  37646. var verticesLength = positions.length / 3;
  37647. indices.push(verticesLength);
  37648. indices.push(verticesLength + 1);
  37649. indices.push(verticesLength + 2);
  37650. indices.push(verticesLength);
  37651. indices.push(verticesLength + 2);
  37652. indices.push(verticesLength + 3);
  37653. // Four vertices per face.
  37654. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37655. positions.push(vertex.x, vertex.y, vertex.z);
  37656. normals.push(normal.x, normal.y, normal.z);
  37657. uvs.push(faceUV[index].z, faceUV[index].w);
  37658. if (faceColors) {
  37659. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37660. }
  37661. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37662. positions.push(vertex.x, vertex.y, vertex.z);
  37663. normals.push(normal.x, normal.y, normal.z);
  37664. uvs.push(faceUV[index].x, faceUV[index].w);
  37665. if (faceColors) {
  37666. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37667. }
  37668. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37669. positions.push(vertex.x, vertex.y, vertex.z);
  37670. normals.push(normal.x, normal.y, normal.z);
  37671. uvs.push(faceUV[index].x, faceUV[index].y);
  37672. if (faceColors) {
  37673. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37674. }
  37675. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37676. positions.push(vertex.x, vertex.y, vertex.z);
  37677. normals.push(normal.x, normal.y, normal.z);
  37678. uvs.push(faceUV[index].z, faceUV[index].y);
  37679. if (faceColors) {
  37680. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37681. }
  37682. }
  37683. // sides
  37684. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37685. // Result
  37686. var vertexData = new VertexData();
  37687. vertexData.indices = indices;
  37688. vertexData.positions = positions;
  37689. vertexData.normals = normals;
  37690. vertexData.uvs = uvs;
  37691. if (faceColors) {
  37692. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37693. vertexData.colors = totalColors;
  37694. }
  37695. return vertexData;
  37696. };
  37697. /**
  37698. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37699. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37700. * * segments sets the number of horizontal strips optional, default 32
  37701. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37702. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37703. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37704. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37705. * * 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
  37706. * * 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
  37707. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37708. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37709. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37710. * @returns the VertexData of the ellipsoid
  37711. */
  37712. VertexData.CreateSphere = function (options) {
  37713. var segments = options.segments || 32;
  37714. var diameterX = options.diameterX || options.diameter || 1;
  37715. var diameterY = options.diameterY || options.diameter || 1;
  37716. var diameterZ = options.diameterZ || options.diameter || 1;
  37717. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37718. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37719. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37720. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37721. var totalZRotationSteps = 2 + segments;
  37722. var totalYRotationSteps = 2 * totalZRotationSteps;
  37723. var indices = [];
  37724. var positions = [];
  37725. var normals = [];
  37726. var uvs = [];
  37727. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37728. var normalizedZ = zRotationStep / totalZRotationSteps;
  37729. var angleZ = normalizedZ * Math.PI * slice;
  37730. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37731. var normalizedY = yRotationStep / totalYRotationSteps;
  37732. var angleY = normalizedY * Math.PI * 2 * arc;
  37733. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37734. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37735. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37736. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37737. var vertex = complete.multiply(radius);
  37738. var normal = complete.divide(radius).normalize();
  37739. positions.push(vertex.x, vertex.y, vertex.z);
  37740. normals.push(normal.x, normal.y, normal.z);
  37741. uvs.push(normalizedY, normalizedZ);
  37742. }
  37743. if (zRotationStep > 0) {
  37744. var verticesCount = positions.length / 3;
  37745. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37746. indices.push((firstIndex));
  37747. indices.push((firstIndex + 1));
  37748. indices.push(firstIndex + totalYRotationSteps + 1);
  37749. indices.push((firstIndex + totalYRotationSteps + 1));
  37750. indices.push((firstIndex + 1));
  37751. indices.push((firstIndex + totalYRotationSteps + 2));
  37752. }
  37753. }
  37754. }
  37755. // Sides
  37756. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37757. // Result
  37758. var vertexData = new VertexData();
  37759. vertexData.indices = indices;
  37760. vertexData.positions = positions;
  37761. vertexData.normals = normals;
  37762. vertexData.uvs = uvs;
  37763. return vertexData;
  37764. };
  37765. /**
  37766. * Creates the VertexData for a cylinder, cone or prism
  37767. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37768. * * height sets the height (y direction) of the cylinder, optional, default 2
  37769. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37770. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37771. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37772. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37773. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37774. * * 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
  37775. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37776. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37777. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37778. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37779. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37780. * * 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)
  37781. * * 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)
  37782. * @returns the VertexData of the cylinder, cone or prism
  37783. */
  37784. VertexData.CreateCylinder = function (options) {
  37785. var height = options.height || 2;
  37786. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37787. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37788. var tessellation = options.tessellation || 24;
  37789. var subdivisions = options.subdivisions || 1;
  37790. var hasRings = options.hasRings ? true : false;
  37791. var enclose = options.enclose ? true : false;
  37792. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37793. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37794. var faceUV = options.faceUV || new Array(3);
  37795. var faceColors = options.faceColors;
  37796. // default face colors and UV if undefined
  37797. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37798. var ringNb = (hasRings) ? subdivisions : 1;
  37799. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37800. var f;
  37801. for (f = 0; f < surfaceNb; f++) {
  37802. if (faceColors && faceColors[f] === undefined) {
  37803. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37804. }
  37805. }
  37806. for (f = 0; f < surfaceNb; f++) {
  37807. if (faceUV && faceUV[f] === undefined) {
  37808. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37809. }
  37810. }
  37811. var indices = new Array();
  37812. var positions = new Array();
  37813. var normals = new Array();
  37814. var uvs = new Array();
  37815. var colors = new Array();
  37816. var angle_step = Math.PI * 2 * arc / tessellation;
  37817. var angle;
  37818. var h;
  37819. var radius;
  37820. var tan = (diameterBottom - diameterTop) / 2 / height;
  37821. var ringVertex = BABYLON.Vector3.Zero();
  37822. var ringNormal = BABYLON.Vector3.Zero();
  37823. var ringFirstVertex = BABYLON.Vector3.Zero();
  37824. var ringFirstNormal = BABYLON.Vector3.Zero();
  37825. var quadNormal = BABYLON.Vector3.Zero();
  37826. var Y = BABYLON.Axis.Y;
  37827. // positions, normals, uvs
  37828. var i;
  37829. var j;
  37830. var r;
  37831. var ringIdx = 1;
  37832. var s = 1; // surface index
  37833. var cs = 0;
  37834. var v = 0;
  37835. for (i = 0; i <= subdivisions; i++) {
  37836. h = i / subdivisions;
  37837. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37838. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37839. for (r = 0; r < ringIdx; r++) {
  37840. if (hasRings) {
  37841. s += r;
  37842. }
  37843. if (enclose) {
  37844. s += 2 * r;
  37845. }
  37846. for (j = 0; j <= tessellation; j++) {
  37847. angle = j * angle_step;
  37848. // position
  37849. ringVertex.x = Math.cos(-angle) * radius;
  37850. ringVertex.y = -height / 2 + h * height;
  37851. ringVertex.z = Math.sin(-angle) * radius;
  37852. // normal
  37853. if (diameterTop === 0 && i === subdivisions) {
  37854. // if no top cap, reuse former normals
  37855. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37856. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37857. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37858. }
  37859. else {
  37860. ringNormal.x = ringVertex.x;
  37861. ringNormal.z = ringVertex.z;
  37862. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37863. ringNormal.normalize();
  37864. }
  37865. // keep first ring vertex values for enclose
  37866. if (j === 0) {
  37867. ringFirstVertex.copyFrom(ringVertex);
  37868. ringFirstNormal.copyFrom(ringNormal);
  37869. }
  37870. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37871. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37872. if (hasRings) {
  37873. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37874. }
  37875. else {
  37876. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37877. }
  37878. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37879. if (faceColors) {
  37880. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37881. }
  37882. }
  37883. // if enclose, add four vertices and their dedicated normals
  37884. if (arc !== 1 && enclose) {
  37885. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37886. positions.push(0, ringVertex.y, 0);
  37887. positions.push(0, ringVertex.y, 0);
  37888. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37889. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37890. quadNormal.normalize();
  37891. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37892. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37893. quadNormal.normalize();
  37894. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37895. if (hasRings) {
  37896. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37897. }
  37898. else {
  37899. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37900. }
  37901. uvs.push(faceUV[s + 1].x, v);
  37902. uvs.push(faceUV[s + 1].z, v);
  37903. if (hasRings) {
  37904. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37905. }
  37906. else {
  37907. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37908. }
  37909. uvs.push(faceUV[s + 2].x, v);
  37910. uvs.push(faceUV[s + 2].z, v);
  37911. if (faceColors) {
  37912. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37913. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37914. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37915. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37916. }
  37917. }
  37918. if (cs !== s) {
  37919. cs = s;
  37920. }
  37921. }
  37922. }
  37923. // indices
  37924. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37925. var s;
  37926. i = 0;
  37927. for (s = 0; s < subdivisions; s++) {
  37928. var i0 = 0;
  37929. var i1 = 0;
  37930. var i2 = 0;
  37931. var i3 = 0;
  37932. for (j = 0; j < tessellation; j++) {
  37933. i0 = i * (e + 1) + j;
  37934. i1 = (i + 1) * (e + 1) + j;
  37935. i2 = i * (e + 1) + (j + 1);
  37936. i3 = (i + 1) * (e + 1) + (j + 1);
  37937. indices.push(i0, i1, i2);
  37938. indices.push(i3, i2, i1);
  37939. }
  37940. if (arc !== 1 && enclose) { // if enclose, add two quads
  37941. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37942. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37943. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37944. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37945. }
  37946. i = (hasRings) ? (i + 2) : (i + 1);
  37947. }
  37948. // Caps
  37949. var createCylinderCap = function (isTop) {
  37950. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37951. if (radius === 0) {
  37952. return;
  37953. }
  37954. // Cap positions, normals & uvs
  37955. var angle;
  37956. var circleVector;
  37957. var i;
  37958. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37959. var c = null;
  37960. if (faceColors) {
  37961. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37962. }
  37963. // cap center
  37964. var vbase = positions.length / 3;
  37965. var offset = isTop ? height / 2 : -height / 2;
  37966. var center = new BABYLON.Vector3(0, offset, 0);
  37967. positions.push(center.x, center.y, center.z);
  37968. normals.push(0, isTop ? 1 : -1, 0);
  37969. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37970. if (c) {
  37971. colors.push(c.r, c.g, c.b, c.a);
  37972. }
  37973. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37974. for (i = 0; i <= tessellation; i++) {
  37975. angle = Math.PI * 2 * i * arc / tessellation;
  37976. var cos = Math.cos(-angle);
  37977. var sin = Math.sin(-angle);
  37978. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37979. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37980. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37981. normals.push(0, isTop ? 1 : -1, 0);
  37982. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37983. if (c) {
  37984. colors.push(c.r, c.g, c.b, c.a);
  37985. }
  37986. }
  37987. // Cap indices
  37988. for (i = 0; i < tessellation; i++) {
  37989. if (!isTop) {
  37990. indices.push(vbase);
  37991. indices.push(vbase + (i + 1));
  37992. indices.push(vbase + (i + 2));
  37993. }
  37994. else {
  37995. indices.push(vbase);
  37996. indices.push(vbase + (i + 2));
  37997. indices.push(vbase + (i + 1));
  37998. }
  37999. }
  38000. };
  38001. // add caps to geometry
  38002. createCylinderCap(false);
  38003. createCylinderCap(true);
  38004. // Sides
  38005. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38006. var vertexData = new VertexData();
  38007. vertexData.indices = indices;
  38008. vertexData.positions = positions;
  38009. vertexData.normals = normals;
  38010. vertexData.uvs = uvs;
  38011. if (faceColors) {
  38012. vertexData.colors = colors;
  38013. }
  38014. return vertexData;
  38015. };
  38016. /**
  38017. * Creates the VertexData for a torus
  38018. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38019. * * diameter the diameter of the torus, optional default 1
  38020. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38021. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38022. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38023. * * 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)
  38024. * * 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)
  38025. * @returns the VertexData of the torus
  38026. */
  38027. VertexData.CreateTorus = function (options) {
  38028. var indices = [];
  38029. var positions = [];
  38030. var normals = [];
  38031. var uvs = [];
  38032. var diameter = options.diameter || 1;
  38033. var thickness = options.thickness || 0.5;
  38034. var tessellation = options.tessellation || 16;
  38035. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38036. var stride = tessellation + 1;
  38037. for (var i = 0; i <= tessellation; i++) {
  38038. var u = i / tessellation;
  38039. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38040. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38041. for (var j = 0; j <= tessellation; j++) {
  38042. var v = 1 - j / tessellation;
  38043. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38044. var dx = Math.cos(innerAngle);
  38045. var dy = Math.sin(innerAngle);
  38046. // Create a vertex.
  38047. var normal = new BABYLON.Vector3(dx, dy, 0);
  38048. var position = normal.scale(thickness / 2);
  38049. var textureCoordinate = new BABYLON.Vector2(u, v);
  38050. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38051. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38052. positions.push(position.x, position.y, position.z);
  38053. normals.push(normal.x, normal.y, normal.z);
  38054. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38055. // And create indices for two triangles.
  38056. var nextI = (i + 1) % stride;
  38057. var nextJ = (j + 1) % stride;
  38058. indices.push(i * stride + j);
  38059. indices.push(i * stride + nextJ);
  38060. indices.push(nextI * stride + j);
  38061. indices.push(i * stride + nextJ);
  38062. indices.push(nextI * stride + nextJ);
  38063. indices.push(nextI * stride + j);
  38064. }
  38065. }
  38066. // Sides
  38067. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38068. // Result
  38069. var vertexData = new VertexData();
  38070. vertexData.indices = indices;
  38071. vertexData.positions = positions;
  38072. vertexData.normals = normals;
  38073. vertexData.uvs = uvs;
  38074. return vertexData;
  38075. };
  38076. /**
  38077. * Creates the VertexData of the LineSystem
  38078. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38079. * - lines an array of lines, each line being an array of successive Vector3
  38080. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38081. * @returns the VertexData of the LineSystem
  38082. */
  38083. VertexData.CreateLineSystem = function (options) {
  38084. var indices = [];
  38085. var positions = [];
  38086. var lines = options.lines;
  38087. var colors = options.colors;
  38088. var vertexColors = [];
  38089. var idx = 0;
  38090. for (var l = 0; l < lines.length; l++) {
  38091. var points = lines[l];
  38092. for (var index = 0; index < points.length; index++) {
  38093. positions.push(points[index].x, points[index].y, points[index].z);
  38094. if (colors) {
  38095. var color = colors[l];
  38096. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38097. }
  38098. if (index > 0) {
  38099. indices.push(idx - 1);
  38100. indices.push(idx);
  38101. }
  38102. idx++;
  38103. }
  38104. }
  38105. var vertexData = new VertexData();
  38106. vertexData.indices = indices;
  38107. vertexData.positions = positions;
  38108. if (colors) {
  38109. vertexData.colors = vertexColors;
  38110. }
  38111. return vertexData;
  38112. };
  38113. /**
  38114. * Create the VertexData for a DashedLines
  38115. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38116. * - points an array successive Vector3
  38117. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38118. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38119. * - dashNb the intended total number of dashes, optional, default 200
  38120. * @returns the VertexData for the DashedLines
  38121. */
  38122. VertexData.CreateDashedLines = function (options) {
  38123. var dashSize = options.dashSize || 3;
  38124. var gapSize = options.gapSize || 1;
  38125. var dashNb = options.dashNb || 200;
  38126. var points = options.points;
  38127. var positions = new Array();
  38128. var indices = new Array();
  38129. var curvect = BABYLON.Vector3.Zero();
  38130. var lg = 0;
  38131. var nb = 0;
  38132. var shft = 0;
  38133. var dashshft = 0;
  38134. var curshft = 0;
  38135. var idx = 0;
  38136. var i = 0;
  38137. for (i = 0; i < points.length - 1; i++) {
  38138. points[i + 1].subtractToRef(points[i], curvect);
  38139. lg += curvect.length();
  38140. }
  38141. shft = lg / dashNb;
  38142. dashshft = dashSize * shft / (dashSize + gapSize);
  38143. for (i = 0; i < points.length - 1; i++) {
  38144. points[i + 1].subtractToRef(points[i], curvect);
  38145. nb = Math.floor(curvect.length() / shft);
  38146. curvect.normalize();
  38147. for (var j = 0; j < nb; j++) {
  38148. curshft = shft * j;
  38149. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38150. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38151. indices.push(idx, idx + 1);
  38152. idx += 2;
  38153. }
  38154. }
  38155. // Result
  38156. var vertexData = new VertexData();
  38157. vertexData.positions = positions;
  38158. vertexData.indices = indices;
  38159. return vertexData;
  38160. };
  38161. /**
  38162. * Creates the VertexData for a Ground
  38163. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38164. * - width the width (x direction) of the ground, optional, default 1
  38165. * - height the height (z direction) of the ground, optional, default 1
  38166. * - subdivisions the number of subdivisions per side, optional, default 1
  38167. * @returns the VertexData of the Ground
  38168. */
  38169. VertexData.CreateGround = function (options) {
  38170. var indices = [];
  38171. var positions = [];
  38172. var normals = [];
  38173. var uvs = [];
  38174. var row, col;
  38175. var width = options.width || 1;
  38176. var height = options.height || 1;
  38177. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38178. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38179. for (row = 0; row <= subdivisionsY; row++) {
  38180. for (col = 0; col <= subdivisionsX; col++) {
  38181. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38182. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38183. positions.push(position.x, position.y, position.z);
  38184. normals.push(normal.x, normal.y, normal.z);
  38185. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38186. }
  38187. }
  38188. for (row = 0; row < subdivisionsY; row++) {
  38189. for (col = 0; col < subdivisionsX; col++) {
  38190. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38191. indices.push(col + 1 + row * (subdivisionsX + 1));
  38192. indices.push(col + row * (subdivisionsX + 1));
  38193. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38194. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38195. indices.push(col + row * (subdivisionsX + 1));
  38196. }
  38197. }
  38198. // Result
  38199. var vertexData = new VertexData();
  38200. vertexData.indices = indices;
  38201. vertexData.positions = positions;
  38202. vertexData.normals = normals;
  38203. vertexData.uvs = uvs;
  38204. return vertexData;
  38205. };
  38206. /**
  38207. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38208. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38209. * * xmin the ground minimum X coordinate, optional, default -1
  38210. * * zmin the ground minimum Z coordinate, optional, default -1
  38211. * * xmax the ground maximum X coordinate, optional, default 1
  38212. * * zmax the ground maximum Z coordinate, optional, default 1
  38213. * * 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}
  38214. * * 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}
  38215. * @returns the VertexData of the TiledGround
  38216. */
  38217. VertexData.CreateTiledGround = function (options) {
  38218. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38219. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38220. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38221. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38222. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38223. var precision = options.precision || { w: 1, h: 1 };
  38224. var indices = new Array();
  38225. var positions = new Array();
  38226. var normals = new Array();
  38227. var uvs = new Array();
  38228. var row, col, tileRow, tileCol;
  38229. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38230. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38231. precision.w = (precision.w < 1) ? 1 : precision.w;
  38232. precision.h = (precision.h < 1) ? 1 : precision.h;
  38233. var tileSize = {
  38234. 'w': (xmax - xmin) / subdivisions.w,
  38235. 'h': (zmax - zmin) / subdivisions.h
  38236. };
  38237. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38238. // Indices
  38239. var base = positions.length / 3;
  38240. var rowLength = precision.w + 1;
  38241. for (row = 0; row < precision.h; row++) {
  38242. for (col = 0; col < precision.w; col++) {
  38243. var square = [
  38244. base + col + row * rowLength,
  38245. base + (col + 1) + row * rowLength,
  38246. base + (col + 1) + (row + 1) * rowLength,
  38247. base + col + (row + 1) * rowLength
  38248. ];
  38249. indices.push(square[1]);
  38250. indices.push(square[2]);
  38251. indices.push(square[3]);
  38252. indices.push(square[0]);
  38253. indices.push(square[1]);
  38254. indices.push(square[3]);
  38255. }
  38256. }
  38257. // Position, normals and uvs
  38258. var position = BABYLON.Vector3.Zero();
  38259. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38260. for (row = 0; row <= precision.h; row++) {
  38261. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38262. for (col = 0; col <= precision.w; col++) {
  38263. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38264. position.y = 0;
  38265. positions.push(position.x, position.y, position.z);
  38266. normals.push(normal.x, normal.y, normal.z);
  38267. uvs.push(col / precision.w, row / precision.h);
  38268. }
  38269. }
  38270. }
  38271. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38272. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38273. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38274. }
  38275. }
  38276. // Result
  38277. var vertexData = new VertexData();
  38278. vertexData.indices = indices;
  38279. vertexData.positions = positions;
  38280. vertexData.normals = normals;
  38281. vertexData.uvs = uvs;
  38282. return vertexData;
  38283. };
  38284. /**
  38285. * Creates the VertexData of the Ground designed from a heightmap
  38286. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38287. * * width the width (x direction) of the ground
  38288. * * height the height (z direction) of the ground
  38289. * * subdivisions the number of subdivisions per side
  38290. * * minHeight the minimum altitude on the ground, optional, default 0
  38291. * * maxHeight the maximum altitude on the ground, optional default 1
  38292. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38293. * * buffer the array holding the image color data
  38294. * * bufferWidth the width of image
  38295. * * bufferHeight the height of image
  38296. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38297. * @returns the VertexData of the Ground designed from a heightmap
  38298. */
  38299. VertexData.CreateGroundFromHeightMap = function (options) {
  38300. var indices = [];
  38301. var positions = [];
  38302. var normals = [];
  38303. var uvs = [];
  38304. var row, col;
  38305. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38306. var alphaFilter = options.alphaFilter || 0.0;
  38307. // Vertices
  38308. for (row = 0; row <= options.subdivisions; row++) {
  38309. for (col = 0; col <= options.subdivisions; col++) {
  38310. 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));
  38311. // Compute height
  38312. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38313. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38314. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38315. var r = options.buffer[pos] / 255.0;
  38316. var g = options.buffer[pos + 1] / 255.0;
  38317. var b = options.buffer[pos + 2] / 255.0;
  38318. var a = options.buffer[pos + 3] / 255.0;
  38319. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38320. // If our alpha channel is not within our filter then we will assign a 'special' height
  38321. // Then when building the indices, we will ignore any vertex that is using the special height
  38322. if (a >= alphaFilter)
  38323. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38324. else {
  38325. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38326. }
  38327. // Add vertex
  38328. positions.push(position.x, position.y, position.z);
  38329. normals.push(0, 0, 0);
  38330. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38331. }
  38332. }
  38333. // Indices
  38334. for (row = 0; row < options.subdivisions; row++) {
  38335. for (col = 0; col < options.subdivisions; col++) {
  38336. // Calculate Indices
  38337. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38338. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38339. var idx3 = (col + row * (options.subdivisions + 1));
  38340. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38341. // Check that all indices are visible (based on our special height)
  38342. // Only display the vertex if all Indices are visible
  38343. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38344. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38345. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38346. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38347. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38348. indices.push(idx1);
  38349. indices.push(idx2);
  38350. indices.push(idx3);
  38351. }
  38352. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38353. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38354. indices.push(idx4);
  38355. indices.push(idx1);
  38356. indices.push(idx3);
  38357. }
  38358. }
  38359. }
  38360. // Normals
  38361. VertexData.ComputeNormals(positions, indices, normals);
  38362. // Result
  38363. var vertexData = new VertexData();
  38364. vertexData.indices = indices;
  38365. vertexData.positions = positions;
  38366. vertexData.normals = normals;
  38367. vertexData.uvs = uvs;
  38368. return vertexData;
  38369. };
  38370. /**
  38371. * Creates the VertexData for a Plane
  38372. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38373. * * size sets the width and height of the plane to the value of size, optional default 1
  38374. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38375. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38376. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38377. * * 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)
  38378. * * 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)
  38379. * @returns the VertexData of the box
  38380. */
  38381. VertexData.CreatePlane = function (options) {
  38382. var indices = [];
  38383. var positions = [];
  38384. var normals = [];
  38385. var uvs = [];
  38386. var width = options.width || options.size || 1;
  38387. var height = options.height || options.size || 1;
  38388. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38389. // Vertices
  38390. var halfWidth = width / 2.0;
  38391. var halfHeight = height / 2.0;
  38392. positions.push(-halfWidth, -halfHeight, 0);
  38393. normals.push(0, 0, -1.0);
  38394. uvs.push(0.0, 0.0);
  38395. positions.push(halfWidth, -halfHeight, 0);
  38396. normals.push(0, 0, -1.0);
  38397. uvs.push(1.0, 0.0);
  38398. positions.push(halfWidth, halfHeight, 0);
  38399. normals.push(0, 0, -1.0);
  38400. uvs.push(1.0, 1.0);
  38401. positions.push(-halfWidth, halfHeight, 0);
  38402. normals.push(0, 0, -1.0);
  38403. uvs.push(0.0, 1.0);
  38404. // Indices
  38405. indices.push(0);
  38406. indices.push(1);
  38407. indices.push(2);
  38408. indices.push(0);
  38409. indices.push(2);
  38410. indices.push(3);
  38411. // Sides
  38412. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38413. // Result
  38414. var vertexData = new VertexData();
  38415. vertexData.indices = indices;
  38416. vertexData.positions = positions;
  38417. vertexData.normals = normals;
  38418. vertexData.uvs = uvs;
  38419. return vertexData;
  38420. };
  38421. /**
  38422. * Creates the VertexData of the Disc or regular Polygon
  38423. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38424. * * radius the radius of the disc, optional default 0.5
  38425. * * tessellation the number of polygon sides, optional, default 64
  38426. * * 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
  38427. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38428. * * 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)
  38429. * * 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)
  38430. * @returns the VertexData of the box
  38431. */
  38432. VertexData.CreateDisc = function (options) {
  38433. var positions = new Array();
  38434. var indices = new Array();
  38435. var normals = new Array();
  38436. var uvs = new Array();
  38437. var radius = options.radius || 0.5;
  38438. var tessellation = options.tessellation || 64;
  38439. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38440. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38441. // positions and uvs
  38442. positions.push(0, 0, 0); // disc center first
  38443. uvs.push(0.5, 0.5);
  38444. var theta = Math.PI * 2 * arc;
  38445. var step = theta / tessellation;
  38446. for (var a = 0; a < theta; a += step) {
  38447. var x = Math.cos(a);
  38448. var y = Math.sin(a);
  38449. var u = (x + 1) / 2;
  38450. var v = (1 - y) / 2;
  38451. positions.push(radius * x, radius * y, 0);
  38452. uvs.push(u, v);
  38453. }
  38454. if (arc === 1) {
  38455. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38456. uvs.push(uvs[2], uvs[3]);
  38457. }
  38458. //indices
  38459. var vertexNb = positions.length / 3;
  38460. for (var i = 1; i < vertexNb - 1; i++) {
  38461. indices.push(i + 1, 0, i);
  38462. }
  38463. // result
  38464. VertexData.ComputeNormals(positions, indices, normals);
  38465. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38466. var vertexData = new VertexData();
  38467. vertexData.indices = indices;
  38468. vertexData.positions = positions;
  38469. vertexData.normals = normals;
  38470. vertexData.uvs = uvs;
  38471. return vertexData;
  38472. };
  38473. /**
  38474. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38475. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38476. * @param polygon a mesh built from polygonTriangulation.build()
  38477. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38478. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38479. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38480. * @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)
  38481. * @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)
  38482. * @returns the VertexData of the Polygon
  38483. */
  38484. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38485. var faceUV = fUV || new Array(3);
  38486. var faceColors = fColors;
  38487. var colors = [];
  38488. // default face colors and UV if undefined
  38489. for (var f = 0; f < 3; f++) {
  38490. if (faceUV[f] === undefined) {
  38491. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38492. }
  38493. if (faceColors && faceColors[f] === undefined) {
  38494. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38495. }
  38496. }
  38497. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38498. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38499. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38500. var indices = polygon.getIndices();
  38501. // set face colours and textures
  38502. var idx = 0;
  38503. var face = 0;
  38504. for (var index = 0; index < normals.length; index += 3) {
  38505. //Edge Face no. 1
  38506. if (Math.abs(normals[index + 1]) < 0.001) {
  38507. face = 1;
  38508. }
  38509. //Top Face no. 0
  38510. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38511. face = 0;
  38512. }
  38513. //Bottom Face no. 2
  38514. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38515. face = 2;
  38516. }
  38517. idx = index / 3;
  38518. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38519. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38520. if (faceColors) {
  38521. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38522. }
  38523. }
  38524. // sides
  38525. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38526. // Result
  38527. var vertexData = new VertexData();
  38528. vertexData.indices = indices;
  38529. vertexData.positions = positions;
  38530. vertexData.normals = normals;
  38531. vertexData.uvs = uvs;
  38532. if (faceColors) {
  38533. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38534. vertexData.colors = totalColors;
  38535. }
  38536. return vertexData;
  38537. };
  38538. /**
  38539. * Creates the VertexData of the IcoSphere
  38540. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38541. * * radius the radius of the IcoSphere, optional default 1
  38542. * * radiusX allows stretching in the x direction, optional, default radius
  38543. * * radiusY allows stretching in the y direction, optional, default radius
  38544. * * radiusZ allows stretching in the z direction, optional, default radius
  38545. * * flat when true creates a flat shaded mesh, optional, default true
  38546. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38547. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38548. * * 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)
  38549. * * 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)
  38550. * @returns the VertexData of the IcoSphere
  38551. */
  38552. VertexData.CreateIcoSphere = function (options) {
  38553. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38554. var radius = options.radius || 1;
  38555. var flat = (options.flat === undefined) ? true : options.flat;
  38556. var subdivisions = options.subdivisions || 4;
  38557. var radiusX = options.radiusX || radius;
  38558. var radiusY = options.radiusY || radius;
  38559. var radiusZ = options.radiusZ || radius;
  38560. var t = (1 + Math.sqrt(5)) / 2;
  38561. // 12 vertex x,y,z
  38562. var ico_vertices = [
  38563. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38564. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38565. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38566. ];
  38567. // index of 3 vertex makes a face of icopshere
  38568. var ico_indices = [
  38569. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38570. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38571. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38572. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38573. ];
  38574. // vertex for uv have aliased position, not for UV
  38575. var vertices_unalias_id = [
  38576. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38577. // vertex alias
  38578. 0,
  38579. 2,
  38580. 3,
  38581. 3,
  38582. 3,
  38583. 4,
  38584. 7,
  38585. 8,
  38586. 9,
  38587. 9,
  38588. 10,
  38589. 11 // 23: B + 12
  38590. ];
  38591. // uv as integer step (not pixels !)
  38592. var ico_vertexuv = [
  38593. 5, 1, 3, 1, 6, 4, 0, 0,
  38594. 5, 3, 4, 2, 2, 2, 4, 0,
  38595. 2, 0, 1, 1, 6, 0, 6, 2,
  38596. // vertex alias (for same vertex on different faces)
  38597. 0, 4,
  38598. 3, 3,
  38599. 4, 4,
  38600. 3, 1,
  38601. 4, 2,
  38602. 4, 4,
  38603. 0, 2,
  38604. 1, 1,
  38605. 2, 2,
  38606. 3, 3,
  38607. 1, 3,
  38608. 2, 4 // 23: B + 12
  38609. ];
  38610. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38611. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38612. // First island of uv mapping
  38613. // v = 4h 3+ 2
  38614. // v = 3h 9+ 4
  38615. // v = 2h 9+ 5 B
  38616. // v = 1h 9 1 0
  38617. // v = 0h 3 8 7 A
  38618. // u = 0 1 2 3 4 5 6 *a
  38619. // Second island of uv mapping
  38620. // v = 4h 0+ B+ 4+
  38621. // v = 3h A+ 2+
  38622. // v = 2h 7+ 6 3+
  38623. // v = 1h 8+ 3+
  38624. // v = 0h
  38625. // u = 0 1 2 3 4 5 6 *a
  38626. // Face layout on texture UV mapping
  38627. // ============
  38628. // \ 4 /\ 16 / ======
  38629. // \ / \ / /\ 11 /
  38630. // \/ 7 \/ / \ /
  38631. // ======= / 10 \/
  38632. // /\ 17 /\ =======
  38633. // / \ / \ \ 15 /\
  38634. // / 8 \/ 12 \ \ / \
  38635. // ============ \/ 6 \
  38636. // \ 18 /\ ============
  38637. // \ / \ \ 5 /\ 0 /
  38638. // \/ 13 \ \ / \ /
  38639. // ======= \/ 1 \/
  38640. // =============
  38641. // /\ 19 /\ 2 /\
  38642. // / \ / \ / \
  38643. // / 14 \/ 9 \/ 3 \
  38644. // ===================
  38645. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38646. var ustep = 138 / 1024;
  38647. var vstep = 239 / 1024;
  38648. var uoffset = 60 / 1024;
  38649. var voffset = 26 / 1024;
  38650. // Second island should have margin, not to touch the first island
  38651. // avoid any borderline artefact in pixel rounding
  38652. var island_u_offset = -40 / 1024;
  38653. var island_v_offset = +20 / 1024;
  38654. // face is either island 0 or 1 :
  38655. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38656. var island = [
  38657. 0, 0, 0, 0, 1,
  38658. 0, 0, 1, 1, 0,
  38659. 0, 0, 1, 1, 0,
  38660. 0, 1, 1, 1, 0 // 15 - 19
  38661. ];
  38662. var indices = new Array();
  38663. var positions = new Array();
  38664. var normals = new Array();
  38665. var uvs = new Array();
  38666. var current_indice = 0;
  38667. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38668. var face_vertex_pos = new Array(3);
  38669. var face_vertex_uv = new Array(3);
  38670. var v012;
  38671. for (v012 = 0; v012 < 3; v012++) {
  38672. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38673. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38674. }
  38675. // create all with normals
  38676. for (var face = 0; face < 20; face++) {
  38677. // 3 vertex per face
  38678. for (v012 = 0; v012 < 3; v012++) {
  38679. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38680. var v_id = ico_indices[3 * face + v012];
  38681. // vertex have 3D position (x,y,z)
  38682. 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]);
  38683. // Normalize to get normal, then scale to radius
  38684. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38685. // uv Coordinates from vertex ID
  38686. 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);
  38687. }
  38688. // Subdivide the face (interpolate pos, norm, uv)
  38689. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38690. // - norm is linear interpolation of vertex corner normal
  38691. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38692. // - uv is linear interpolation
  38693. //
  38694. // Topology is as below for sub-divide by 2
  38695. // vertex shown as v0,v1,v2
  38696. // interp index is i1 to progress in range [v0,v1[
  38697. // interp index is i2 to progress in range [v0,v2[
  38698. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38699. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38700. //
  38701. //
  38702. // i2 v2
  38703. // ^ ^
  38704. // / / \
  38705. // / / \
  38706. // / / \
  38707. // / / (0,1) \
  38708. // / #---------\
  38709. // / / \ (0,0)'/ \
  38710. // / / \ / \
  38711. // / / \ / \
  38712. // / / (0,0) \ / (1,0) \
  38713. // / #---------#---------\
  38714. // v0 v1
  38715. //
  38716. // --------------------> i1
  38717. //
  38718. // interp of (i1,i2):
  38719. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38720. // along i1 : lerp(x0,x1, i1/(S-i2))
  38721. //
  38722. // centroid of triangle is needed to get help normal computation
  38723. // (c1,c2) are used for centroid location
  38724. var interp_vertex = function (i1, i2, c1, c2) {
  38725. // vertex is interpolated from
  38726. // - face_vertex_pos[0..2]
  38727. // - face_vertex_uv[0..2]
  38728. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38729. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38730. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38731. pos_interp.normalize();
  38732. var vertex_normal;
  38733. if (flat) {
  38734. // in flat mode, recalculate normal as face centroid normal
  38735. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38736. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38737. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38738. }
  38739. else {
  38740. // in smooth mode, recalculate normal from each single vertex position
  38741. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38742. }
  38743. // Vertex normal need correction due to X,Y,Z radius scaling
  38744. vertex_normal.x /= radiusX;
  38745. vertex_normal.y /= radiusY;
  38746. vertex_normal.z /= radiusZ;
  38747. vertex_normal.normalize();
  38748. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38749. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38750. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38751. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38752. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38753. uvs.push(uv_interp.x, uv_interp.y);
  38754. // push each vertex has member of a face
  38755. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38756. indices.push(current_indice);
  38757. current_indice++;
  38758. };
  38759. for (var i2 = 0; i2 < subdivisions; i2++) {
  38760. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38761. // face : (i1,i2) for /\ :
  38762. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38763. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38764. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38765. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38766. if (i1 + i2 + 1 < subdivisions) {
  38767. // face : (i1,i2)' for \/ :
  38768. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38769. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38770. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38771. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38772. }
  38773. }
  38774. }
  38775. }
  38776. // Sides
  38777. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38778. // Result
  38779. var vertexData = new VertexData();
  38780. vertexData.indices = indices;
  38781. vertexData.positions = positions;
  38782. vertexData.normals = normals;
  38783. vertexData.uvs = uvs;
  38784. return vertexData;
  38785. };
  38786. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38787. /**
  38788. * Creates the VertexData for a Polyhedron
  38789. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38790. * * type provided types are:
  38791. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38792. * * 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)
  38793. * * size the size of the IcoSphere, optional default 1
  38794. * * sizeX allows stretching in the x direction, optional, default size
  38795. * * sizeY allows stretching in the y direction, optional, default size
  38796. * * sizeZ allows stretching in the z direction, optional, default size
  38797. * * 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
  38798. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38799. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38800. * * flat when true creates a flat shaded mesh, optional, default true
  38801. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38802. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38803. * * 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)
  38804. * * 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)
  38805. * @returns the VertexData of the Polyhedron
  38806. */
  38807. VertexData.CreatePolyhedron = function (options) {
  38808. // provided polyhedron types :
  38809. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38810. // 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)
  38811. var polyhedra = [];
  38812. 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]] };
  38813. 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]] };
  38814. polyhedra[2] = {
  38815. 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]],
  38816. 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]]
  38817. };
  38818. polyhedra[3] = {
  38819. 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]],
  38820. 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]]
  38821. };
  38822. polyhedra[4] = {
  38823. 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]],
  38824. 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]]
  38825. };
  38826. 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]] };
  38827. 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]] };
  38828. 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]] };
  38829. 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]] };
  38830. 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]] };
  38831. 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]] };
  38832. 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]] };
  38833. 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]] };
  38834. 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]] };
  38835. polyhedra[14] = {
  38836. 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]],
  38837. 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]]
  38838. };
  38839. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38840. var size = options.size;
  38841. var sizeX = options.sizeX || size || 1;
  38842. var sizeY = options.sizeY || size || 1;
  38843. var sizeZ = options.sizeZ || size || 1;
  38844. var data = options.custom || polyhedra[type];
  38845. var nbfaces = data.face.length;
  38846. var faceUV = options.faceUV || new Array(nbfaces);
  38847. var faceColors = options.faceColors;
  38848. var flat = (options.flat === undefined) ? true : options.flat;
  38849. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38850. var positions = new Array();
  38851. var indices = new Array();
  38852. var normals = new Array();
  38853. var uvs = new Array();
  38854. var colors = new Array();
  38855. var index = 0;
  38856. var faceIdx = 0; // face cursor in the array "indexes"
  38857. var indexes = new Array();
  38858. var i = 0;
  38859. var f = 0;
  38860. var u, v, ang, x, y, tmp;
  38861. // default face colors and UV if undefined
  38862. if (flat) {
  38863. for (f = 0; f < nbfaces; f++) {
  38864. if (faceColors && faceColors[f] === undefined) {
  38865. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38866. }
  38867. if (faceUV && faceUV[f] === undefined) {
  38868. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38869. }
  38870. }
  38871. }
  38872. if (!flat) {
  38873. for (i = 0; i < data.vertex.length; i++) {
  38874. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38875. uvs.push(0, 0);
  38876. }
  38877. for (f = 0; f < nbfaces; f++) {
  38878. for (i = 0; i < data.face[f].length - 2; i++) {
  38879. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38880. }
  38881. }
  38882. }
  38883. else {
  38884. for (f = 0; f < nbfaces; f++) {
  38885. var fl = data.face[f].length; // number of vertices of the current face
  38886. ang = 2 * Math.PI / fl;
  38887. x = 0.5 * Math.tan(ang / 2);
  38888. y = 0.5;
  38889. // positions, uvs, colors
  38890. for (i = 0; i < fl; i++) {
  38891. // positions
  38892. 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);
  38893. indexes.push(index);
  38894. index++;
  38895. // uvs
  38896. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38897. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38898. uvs.push(u, v);
  38899. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38900. y = x * Math.sin(ang) + y * Math.cos(ang);
  38901. x = tmp;
  38902. // colors
  38903. if (faceColors) {
  38904. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38905. }
  38906. }
  38907. // indices from indexes
  38908. for (i = 0; i < fl - 2; i++) {
  38909. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38910. }
  38911. faceIdx += fl;
  38912. }
  38913. }
  38914. VertexData.ComputeNormals(positions, indices, normals);
  38915. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38916. var vertexData = new VertexData();
  38917. vertexData.positions = positions;
  38918. vertexData.indices = indices;
  38919. vertexData.normals = normals;
  38920. vertexData.uvs = uvs;
  38921. if (faceColors && flat) {
  38922. vertexData.colors = colors;
  38923. }
  38924. return vertexData;
  38925. };
  38926. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38927. /**
  38928. * Creates the VertexData for a TorusKnot
  38929. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38930. * * radius the radius of the torus knot, optional, default 2
  38931. * * tube the thickness of the tube, optional, default 0.5
  38932. * * radialSegments the number of sides on each tube segments, optional, default 32
  38933. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38934. * * p the number of windings around the z axis, optional, default 2
  38935. * * q the number of windings around the x axis, optional, default 3
  38936. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38937. * * 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)
  38938. * * 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)
  38939. * @returns the VertexData of the Torus Knot
  38940. */
  38941. VertexData.CreateTorusKnot = function (options) {
  38942. var indices = new Array();
  38943. var positions = new Array();
  38944. var normals = new Array();
  38945. var uvs = new Array();
  38946. var radius = options.radius || 2;
  38947. var tube = options.tube || 0.5;
  38948. var radialSegments = options.radialSegments || 32;
  38949. var tubularSegments = options.tubularSegments || 32;
  38950. var p = options.p || 2;
  38951. var q = options.q || 3;
  38952. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38953. // Helper
  38954. var getPos = function (angle) {
  38955. var cu = Math.cos(angle);
  38956. var su = Math.sin(angle);
  38957. var quOverP = q / p * angle;
  38958. var cs = Math.cos(quOverP);
  38959. var tx = radius * (2 + cs) * 0.5 * cu;
  38960. var ty = radius * (2 + cs) * su * 0.5;
  38961. var tz = radius * Math.sin(quOverP) * 0.5;
  38962. return new BABYLON.Vector3(tx, ty, tz);
  38963. };
  38964. // Vertices
  38965. var i;
  38966. var j;
  38967. for (i = 0; i <= radialSegments; i++) {
  38968. var modI = i % radialSegments;
  38969. var u = modI / radialSegments * 2 * p * Math.PI;
  38970. var p1 = getPos(u);
  38971. var p2 = getPos(u + 0.01);
  38972. var tang = p2.subtract(p1);
  38973. var n = p2.add(p1);
  38974. var bitan = BABYLON.Vector3.Cross(tang, n);
  38975. n = BABYLON.Vector3.Cross(bitan, tang);
  38976. bitan.normalize();
  38977. n.normalize();
  38978. for (j = 0; j < tubularSegments; j++) {
  38979. var modJ = j % tubularSegments;
  38980. var v = modJ / tubularSegments * 2 * Math.PI;
  38981. var cx = -tube * Math.cos(v);
  38982. var cy = tube * Math.sin(v);
  38983. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38984. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38985. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38986. uvs.push(i / radialSegments);
  38987. uvs.push(j / tubularSegments);
  38988. }
  38989. }
  38990. for (i = 0; i < radialSegments; i++) {
  38991. for (j = 0; j < tubularSegments; j++) {
  38992. var jNext = (j + 1) % tubularSegments;
  38993. var a = i * tubularSegments + j;
  38994. var b = (i + 1) * tubularSegments + j;
  38995. var c = (i + 1) * tubularSegments + jNext;
  38996. var d = i * tubularSegments + jNext;
  38997. indices.push(d);
  38998. indices.push(b);
  38999. indices.push(a);
  39000. indices.push(d);
  39001. indices.push(c);
  39002. indices.push(b);
  39003. }
  39004. }
  39005. // Normals
  39006. VertexData.ComputeNormals(positions, indices, normals);
  39007. // Sides
  39008. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39009. // Result
  39010. var vertexData = new VertexData();
  39011. vertexData.indices = indices;
  39012. vertexData.positions = positions;
  39013. vertexData.normals = normals;
  39014. vertexData.uvs = uvs;
  39015. return vertexData;
  39016. };
  39017. // Tools
  39018. /**
  39019. * Compute normals for given positions and indices
  39020. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39021. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39022. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39023. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39024. * * facetNormals : optional array of facet normals (vector3)
  39025. * * facetPositions : optional array of facet positions (vector3)
  39026. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39027. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39028. * * bInfo : optional bounding info, required for facetPartitioning computation
  39029. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39030. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39031. * * useRightHandedSystem: optional boolean to for right handed system computation
  39032. * * depthSort : optional boolean to enable the facet depth sort computation
  39033. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39034. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39035. */
  39036. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39037. // temporary scalar variables
  39038. var index = 0; // facet index
  39039. var p1p2x = 0.0; // p1p2 vector x coordinate
  39040. var p1p2y = 0.0; // p1p2 vector y coordinate
  39041. var p1p2z = 0.0; // p1p2 vector z coordinate
  39042. var p3p2x = 0.0; // p3p2 vector x coordinate
  39043. var p3p2y = 0.0; // p3p2 vector y coordinate
  39044. var p3p2z = 0.0; // p3p2 vector z coordinate
  39045. var faceNormalx = 0.0; // facet normal x coordinate
  39046. var faceNormaly = 0.0; // facet normal y coordinate
  39047. var faceNormalz = 0.0; // facet normal z coordinate
  39048. var length = 0.0; // facet normal length before normalization
  39049. var v1x = 0; // vector1 x index in the positions array
  39050. var v1y = 0; // vector1 y index in the positions array
  39051. var v1z = 0; // vector1 z index in the positions array
  39052. var v2x = 0; // vector2 x index in the positions array
  39053. var v2y = 0; // vector2 y index in the positions array
  39054. var v2z = 0; // vector2 z index in the positions array
  39055. var v3x = 0; // vector3 x index in the positions array
  39056. var v3y = 0; // vector3 y index in the positions array
  39057. var v3z = 0; // vector3 z index in the positions array
  39058. var computeFacetNormals = false;
  39059. var computeFacetPositions = false;
  39060. var computeFacetPartitioning = false;
  39061. var computeDepthSort = false;
  39062. var faceNormalSign = 1;
  39063. var ratio = 0;
  39064. var distanceTo = null;
  39065. if (options) {
  39066. computeFacetNormals = (options.facetNormals) ? true : false;
  39067. computeFacetPositions = (options.facetPositions) ? true : false;
  39068. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39069. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39070. ratio = options.ratio || 0;
  39071. computeDepthSort = (options.depthSort) ? true : false;
  39072. distanceTo = (options.distanceTo);
  39073. if (computeDepthSort) {
  39074. if (distanceTo === undefined) {
  39075. distanceTo = BABYLON.Vector3.Zero();
  39076. }
  39077. var depthSortedFacets = options.depthSortedFacets;
  39078. }
  39079. }
  39080. // facetPartitioning reinit if needed
  39081. var xSubRatio = 0;
  39082. var ySubRatio = 0;
  39083. var zSubRatio = 0;
  39084. var subSq = 0;
  39085. if (computeFacetPartitioning && options && options.bbSize) {
  39086. var ox = 0; // X partitioning index for facet position
  39087. var oy = 0; // Y partinioning index for facet position
  39088. var oz = 0; // Z partinioning index for facet position
  39089. var b1x = 0; // X partitioning index for facet v1 vertex
  39090. var b1y = 0; // Y partitioning index for facet v1 vertex
  39091. var b1z = 0; // z partitioning index for facet v1 vertex
  39092. var b2x = 0; // X partitioning index for facet v2 vertex
  39093. var b2y = 0; // Y partitioning index for facet v2 vertex
  39094. var b2z = 0; // Z partitioning index for facet v2 vertex
  39095. var b3x = 0; // X partitioning index for facet v3 vertex
  39096. var b3y = 0; // Y partitioning index for facet v3 vertex
  39097. var b3z = 0; // Z partitioning index for facet v3 vertex
  39098. var block_idx_o = 0; // facet barycenter block index
  39099. var block_idx_v1 = 0; // v1 vertex block index
  39100. var block_idx_v2 = 0; // v2 vertex block index
  39101. var block_idx_v3 = 0; // v3 vertex block index
  39102. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39103. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39104. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39105. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39106. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39107. subSq = options.subDiv.max * options.subDiv.max;
  39108. options.facetPartitioning.length = 0;
  39109. }
  39110. // reset the normals
  39111. for (index = 0; index < positions.length; index++) {
  39112. normals[index] = 0.0;
  39113. }
  39114. // Loop : 1 indice triplet = 1 facet
  39115. var nbFaces = (indices.length / 3) | 0;
  39116. for (index = 0; index < nbFaces; index++) {
  39117. // get the indexes of the coordinates of each vertex of the facet
  39118. v1x = indices[index * 3] * 3;
  39119. v1y = v1x + 1;
  39120. v1z = v1x + 2;
  39121. v2x = indices[index * 3 + 1] * 3;
  39122. v2y = v2x + 1;
  39123. v2z = v2x + 2;
  39124. v3x = indices[index * 3 + 2] * 3;
  39125. v3y = v3x + 1;
  39126. v3z = v3x + 2;
  39127. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39128. p1p2y = positions[v1y] - positions[v2y];
  39129. p1p2z = positions[v1z] - positions[v2z];
  39130. p3p2x = positions[v3x] - positions[v2x];
  39131. p3p2y = positions[v3y] - positions[v2y];
  39132. p3p2z = positions[v3z] - positions[v2z];
  39133. // compute the face normal with the cross product
  39134. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39135. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39136. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39137. // normalize this normal and store it in the array facetData
  39138. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39139. length = (length === 0) ? 1.0 : length;
  39140. faceNormalx /= length;
  39141. faceNormaly /= length;
  39142. faceNormalz /= length;
  39143. if (computeFacetNormals && options) {
  39144. options.facetNormals[index].x = faceNormalx;
  39145. options.facetNormals[index].y = faceNormaly;
  39146. options.facetNormals[index].z = faceNormalz;
  39147. }
  39148. if (computeFacetPositions && options) {
  39149. // compute and the facet barycenter coordinates in the array facetPositions
  39150. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39151. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39152. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39153. }
  39154. if (computeFacetPartitioning && options) {
  39155. // store the facet indexes in arrays in the main facetPartitioning array :
  39156. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39157. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39158. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39159. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39160. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39161. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39162. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39163. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39164. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39165. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39166. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39167. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39168. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39169. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39170. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39171. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39172. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39173. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39174. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39175. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39176. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39177. // push each facet index in each block containing the vertex
  39178. options.facetPartitioning[block_idx_v1].push(index);
  39179. if (block_idx_v2 != block_idx_v1) {
  39180. options.facetPartitioning[block_idx_v2].push(index);
  39181. }
  39182. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39183. options.facetPartitioning[block_idx_v3].push(index);
  39184. }
  39185. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39186. options.facetPartitioning[block_idx_o].push(index);
  39187. }
  39188. }
  39189. if (computeDepthSort && options && options.facetPositions) {
  39190. var dsf = depthSortedFacets[index];
  39191. dsf.ind = index * 3;
  39192. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39193. }
  39194. // compute the normals anyway
  39195. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39196. normals[v1y] += faceNormaly;
  39197. normals[v1z] += faceNormalz;
  39198. normals[v2x] += faceNormalx;
  39199. normals[v2y] += faceNormaly;
  39200. normals[v2z] += faceNormalz;
  39201. normals[v3x] += faceNormalx;
  39202. normals[v3y] += faceNormaly;
  39203. normals[v3z] += faceNormalz;
  39204. }
  39205. // last normalization of each normal
  39206. for (index = 0; index < normals.length / 3; index++) {
  39207. faceNormalx = normals[index * 3];
  39208. faceNormaly = normals[index * 3 + 1];
  39209. faceNormalz = normals[index * 3 + 2];
  39210. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39211. length = (length === 0) ? 1.0 : length;
  39212. faceNormalx /= length;
  39213. faceNormaly /= length;
  39214. faceNormalz /= length;
  39215. normals[index * 3] = faceNormalx;
  39216. normals[index * 3 + 1] = faceNormaly;
  39217. normals[index * 3 + 2] = faceNormalz;
  39218. }
  39219. };
  39220. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39221. var li = indices.length;
  39222. var ln = normals.length;
  39223. var i;
  39224. var n;
  39225. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39226. switch (sideOrientation) {
  39227. case BABYLON.Mesh.FRONTSIDE:
  39228. // nothing changed
  39229. break;
  39230. case BABYLON.Mesh.BACKSIDE:
  39231. var tmp;
  39232. // indices
  39233. for (i = 0; i < li; i += 3) {
  39234. tmp = indices[i];
  39235. indices[i] = indices[i + 2];
  39236. indices[i + 2] = tmp;
  39237. }
  39238. // normals
  39239. for (n = 0; n < ln; n++) {
  39240. normals[n] = -normals[n];
  39241. }
  39242. break;
  39243. case BABYLON.Mesh.DOUBLESIDE:
  39244. // positions
  39245. var lp = positions.length;
  39246. var l = lp / 3;
  39247. for (var p = 0; p < lp; p++) {
  39248. positions[lp + p] = positions[p];
  39249. }
  39250. // indices
  39251. for (i = 0; i < li; i += 3) {
  39252. indices[i + li] = indices[i + 2] + l;
  39253. indices[i + 1 + li] = indices[i + 1] + l;
  39254. indices[i + 2 + li] = indices[i] + l;
  39255. }
  39256. // normals
  39257. for (n = 0; n < ln; n++) {
  39258. normals[ln + n] = -normals[n];
  39259. }
  39260. // uvs
  39261. var lu = uvs.length;
  39262. var u = 0;
  39263. for (u = 0; u < lu; u++) {
  39264. uvs[u + lu] = uvs[u];
  39265. }
  39266. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39267. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39268. u = 0;
  39269. for (i = 0; i < lu / 2; i++) {
  39270. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39271. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39272. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39273. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39274. u += 2;
  39275. }
  39276. break;
  39277. }
  39278. };
  39279. /**
  39280. * Applies VertexData created from the imported parameters to the geometry
  39281. * @param parsedVertexData the parsed data from an imported file
  39282. * @param geometry the geometry to apply the VertexData to
  39283. */
  39284. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39285. var vertexData = new VertexData();
  39286. // positions
  39287. var positions = parsedVertexData.positions;
  39288. if (positions) {
  39289. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39290. }
  39291. // normals
  39292. var normals = parsedVertexData.normals;
  39293. if (normals) {
  39294. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39295. }
  39296. // tangents
  39297. var tangents = parsedVertexData.tangents;
  39298. if (tangents) {
  39299. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39300. }
  39301. // uvs
  39302. var uvs = parsedVertexData.uvs;
  39303. if (uvs) {
  39304. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39305. }
  39306. // uv2s
  39307. var uv2s = parsedVertexData.uv2s;
  39308. if (uv2s) {
  39309. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39310. }
  39311. // uv3s
  39312. var uv3s = parsedVertexData.uv3s;
  39313. if (uv3s) {
  39314. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39315. }
  39316. // uv4s
  39317. var uv4s = parsedVertexData.uv4s;
  39318. if (uv4s) {
  39319. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39320. }
  39321. // uv5s
  39322. var uv5s = parsedVertexData.uv5s;
  39323. if (uv5s) {
  39324. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39325. }
  39326. // uv6s
  39327. var uv6s = parsedVertexData.uv6s;
  39328. if (uv6s) {
  39329. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39330. }
  39331. // colors
  39332. var colors = parsedVertexData.colors;
  39333. if (colors) {
  39334. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39335. }
  39336. // matricesIndices
  39337. var matricesIndices = parsedVertexData.matricesIndices;
  39338. if (matricesIndices) {
  39339. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39340. }
  39341. // matricesWeights
  39342. var matricesWeights = parsedVertexData.matricesWeights;
  39343. if (matricesWeights) {
  39344. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39345. }
  39346. // indices
  39347. var indices = parsedVertexData.indices;
  39348. if (indices) {
  39349. vertexData.indices = indices;
  39350. }
  39351. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39352. };
  39353. return VertexData;
  39354. }());
  39355. BABYLON.VertexData = VertexData;
  39356. })(BABYLON || (BABYLON = {}));
  39357. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39358. var BABYLON;
  39359. (function (BABYLON) {
  39360. /**
  39361. * Class used to store geometry data (vertex buffers + index buffer)
  39362. */
  39363. var Geometry = /** @class */ (function () {
  39364. /**
  39365. * Creates a new geometry
  39366. * @param id defines the unique ID
  39367. * @param scene defines the hosting scene
  39368. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39369. * @param updatable defines if geometry must be updatable (false by default)
  39370. * @param mesh defines the mesh that will be associated with the geometry
  39371. */
  39372. function Geometry(id, scene, vertexData, updatable, mesh) {
  39373. if (updatable === void 0) { updatable = false; }
  39374. if (mesh === void 0) { mesh = null; }
  39375. /**
  39376. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39377. */
  39378. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39379. this._totalVertices = 0;
  39380. this._isDisposed = false;
  39381. this._indexBufferIsUpdatable = false;
  39382. this.id = id;
  39383. this._engine = scene.getEngine();
  39384. this._meshes = [];
  39385. this._scene = scene;
  39386. //Init vertex buffer cache
  39387. this._vertexBuffers = {};
  39388. this._indices = [];
  39389. this._updatable = updatable;
  39390. // vertexData
  39391. if (vertexData) {
  39392. this.setAllVerticesData(vertexData, updatable);
  39393. }
  39394. else {
  39395. this._totalVertices = 0;
  39396. this._indices = [];
  39397. }
  39398. if (this._engine.getCaps().vertexArrayObject) {
  39399. this._vertexArrayObjects = {};
  39400. }
  39401. // applyToMesh
  39402. if (mesh) {
  39403. if (mesh.getClassName() === "LinesMesh") {
  39404. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39405. this._updateExtend();
  39406. }
  39407. this.applyToMesh(mesh);
  39408. mesh.computeWorldMatrix(true);
  39409. }
  39410. }
  39411. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39412. /**
  39413. * 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
  39414. */
  39415. get: function () {
  39416. return this._boundingBias;
  39417. },
  39418. /**
  39419. * 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
  39420. */
  39421. set: function (value) {
  39422. if (this._boundingBias && this._boundingBias.equals(value)) {
  39423. return;
  39424. }
  39425. this._boundingBias = value.clone();
  39426. this._updateBoundingInfo(true, null);
  39427. },
  39428. enumerable: true,
  39429. configurable: true
  39430. });
  39431. /**
  39432. * Static function used to attach a new empty geometry to a mesh
  39433. * @param mesh defines the mesh to attach the geometry to
  39434. * @returns the new {BABYLON.Geometry}
  39435. */
  39436. Geometry.CreateGeometryForMesh = function (mesh) {
  39437. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39438. geometry.applyToMesh(mesh);
  39439. return geometry;
  39440. };
  39441. Object.defineProperty(Geometry.prototype, "extend", {
  39442. /**
  39443. * Gets the current extend of the geometry
  39444. */
  39445. get: function () {
  39446. return this._extend;
  39447. },
  39448. enumerable: true,
  39449. configurable: true
  39450. });
  39451. /**
  39452. * Gets the hosting scene
  39453. * @returns the hosting {BABYLON.Scene}
  39454. */
  39455. Geometry.prototype.getScene = function () {
  39456. return this._scene;
  39457. };
  39458. /**
  39459. * Gets the hosting engine
  39460. * @returns the hosting {BABYLON.Engine}
  39461. */
  39462. Geometry.prototype.getEngine = function () {
  39463. return this._engine;
  39464. };
  39465. /**
  39466. * Defines if the geometry is ready to use
  39467. * @returns true if the geometry is ready to be used
  39468. */
  39469. Geometry.prototype.isReady = function () {
  39470. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39471. };
  39472. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39473. /**
  39474. * Gets a value indicating that the geometry should not be serialized
  39475. */
  39476. get: function () {
  39477. for (var index = 0; index < this._meshes.length; index++) {
  39478. if (!this._meshes[index].doNotSerialize) {
  39479. return false;
  39480. }
  39481. }
  39482. return true;
  39483. },
  39484. enumerable: true,
  39485. configurable: true
  39486. });
  39487. /** @hidden */
  39488. Geometry.prototype._rebuild = function () {
  39489. if (this._vertexArrayObjects) {
  39490. this._vertexArrayObjects = {};
  39491. }
  39492. // Index buffer
  39493. if (this._meshes.length !== 0 && this._indices) {
  39494. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39495. }
  39496. // Vertex buffers
  39497. for (var key in this._vertexBuffers) {
  39498. var vertexBuffer = this._vertexBuffers[key];
  39499. vertexBuffer._rebuild();
  39500. }
  39501. };
  39502. /**
  39503. * Affects all geometry data in one call
  39504. * @param vertexData defines the geometry data
  39505. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39506. */
  39507. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39508. vertexData.applyToGeometry(this, updatable);
  39509. this.notifyUpdate();
  39510. };
  39511. /**
  39512. * Set specific vertex data
  39513. * @param kind defines the data kind (Position, normal, etc...)
  39514. * @param data defines the vertex data to use
  39515. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39516. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39517. */
  39518. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39519. if (updatable === void 0) { updatable = false; }
  39520. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39521. this.setVerticesBuffer(buffer);
  39522. };
  39523. /**
  39524. * Removes a specific vertex data
  39525. * @param kind defines the data kind (Position, normal, etc...)
  39526. */
  39527. Geometry.prototype.removeVerticesData = function (kind) {
  39528. if (this._vertexBuffers[kind]) {
  39529. this._vertexBuffers[kind].dispose();
  39530. delete this._vertexBuffers[kind];
  39531. }
  39532. };
  39533. /**
  39534. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39535. * @param buffer defines the vertex buffer to use
  39536. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39537. */
  39538. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39539. if (totalVertices === void 0) { totalVertices = null; }
  39540. var kind = buffer.getKind();
  39541. if (this._vertexBuffers[kind]) {
  39542. this._vertexBuffers[kind].dispose();
  39543. }
  39544. this._vertexBuffers[kind] = buffer;
  39545. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39546. var data = buffer.getData();
  39547. if (totalVertices != null) {
  39548. this._totalVertices = totalVertices;
  39549. }
  39550. else {
  39551. if (data != null) {
  39552. this._totalVertices = data.length / (buffer.byteStride / 4);
  39553. }
  39554. }
  39555. this._updateExtend(data);
  39556. this._resetPointsArrayCache();
  39557. var meshes = this._meshes;
  39558. var numOfMeshes = meshes.length;
  39559. for (var index = 0; index < numOfMeshes; index++) {
  39560. var mesh = meshes[index];
  39561. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39562. mesh._createGlobalSubMesh(false);
  39563. mesh.computeWorldMatrix(true);
  39564. }
  39565. }
  39566. this.notifyUpdate(kind);
  39567. if (this._vertexArrayObjects) {
  39568. this._disposeVertexArrayObjects();
  39569. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39570. }
  39571. };
  39572. /**
  39573. * Update a specific vertex buffer
  39574. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39575. * It will do nothing if the buffer is not updatable
  39576. * @param kind defines the data kind (Position, normal, etc...)
  39577. * @param data defines the data to use
  39578. * @param offset defines the offset in the target buffer where to store the data
  39579. * @param useBytes set to true if the offset is in bytes
  39580. */
  39581. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39582. if (useBytes === void 0) { useBytes = false; }
  39583. var vertexBuffer = this.getVertexBuffer(kind);
  39584. if (!vertexBuffer) {
  39585. return;
  39586. }
  39587. vertexBuffer.updateDirectly(data, offset, useBytes);
  39588. this.notifyUpdate(kind);
  39589. };
  39590. /**
  39591. * Update a specific vertex buffer
  39592. * This function will create a new buffer if the current one is not updatable
  39593. * @param kind defines the data kind (Position, normal, etc...)
  39594. * @param data defines the data to use
  39595. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39596. */
  39597. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39598. if (updateExtends === void 0) { updateExtends = false; }
  39599. var vertexBuffer = this.getVertexBuffer(kind);
  39600. if (!vertexBuffer) {
  39601. return;
  39602. }
  39603. vertexBuffer.update(data);
  39604. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39605. this._updateBoundingInfo(updateExtends, data);
  39606. }
  39607. this.notifyUpdate(kind);
  39608. };
  39609. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39610. if (updateExtends) {
  39611. this._updateExtend(data);
  39612. }
  39613. var meshes = this._meshes;
  39614. var numOfMeshes = meshes.length;
  39615. this._resetPointsArrayCache();
  39616. for (var index = 0; index < numOfMeshes; index++) {
  39617. var mesh = meshes[index];
  39618. if (updateExtends) {
  39619. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39620. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39621. var subMesh = mesh.subMeshes[subIndex];
  39622. subMesh.refreshBoundingInfo();
  39623. }
  39624. }
  39625. }
  39626. };
  39627. /** @hidden */
  39628. Geometry.prototype._bind = function (effect, indexToBind) {
  39629. if (!effect) {
  39630. return;
  39631. }
  39632. if (indexToBind === undefined) {
  39633. indexToBind = this._indexBuffer;
  39634. }
  39635. var vbs = this.getVertexBuffers();
  39636. if (!vbs) {
  39637. return;
  39638. }
  39639. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39640. this._engine.bindBuffers(vbs, indexToBind, effect);
  39641. return;
  39642. }
  39643. // Using VAO
  39644. if (!this._vertexArrayObjects[effect.key]) {
  39645. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39646. }
  39647. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39648. };
  39649. /**
  39650. * Gets total number of vertices
  39651. * @returns the total number of vertices
  39652. */
  39653. Geometry.prototype.getTotalVertices = function () {
  39654. if (!this.isReady()) {
  39655. return 0;
  39656. }
  39657. return this._totalVertices;
  39658. };
  39659. /**
  39660. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39661. * @param kind defines the data kind (Position, normal, etc...)
  39662. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39663. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39664. * @returns a float array containing vertex data
  39665. */
  39666. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39667. var vertexBuffer = this.getVertexBuffer(kind);
  39668. if (!vertexBuffer) {
  39669. return null;
  39670. }
  39671. var data = vertexBuffer.getData();
  39672. if (!data) {
  39673. return null;
  39674. }
  39675. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39676. var count = this._totalVertices * vertexBuffer.getSize();
  39677. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39678. var copy_1 = new Array(count);
  39679. vertexBuffer.forEach(count, function (value, index) {
  39680. copy_1[index] = value;
  39681. });
  39682. return copy_1;
  39683. }
  39684. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39685. if (data instanceof Array) {
  39686. var offset = vertexBuffer.byteOffset / 4;
  39687. return BABYLON.Tools.Slice(data, offset, offset + count);
  39688. }
  39689. else if (data instanceof ArrayBuffer) {
  39690. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39691. }
  39692. else {
  39693. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39694. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39695. var result = new Float32Array(count);
  39696. var source = new Float32Array(data.buffer, offset, count);
  39697. result.set(source);
  39698. return result;
  39699. }
  39700. return new Float32Array(data.buffer, offset, count);
  39701. }
  39702. }
  39703. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39704. return BABYLON.Tools.Slice(data);
  39705. }
  39706. return data;
  39707. };
  39708. /**
  39709. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39710. * @param kind defines the data kind (Position, normal, etc...)
  39711. * @returns true if the vertex buffer with the specified kind is updatable
  39712. */
  39713. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39714. var vb = this._vertexBuffers[kind];
  39715. if (!vb) {
  39716. return false;
  39717. }
  39718. return vb.isUpdatable();
  39719. };
  39720. /**
  39721. * Gets a specific vertex buffer
  39722. * @param kind defines the data kind (Position, normal, etc...)
  39723. * @returns a {BABYLON.VertexBuffer}
  39724. */
  39725. Geometry.prototype.getVertexBuffer = function (kind) {
  39726. if (!this.isReady()) {
  39727. return null;
  39728. }
  39729. return this._vertexBuffers[kind];
  39730. };
  39731. /**
  39732. * Returns all vertex buffers
  39733. * @return an object holding all vertex buffers indexed by kind
  39734. */
  39735. Geometry.prototype.getVertexBuffers = function () {
  39736. if (!this.isReady()) {
  39737. return null;
  39738. }
  39739. return this._vertexBuffers;
  39740. };
  39741. /**
  39742. * Gets a boolean indicating if specific vertex buffer is present
  39743. * @param kind defines the data kind (Position, normal, etc...)
  39744. * @returns true if data is present
  39745. */
  39746. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39747. if (!this._vertexBuffers) {
  39748. if (this._delayInfo) {
  39749. return this._delayInfo.indexOf(kind) !== -1;
  39750. }
  39751. return false;
  39752. }
  39753. return this._vertexBuffers[kind] !== undefined;
  39754. };
  39755. /**
  39756. * Gets a list of all attached data kinds (Position, normal, etc...)
  39757. * @returns a list of string containing all kinds
  39758. */
  39759. Geometry.prototype.getVerticesDataKinds = function () {
  39760. var result = [];
  39761. var kind;
  39762. if (!this._vertexBuffers && this._delayInfo) {
  39763. for (kind in this._delayInfo) {
  39764. result.push(kind);
  39765. }
  39766. }
  39767. else {
  39768. for (kind in this._vertexBuffers) {
  39769. result.push(kind);
  39770. }
  39771. }
  39772. return result;
  39773. };
  39774. /**
  39775. * Update index buffer
  39776. * @param indices defines the indices to store in the index buffer
  39777. * @param offset defines the offset in the target buffer where to store the data
  39778. */
  39779. Geometry.prototype.updateIndices = function (indices, offset) {
  39780. if (!this._indexBuffer) {
  39781. return;
  39782. }
  39783. if (!this._indexBufferIsUpdatable) {
  39784. this.setIndices(indices, null, true);
  39785. }
  39786. else {
  39787. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39788. }
  39789. };
  39790. /**
  39791. * Creates a new index buffer
  39792. * @param indices defines the indices to store in the index buffer
  39793. * @param totalVertices defines the total number of vertices (could be null)
  39794. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39795. */
  39796. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39797. if (totalVertices === void 0) { totalVertices = null; }
  39798. if (updatable === void 0) { updatable = false; }
  39799. if (this._indexBuffer) {
  39800. this._engine._releaseBuffer(this._indexBuffer);
  39801. }
  39802. this._disposeVertexArrayObjects();
  39803. this._indices = indices;
  39804. this._indexBufferIsUpdatable = updatable;
  39805. if (this._meshes.length !== 0 && this._indices) {
  39806. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39807. }
  39808. if (totalVertices != undefined) { // including null and undefined
  39809. this._totalVertices = totalVertices;
  39810. }
  39811. var meshes = this._meshes;
  39812. var numOfMeshes = meshes.length;
  39813. for (var index = 0; index < numOfMeshes; index++) {
  39814. meshes[index]._createGlobalSubMesh(true);
  39815. }
  39816. this.notifyUpdate();
  39817. };
  39818. /**
  39819. * Return the total number of indices
  39820. * @returns the total number of indices
  39821. */
  39822. Geometry.prototype.getTotalIndices = function () {
  39823. if (!this.isReady()) {
  39824. return 0;
  39825. }
  39826. return this._indices.length;
  39827. };
  39828. /**
  39829. * Gets the index buffer array
  39830. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39831. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39832. * @returns the index buffer array
  39833. */
  39834. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39835. if (!this.isReady()) {
  39836. return null;
  39837. }
  39838. var orig = this._indices;
  39839. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39840. return orig;
  39841. }
  39842. else {
  39843. var len = orig.length;
  39844. var copy = [];
  39845. for (var i = 0; i < len; i++) {
  39846. copy.push(orig[i]);
  39847. }
  39848. return copy;
  39849. }
  39850. };
  39851. /**
  39852. * Gets the index buffer
  39853. * @return the index buffer
  39854. */
  39855. Geometry.prototype.getIndexBuffer = function () {
  39856. if (!this.isReady()) {
  39857. return null;
  39858. }
  39859. return this._indexBuffer;
  39860. };
  39861. /** @hidden */
  39862. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39863. if (effect === void 0) { effect = null; }
  39864. if (!effect || !this._vertexArrayObjects) {
  39865. return;
  39866. }
  39867. if (this._vertexArrayObjects[effect.key]) {
  39868. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39869. delete this._vertexArrayObjects[effect.key];
  39870. }
  39871. };
  39872. /**
  39873. * Release the associated resources for a specific mesh
  39874. * @param mesh defines the source mesh
  39875. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39876. */
  39877. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39878. var meshes = this._meshes;
  39879. var index = meshes.indexOf(mesh);
  39880. if (index === -1) {
  39881. return;
  39882. }
  39883. meshes.splice(index, 1);
  39884. mesh._geometry = null;
  39885. if (meshes.length === 0 && shouldDispose) {
  39886. this.dispose();
  39887. }
  39888. };
  39889. /**
  39890. * Apply current geometry to a given mesh
  39891. * @param mesh defines the mesh to apply geometry to
  39892. */
  39893. Geometry.prototype.applyToMesh = function (mesh) {
  39894. if (mesh._geometry === this) {
  39895. return;
  39896. }
  39897. var previousGeometry = mesh._geometry;
  39898. if (previousGeometry) {
  39899. previousGeometry.releaseForMesh(mesh);
  39900. }
  39901. var meshes = this._meshes;
  39902. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39903. mesh._geometry = this;
  39904. this._scene.pushGeometry(this);
  39905. meshes.push(mesh);
  39906. if (this.isReady()) {
  39907. this._applyToMesh(mesh);
  39908. }
  39909. else {
  39910. mesh._boundingInfo = this._boundingInfo;
  39911. }
  39912. };
  39913. Geometry.prototype._updateExtend = function (data) {
  39914. if (data === void 0) { data = null; }
  39915. if (!data) {
  39916. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39917. }
  39918. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39919. };
  39920. Geometry.prototype._applyToMesh = function (mesh) {
  39921. var numOfMeshes = this._meshes.length;
  39922. // vertexBuffers
  39923. for (var kind in this._vertexBuffers) {
  39924. if (numOfMeshes === 1) {
  39925. this._vertexBuffers[kind].create();
  39926. }
  39927. var buffer = this._vertexBuffers[kind].getBuffer();
  39928. if (buffer)
  39929. buffer.references = numOfMeshes;
  39930. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39931. if (!this._extend) {
  39932. this._updateExtend();
  39933. }
  39934. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39935. mesh._createGlobalSubMesh(false);
  39936. //bounding info was just created again, world matrix should be applied again.
  39937. mesh._updateBoundingInfo();
  39938. }
  39939. }
  39940. // indexBuffer
  39941. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39942. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39943. }
  39944. if (this._indexBuffer) {
  39945. this._indexBuffer.references = numOfMeshes;
  39946. }
  39947. };
  39948. Geometry.prototype.notifyUpdate = function (kind) {
  39949. if (this.onGeometryUpdated) {
  39950. this.onGeometryUpdated(this, kind);
  39951. }
  39952. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39953. var mesh = _a[_i];
  39954. mesh._markSubMeshesAsAttributesDirty();
  39955. }
  39956. };
  39957. /**
  39958. * Load the geometry if it was flagged as delay loaded
  39959. * @param scene defines the hosting scene
  39960. * @param onLoaded defines a callback called when the geometry is loaded
  39961. */
  39962. Geometry.prototype.load = function (scene, onLoaded) {
  39963. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39964. return;
  39965. }
  39966. if (this.isReady()) {
  39967. if (onLoaded) {
  39968. onLoaded();
  39969. }
  39970. return;
  39971. }
  39972. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39973. this._queueLoad(scene, onLoaded);
  39974. };
  39975. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39976. var _this = this;
  39977. if (!this.delayLoadingFile) {
  39978. return;
  39979. }
  39980. scene._addPendingData(this);
  39981. scene._loadFile(this.delayLoadingFile, function (data) {
  39982. if (!_this._delayLoadingFunction) {
  39983. return;
  39984. }
  39985. _this._delayLoadingFunction(JSON.parse(data), _this);
  39986. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39987. _this._delayInfo = [];
  39988. scene._removePendingData(_this);
  39989. var meshes = _this._meshes;
  39990. var numOfMeshes = meshes.length;
  39991. for (var index = 0; index < numOfMeshes; index++) {
  39992. _this._applyToMesh(meshes[index]);
  39993. }
  39994. if (onLoaded) {
  39995. onLoaded();
  39996. }
  39997. }, undefined, true);
  39998. };
  39999. /**
  40000. * Invert the geometry to move from a right handed system to a left handed one.
  40001. */
  40002. Geometry.prototype.toLeftHanded = function () {
  40003. // Flip faces
  40004. var tIndices = this.getIndices(false);
  40005. if (tIndices != null && tIndices.length > 0) {
  40006. for (var i = 0; i < tIndices.length; i += 3) {
  40007. var tTemp = tIndices[i + 0];
  40008. tIndices[i + 0] = tIndices[i + 2];
  40009. tIndices[i + 2] = tTemp;
  40010. }
  40011. this.setIndices(tIndices);
  40012. }
  40013. // Negate position.z
  40014. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40015. if (tPositions != null && tPositions.length > 0) {
  40016. for (var i = 0; i < tPositions.length; i += 3) {
  40017. tPositions[i + 2] = -tPositions[i + 2];
  40018. }
  40019. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40020. }
  40021. // Negate normal.z
  40022. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40023. if (tNormals != null && tNormals.length > 0) {
  40024. for (var i = 0; i < tNormals.length; i += 3) {
  40025. tNormals[i + 2] = -tNormals[i + 2];
  40026. }
  40027. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40028. }
  40029. };
  40030. // Cache
  40031. /** @hidden */
  40032. Geometry.prototype._resetPointsArrayCache = function () {
  40033. this._positions = null;
  40034. };
  40035. /** @hidden */
  40036. Geometry.prototype._generatePointsArray = function () {
  40037. if (this._positions)
  40038. return true;
  40039. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40040. if (!data || data.length === 0) {
  40041. return false;
  40042. }
  40043. this._positions = [];
  40044. for (var index = 0; index < data.length; index += 3) {
  40045. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40046. }
  40047. return true;
  40048. };
  40049. /**
  40050. * Gets a value indicating if the geometry is disposed
  40051. * @returns true if the geometry was disposed
  40052. */
  40053. Geometry.prototype.isDisposed = function () {
  40054. return this._isDisposed;
  40055. };
  40056. Geometry.prototype._disposeVertexArrayObjects = function () {
  40057. if (this._vertexArrayObjects) {
  40058. for (var kind in this._vertexArrayObjects) {
  40059. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40060. }
  40061. this._vertexArrayObjects = {};
  40062. }
  40063. };
  40064. /**
  40065. * Free all associated resources
  40066. */
  40067. Geometry.prototype.dispose = function () {
  40068. var meshes = this._meshes;
  40069. var numOfMeshes = meshes.length;
  40070. var index;
  40071. for (index = 0; index < numOfMeshes; index++) {
  40072. this.releaseForMesh(meshes[index]);
  40073. }
  40074. this._meshes = [];
  40075. this._disposeVertexArrayObjects();
  40076. for (var kind in this._vertexBuffers) {
  40077. this._vertexBuffers[kind].dispose();
  40078. }
  40079. this._vertexBuffers = {};
  40080. this._totalVertices = 0;
  40081. if (this._indexBuffer) {
  40082. this._engine._releaseBuffer(this._indexBuffer);
  40083. }
  40084. this._indexBuffer = null;
  40085. this._indices = [];
  40086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40087. this.delayLoadingFile = null;
  40088. this._delayLoadingFunction = null;
  40089. this._delayInfo = [];
  40090. this._boundingInfo = null;
  40091. this._scene.removeGeometry(this);
  40092. this._isDisposed = true;
  40093. };
  40094. /**
  40095. * Clone the current geometry into a new geometry
  40096. * @param id defines the unique ID of the new geometry
  40097. * @returns a new geometry object
  40098. */
  40099. Geometry.prototype.copy = function (id) {
  40100. var vertexData = new BABYLON.VertexData();
  40101. vertexData.indices = [];
  40102. var indices = this.getIndices();
  40103. if (indices) {
  40104. for (var index = 0; index < indices.length; index++) {
  40105. vertexData.indices.push(indices[index]);
  40106. }
  40107. }
  40108. var updatable = false;
  40109. var stopChecking = false;
  40110. var kind;
  40111. for (kind in this._vertexBuffers) {
  40112. // using slice() to make a copy of the array and not just reference it
  40113. var data = this.getVerticesData(kind);
  40114. if (data instanceof Float32Array) {
  40115. vertexData.set(new Float32Array(data), kind);
  40116. }
  40117. else {
  40118. vertexData.set(data.slice(0), kind);
  40119. }
  40120. if (!stopChecking) {
  40121. var vb = this.getVertexBuffer(kind);
  40122. if (vb) {
  40123. updatable = vb.isUpdatable();
  40124. stopChecking = !updatable;
  40125. }
  40126. }
  40127. }
  40128. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40129. geometry.delayLoadState = this.delayLoadState;
  40130. geometry.delayLoadingFile = this.delayLoadingFile;
  40131. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40132. for (kind in this._delayInfo) {
  40133. geometry._delayInfo = geometry._delayInfo || [];
  40134. geometry._delayInfo.push(kind);
  40135. }
  40136. // Bounding info
  40137. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40138. return geometry;
  40139. };
  40140. /**
  40141. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40142. * @return a JSON representation of the current geometry data (without the vertices data)
  40143. */
  40144. Geometry.prototype.serialize = function () {
  40145. var serializationObject = {};
  40146. serializationObject.id = this.id;
  40147. serializationObject.updatable = this._updatable;
  40148. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40149. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40150. }
  40151. return serializationObject;
  40152. };
  40153. Geometry.prototype.toNumberArray = function (origin) {
  40154. if (Array.isArray(origin)) {
  40155. return origin;
  40156. }
  40157. else {
  40158. return Array.prototype.slice.call(origin);
  40159. }
  40160. };
  40161. /**
  40162. * Serialize all vertices data into a JSON oject
  40163. * @returns a JSON representation of the current geometry data
  40164. */
  40165. Geometry.prototype.serializeVerticeData = function () {
  40166. var serializationObject = this.serialize();
  40167. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40168. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40169. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40170. serializationObject.positions._updatable = true;
  40171. }
  40172. }
  40173. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40174. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40175. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40176. serializationObject.normals._updatable = true;
  40177. }
  40178. }
  40179. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40180. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40181. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40182. serializationObject.tangets._updatable = true;
  40183. }
  40184. }
  40185. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40186. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40187. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40188. serializationObject.uvs._updatable = true;
  40189. }
  40190. }
  40191. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40192. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40193. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40194. serializationObject.uv2s._updatable = true;
  40195. }
  40196. }
  40197. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40198. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40199. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40200. serializationObject.uv3s._updatable = true;
  40201. }
  40202. }
  40203. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40204. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40205. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40206. serializationObject.uv4s._updatable = true;
  40207. }
  40208. }
  40209. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40210. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40211. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40212. serializationObject.uv5s._updatable = true;
  40213. }
  40214. }
  40215. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40216. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40217. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40218. serializationObject.uv6s._updatable = true;
  40219. }
  40220. }
  40221. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40222. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40223. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40224. serializationObject.colors._updatable = true;
  40225. }
  40226. }
  40227. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40228. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40229. serializationObject.matricesIndices._isExpanded = true;
  40230. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40231. serializationObject.matricesIndices._updatable = true;
  40232. }
  40233. }
  40234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40235. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40236. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40237. serializationObject.matricesWeights._updatable = true;
  40238. }
  40239. }
  40240. serializationObject.indices = this.toNumberArray(this.getIndices());
  40241. return serializationObject;
  40242. };
  40243. // Statics
  40244. /**
  40245. * Extracts a clone of a mesh geometry
  40246. * @param mesh defines the source mesh
  40247. * @param id defines the unique ID of the new geometry object
  40248. * @returns the new geometry object
  40249. */
  40250. Geometry.ExtractFromMesh = function (mesh, id) {
  40251. var geometry = mesh._geometry;
  40252. if (!geometry) {
  40253. return null;
  40254. }
  40255. return geometry.copy(id);
  40256. };
  40257. /**
  40258. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40259. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40260. * Be aware Math.random() could cause collisions, but:
  40261. * "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"
  40262. * @returns a string containing a new GUID
  40263. */
  40264. Geometry.RandomId = function () {
  40265. return BABYLON.Tools.RandomId();
  40266. };
  40267. /** @hidden */
  40268. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40269. var scene = mesh.getScene();
  40270. // Geometry
  40271. var geometryId = parsedGeometry.geometryId;
  40272. if (geometryId) {
  40273. var geometry = scene.getGeometryByID(geometryId);
  40274. if (geometry) {
  40275. geometry.applyToMesh(mesh);
  40276. }
  40277. }
  40278. else if (parsedGeometry instanceof ArrayBuffer) {
  40279. var binaryInfo = mesh._binaryInfo;
  40280. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40281. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40282. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40283. }
  40284. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40285. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40286. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40287. }
  40288. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40289. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40290. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40291. }
  40292. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40293. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40294. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40295. }
  40296. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40297. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40298. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40299. }
  40300. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40301. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40302. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40303. }
  40304. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40305. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40306. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40307. }
  40308. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40309. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40310. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40311. }
  40312. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40313. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40314. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40315. }
  40316. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40317. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40318. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40319. }
  40320. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40321. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40322. var floatIndices = [];
  40323. for (var i = 0; i < matricesIndicesData.length; i++) {
  40324. var index = matricesIndicesData[i];
  40325. floatIndices.push(index & 0x000000FF);
  40326. floatIndices.push((index & 0x0000FF00) >> 8);
  40327. floatIndices.push((index & 0x00FF0000) >> 16);
  40328. floatIndices.push(index >> 24);
  40329. }
  40330. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40331. }
  40332. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40333. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40334. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40335. }
  40336. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40337. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40338. mesh.setIndices(indicesData, null);
  40339. }
  40340. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40341. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40342. mesh.subMeshes = [];
  40343. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40344. var materialIndex = subMeshesData[(i * 5) + 0];
  40345. var verticesStart = subMeshesData[(i * 5) + 1];
  40346. var verticesCount = subMeshesData[(i * 5) + 2];
  40347. var indexStart = subMeshesData[(i * 5) + 3];
  40348. var indexCount = subMeshesData[(i * 5) + 4];
  40349. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40350. }
  40351. }
  40352. }
  40353. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40354. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40355. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40356. if (parsedGeometry.tangents) {
  40357. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40358. }
  40359. if (parsedGeometry.uvs) {
  40360. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40361. }
  40362. if (parsedGeometry.uvs2) {
  40363. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40364. }
  40365. if (parsedGeometry.uvs3) {
  40366. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40367. }
  40368. if (parsedGeometry.uvs4) {
  40369. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40370. }
  40371. if (parsedGeometry.uvs5) {
  40372. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40373. }
  40374. if (parsedGeometry.uvs6) {
  40375. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40376. }
  40377. if (parsedGeometry.colors) {
  40378. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40379. }
  40380. if (parsedGeometry.matricesIndices) {
  40381. if (!parsedGeometry.matricesIndices._isExpanded) {
  40382. var floatIndices = [];
  40383. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40384. var matricesIndex = parsedGeometry.matricesIndices[i];
  40385. floatIndices.push(matricesIndex & 0x000000FF);
  40386. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40387. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40388. floatIndices.push(matricesIndex >> 24);
  40389. }
  40390. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40391. }
  40392. else {
  40393. delete parsedGeometry.matricesIndices._isExpanded;
  40394. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40395. }
  40396. }
  40397. if (parsedGeometry.matricesIndicesExtra) {
  40398. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40399. var floatIndices = [];
  40400. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40401. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40402. floatIndices.push(matricesIndex & 0x000000FF);
  40403. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40404. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40405. floatIndices.push(matricesIndex >> 24);
  40406. }
  40407. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40408. }
  40409. else {
  40410. delete parsedGeometry.matricesIndices._isExpanded;
  40411. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40412. }
  40413. }
  40414. if (parsedGeometry.matricesWeights) {
  40415. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40416. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40417. }
  40418. if (parsedGeometry.matricesWeightsExtra) {
  40419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40420. }
  40421. mesh.setIndices(parsedGeometry.indices, null);
  40422. }
  40423. // SubMeshes
  40424. if (parsedGeometry.subMeshes) {
  40425. mesh.subMeshes = [];
  40426. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40427. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40428. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40429. }
  40430. }
  40431. // Flat shading
  40432. if (mesh._shouldGenerateFlatShading) {
  40433. mesh.convertToFlatShadedMesh();
  40434. delete mesh._shouldGenerateFlatShading;
  40435. }
  40436. // Update
  40437. mesh.computeWorldMatrix(true);
  40438. scene.onMeshImportedObservable.notifyObservers(mesh);
  40439. };
  40440. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40441. var epsilon = 1e-3;
  40442. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40443. return;
  40444. }
  40445. var noInfluenceBoneIndex = 0.0;
  40446. if (parsedGeometry.skeletonId > -1) {
  40447. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40448. if (!skeleton) {
  40449. return;
  40450. }
  40451. noInfluenceBoneIndex = skeleton.bones.length;
  40452. }
  40453. else {
  40454. return;
  40455. }
  40456. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40457. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40458. var matricesWeights = parsedGeometry.matricesWeights;
  40459. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40460. var influencers = parsedGeometry.numBoneInfluencer;
  40461. var size = matricesWeights.length;
  40462. for (var i = 0; i < size; i += 4) {
  40463. var weight = 0.0;
  40464. var firstZeroWeight = -1;
  40465. for (var j = 0; j < 4; j++) {
  40466. var w = matricesWeights[i + j];
  40467. weight += w;
  40468. if (w < epsilon && firstZeroWeight < 0) {
  40469. firstZeroWeight = j;
  40470. }
  40471. }
  40472. if (matricesWeightsExtra) {
  40473. for (var j = 0; j < 4; j++) {
  40474. var w = matricesWeightsExtra[i + j];
  40475. weight += w;
  40476. if (w < epsilon && firstZeroWeight < 0) {
  40477. firstZeroWeight = j + 4;
  40478. }
  40479. }
  40480. }
  40481. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40482. firstZeroWeight = influencers - 1;
  40483. }
  40484. if (weight > epsilon) {
  40485. var mweight = 1.0 / weight;
  40486. for (var j = 0; j < 4; j++) {
  40487. matricesWeights[i + j] *= mweight;
  40488. }
  40489. if (matricesWeightsExtra) {
  40490. for (var j = 0; j < 4; j++) {
  40491. matricesWeightsExtra[i + j] *= mweight;
  40492. }
  40493. }
  40494. }
  40495. else {
  40496. if (firstZeroWeight >= 4) {
  40497. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40498. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40499. }
  40500. else {
  40501. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40502. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40503. }
  40504. }
  40505. }
  40506. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40507. if (parsedGeometry.matricesWeightsExtra) {
  40508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40509. }
  40510. };
  40511. /**
  40512. * Create a new geometry from persisted data (Using .babylon file format)
  40513. * @param parsedVertexData defines the persisted data
  40514. * @param scene defines the hosting scene
  40515. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40516. * @returns the new geometry object
  40517. */
  40518. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40519. if (scene.getGeometryByID(parsedVertexData.id)) {
  40520. return null; // null since geometry could be something else than a box...
  40521. }
  40522. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40523. if (BABYLON.Tags) {
  40524. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40525. }
  40526. if (parsedVertexData.delayLoadingFile) {
  40527. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40528. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40529. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40530. geometry._delayInfo = [];
  40531. if (parsedVertexData.hasUVs) {
  40532. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40533. }
  40534. if (parsedVertexData.hasUVs2) {
  40535. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40536. }
  40537. if (parsedVertexData.hasUVs3) {
  40538. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40539. }
  40540. if (parsedVertexData.hasUVs4) {
  40541. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40542. }
  40543. if (parsedVertexData.hasUVs5) {
  40544. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40545. }
  40546. if (parsedVertexData.hasUVs6) {
  40547. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40548. }
  40549. if (parsedVertexData.hasColors) {
  40550. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40551. }
  40552. if (parsedVertexData.hasMatricesIndices) {
  40553. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40554. }
  40555. if (parsedVertexData.hasMatricesWeights) {
  40556. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40557. }
  40558. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40559. }
  40560. else {
  40561. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40562. }
  40563. scene.pushGeometry(geometry, true);
  40564. return geometry;
  40565. };
  40566. return Geometry;
  40567. }());
  40568. BABYLON.Geometry = Geometry;
  40569. // Primitives
  40570. /// Abstract class
  40571. /**
  40572. * Abstract class used to provide common services for all typed geometries
  40573. * @hidden
  40574. */
  40575. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40576. __extends(_PrimitiveGeometry, _super);
  40577. /**
  40578. * Creates a new typed geometry
  40579. * @param id defines the unique ID of the geometry
  40580. * @param scene defines the hosting scene
  40581. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40582. * @param mesh defines the hosting mesh (can be null)
  40583. */
  40584. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40585. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40586. if (mesh === void 0) { mesh = null; }
  40587. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40588. _this._canBeRegenerated = _canBeRegenerated;
  40589. _this._beingRegenerated = true;
  40590. _this.regenerate();
  40591. _this._beingRegenerated = false;
  40592. return _this;
  40593. }
  40594. /**
  40595. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40596. * @returns true if the geometry can be regenerated
  40597. */
  40598. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40599. return this._canBeRegenerated;
  40600. };
  40601. /**
  40602. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40603. */
  40604. _PrimitiveGeometry.prototype.regenerate = function () {
  40605. if (!this._canBeRegenerated) {
  40606. return;
  40607. }
  40608. this._beingRegenerated = true;
  40609. this.setAllVerticesData(this._regenerateVertexData(), false);
  40610. this._beingRegenerated = false;
  40611. };
  40612. /**
  40613. * Clone the geometry
  40614. * @param id defines the unique ID of the new geometry
  40615. * @returns the new geometry
  40616. */
  40617. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40618. return _super.prototype.copy.call(this, id);
  40619. };
  40620. // overrides
  40621. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40622. if (!this._beingRegenerated) {
  40623. return;
  40624. }
  40625. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40626. };
  40627. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40628. if (!this._beingRegenerated) {
  40629. return;
  40630. }
  40631. _super.prototype.setVerticesData.call(this, kind, data, false);
  40632. };
  40633. // to override
  40634. /** @hidden */
  40635. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40636. throw new Error("Abstract method");
  40637. };
  40638. _PrimitiveGeometry.prototype.copy = function (id) {
  40639. throw new Error("Must be overriden in sub-classes.");
  40640. };
  40641. _PrimitiveGeometry.prototype.serialize = function () {
  40642. var serializationObject = _super.prototype.serialize.call(this);
  40643. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40644. return serializationObject;
  40645. };
  40646. return _PrimitiveGeometry;
  40647. }(Geometry));
  40648. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40649. /**
  40650. * Creates a ribbon geometry
  40651. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40652. */
  40653. var RibbonGeometry = /** @class */ (function (_super) {
  40654. __extends(RibbonGeometry, _super);
  40655. /**
  40656. * Creates a ribbon geometry
  40657. * @param id defines the unique ID of the geometry
  40658. * @param scene defines the hosting scene
  40659. * @param pathArray defines the array of paths to use
  40660. * @param closeArray defines if the last path and the first path must be joined
  40661. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40662. * @param offset defines the offset between points
  40663. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40664. * @param mesh defines the hosting mesh (can be null)
  40665. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40666. */
  40667. function RibbonGeometry(id, scene,
  40668. /**
  40669. * Defines the array of paths to use
  40670. */
  40671. pathArray,
  40672. /**
  40673. * Defines if the last and first points of each path in your pathArray must be joined
  40674. */
  40675. closeArray,
  40676. /**
  40677. * Defines if the last and first points of each path in your pathArray must be joined
  40678. */
  40679. closePath,
  40680. /**
  40681. * Defines the offset between points
  40682. */
  40683. offset, canBeRegenerated, mesh,
  40684. /**
  40685. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40686. */
  40687. side) {
  40688. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40689. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40690. _this.pathArray = pathArray;
  40691. _this.closeArray = closeArray;
  40692. _this.closePath = closePath;
  40693. _this.offset = offset;
  40694. _this.side = side;
  40695. return _this;
  40696. }
  40697. /** @hidden */
  40698. RibbonGeometry.prototype._regenerateVertexData = function () {
  40699. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40700. };
  40701. RibbonGeometry.prototype.copy = function (id) {
  40702. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40703. };
  40704. return RibbonGeometry;
  40705. }(_PrimitiveGeometry));
  40706. BABYLON.RibbonGeometry = RibbonGeometry;
  40707. /**
  40708. * Creates a box geometry
  40709. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40710. */
  40711. var BoxGeometry = /** @class */ (function (_super) {
  40712. __extends(BoxGeometry, _super);
  40713. /**
  40714. * Creates a box geometry
  40715. * @param id defines the unique ID of the geometry
  40716. * @param scene defines the hosting scene
  40717. * @param size defines the zise of the box (width, height and depth are the same)
  40718. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40719. * @param mesh defines the hosting mesh (can be null)
  40720. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40721. */
  40722. function BoxGeometry(id, scene,
  40723. /**
  40724. * Defines the zise of the box (width, height and depth are the same)
  40725. */
  40726. size, canBeRegenerated, mesh,
  40727. /**
  40728. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40729. */
  40730. side) {
  40731. if (mesh === void 0) { mesh = null; }
  40732. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40733. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40734. _this.size = size;
  40735. _this.side = side;
  40736. return _this;
  40737. }
  40738. /** @hidden */
  40739. BoxGeometry.prototype._regenerateVertexData = function () {
  40740. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40741. };
  40742. BoxGeometry.prototype.copy = function (id) {
  40743. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40744. };
  40745. BoxGeometry.prototype.serialize = function () {
  40746. var serializationObject = _super.prototype.serialize.call(this);
  40747. serializationObject.size = this.size;
  40748. return serializationObject;
  40749. };
  40750. BoxGeometry.Parse = function (parsedBox, scene) {
  40751. if (scene.getGeometryByID(parsedBox.id)) {
  40752. return null; // null since geometry could be something else than a box...
  40753. }
  40754. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40755. if (BABYLON.Tags) {
  40756. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40757. }
  40758. scene.pushGeometry(box, true);
  40759. return box;
  40760. };
  40761. return BoxGeometry;
  40762. }(_PrimitiveGeometry));
  40763. BABYLON.BoxGeometry = BoxGeometry;
  40764. /**
  40765. * Creates a sphere geometry
  40766. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40767. */
  40768. var SphereGeometry = /** @class */ (function (_super) {
  40769. __extends(SphereGeometry, _super);
  40770. /**
  40771. * Create a new sphere geometry
  40772. * @param id defines the unique ID of the geometry
  40773. * @param scene defines the hosting scene
  40774. * @param segments defines the number of segments to use to create the sphere
  40775. * @param diameter defines the diameter of the sphere
  40776. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40777. * @param mesh defines the hosting mesh (can be null)
  40778. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40779. */
  40780. function SphereGeometry(id, scene,
  40781. /**
  40782. * Defines the number of segments to use to create the sphere
  40783. */
  40784. segments,
  40785. /**
  40786. * Defines the diameter of the sphere
  40787. */
  40788. diameter, canBeRegenerated, mesh,
  40789. /**
  40790. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40791. */
  40792. side) {
  40793. if (mesh === void 0) { mesh = null; }
  40794. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40795. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40796. _this.segments = segments;
  40797. _this.diameter = diameter;
  40798. _this.side = side;
  40799. return _this;
  40800. }
  40801. /** @hidden */
  40802. SphereGeometry.prototype._regenerateVertexData = function () {
  40803. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40804. };
  40805. SphereGeometry.prototype.copy = function (id) {
  40806. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40807. };
  40808. SphereGeometry.prototype.serialize = function () {
  40809. var serializationObject = _super.prototype.serialize.call(this);
  40810. serializationObject.segments = this.segments;
  40811. serializationObject.diameter = this.diameter;
  40812. return serializationObject;
  40813. };
  40814. SphereGeometry.Parse = function (parsedSphere, scene) {
  40815. if (scene.getGeometryByID(parsedSphere.id)) {
  40816. return null; // null since geometry could be something else than a sphere...
  40817. }
  40818. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40819. if (BABYLON.Tags) {
  40820. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40821. }
  40822. scene.pushGeometry(sphere, true);
  40823. return sphere;
  40824. };
  40825. return SphereGeometry;
  40826. }(_PrimitiveGeometry));
  40827. BABYLON.SphereGeometry = SphereGeometry;
  40828. /**
  40829. * Creates a disc geometry
  40830. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40831. */
  40832. var DiscGeometry = /** @class */ (function (_super) {
  40833. __extends(DiscGeometry, _super);
  40834. /**
  40835. * Creates a new disc geometry
  40836. * @param id defines the unique ID of the geometry
  40837. * @param scene defines the hosting scene
  40838. * @param radius defines the radius of the disc
  40839. * @param tessellation defines the tesselation factor to apply to the disc
  40840. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40841. * @param mesh defines the hosting mesh (can be null)
  40842. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40843. */
  40844. function DiscGeometry(id, scene,
  40845. /**
  40846. * Defines the radius of the disc
  40847. */
  40848. radius,
  40849. /**
  40850. * Defines the tesselation factor to apply to the disc
  40851. */
  40852. tessellation, canBeRegenerated, mesh,
  40853. /**
  40854. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40855. */
  40856. side) {
  40857. if (mesh === void 0) { mesh = null; }
  40858. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40859. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40860. _this.radius = radius;
  40861. _this.tessellation = tessellation;
  40862. _this.side = side;
  40863. return _this;
  40864. }
  40865. /** @hidden */
  40866. DiscGeometry.prototype._regenerateVertexData = function () {
  40867. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40868. };
  40869. DiscGeometry.prototype.copy = function (id) {
  40870. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40871. };
  40872. return DiscGeometry;
  40873. }(_PrimitiveGeometry));
  40874. BABYLON.DiscGeometry = DiscGeometry;
  40875. /**
  40876. * Creates a new cylinder geometry
  40877. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40878. */
  40879. var CylinderGeometry = /** @class */ (function (_super) {
  40880. __extends(CylinderGeometry, _super);
  40881. /**
  40882. * Creates a new cylinder geometry
  40883. * @param id defines the unique ID of the geometry
  40884. * @param scene defines the hosting scene
  40885. * @param height defines the height of the cylinder
  40886. * @param diameterTop defines the diameter of the cylinder's top cap
  40887. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40888. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40889. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40890. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40891. * @param mesh defines the hosting mesh (can be null)
  40892. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40893. */
  40894. function CylinderGeometry(id, scene,
  40895. /**
  40896. * Defines the height of the cylinder
  40897. */
  40898. height,
  40899. /**
  40900. * Defines the diameter of the cylinder's top cap
  40901. */
  40902. diameterTop,
  40903. /**
  40904. * Defines the diameter of the cylinder's bottom cap
  40905. */
  40906. diameterBottom,
  40907. /**
  40908. * Defines the tessellation factor to apply to the cylinder
  40909. */
  40910. tessellation,
  40911. /**
  40912. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40913. */
  40914. subdivisions, canBeRegenerated, mesh,
  40915. /**
  40916. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40917. */
  40918. side) {
  40919. if (subdivisions === void 0) { subdivisions = 1; }
  40920. if (mesh === void 0) { mesh = null; }
  40921. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40922. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40923. _this.height = height;
  40924. _this.diameterTop = diameterTop;
  40925. _this.diameterBottom = diameterBottom;
  40926. _this.tessellation = tessellation;
  40927. _this.subdivisions = subdivisions;
  40928. _this.side = side;
  40929. return _this;
  40930. }
  40931. /** @hidden */
  40932. CylinderGeometry.prototype._regenerateVertexData = function () {
  40933. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40934. };
  40935. CylinderGeometry.prototype.copy = function (id) {
  40936. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40937. };
  40938. CylinderGeometry.prototype.serialize = function () {
  40939. var serializationObject = _super.prototype.serialize.call(this);
  40940. serializationObject.height = this.height;
  40941. serializationObject.diameterTop = this.diameterTop;
  40942. serializationObject.diameterBottom = this.diameterBottom;
  40943. serializationObject.tessellation = this.tessellation;
  40944. return serializationObject;
  40945. };
  40946. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40947. if (scene.getGeometryByID(parsedCylinder.id)) {
  40948. return null; // null since geometry could be something else than a cylinder...
  40949. }
  40950. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40951. if (BABYLON.Tags) {
  40952. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40953. }
  40954. scene.pushGeometry(cylinder, true);
  40955. return cylinder;
  40956. };
  40957. return CylinderGeometry;
  40958. }(_PrimitiveGeometry));
  40959. BABYLON.CylinderGeometry = CylinderGeometry;
  40960. /**
  40961. * Creates a new torus geometry
  40962. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40963. */
  40964. var TorusGeometry = /** @class */ (function (_super) {
  40965. __extends(TorusGeometry, _super);
  40966. /**
  40967. * Creates a new torus geometry
  40968. * @param id defines the unique ID of the geometry
  40969. * @param scene defines the hosting scene
  40970. * @param diameter defines the diameter of the torus
  40971. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40972. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40973. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40974. * @param mesh defines the hosting mesh (can be null)
  40975. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40976. */
  40977. function TorusGeometry(id, scene,
  40978. /**
  40979. * Defines the diameter of the torus
  40980. */
  40981. diameter,
  40982. /**
  40983. * Defines the thickness of the torus (ie. internal diameter)
  40984. */
  40985. thickness,
  40986. /**
  40987. * Defines the tesselation factor to apply to the torus
  40988. */
  40989. tessellation, canBeRegenerated, mesh,
  40990. /**
  40991. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40992. */
  40993. side) {
  40994. if (mesh === void 0) { mesh = null; }
  40995. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40996. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40997. _this.diameter = diameter;
  40998. _this.thickness = thickness;
  40999. _this.tessellation = tessellation;
  41000. _this.side = side;
  41001. return _this;
  41002. }
  41003. /** @hidden */
  41004. TorusGeometry.prototype._regenerateVertexData = function () {
  41005. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41006. };
  41007. TorusGeometry.prototype.copy = function (id) {
  41008. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41009. };
  41010. TorusGeometry.prototype.serialize = function () {
  41011. var serializationObject = _super.prototype.serialize.call(this);
  41012. serializationObject.diameter = this.diameter;
  41013. serializationObject.thickness = this.thickness;
  41014. serializationObject.tessellation = this.tessellation;
  41015. return serializationObject;
  41016. };
  41017. TorusGeometry.Parse = function (parsedTorus, scene) {
  41018. if (scene.getGeometryByID(parsedTorus.id)) {
  41019. return null; // null since geometry could be something else than a torus...
  41020. }
  41021. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41022. if (BABYLON.Tags) {
  41023. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41024. }
  41025. scene.pushGeometry(torus, true);
  41026. return torus;
  41027. };
  41028. return TorusGeometry;
  41029. }(_PrimitiveGeometry));
  41030. BABYLON.TorusGeometry = TorusGeometry;
  41031. /**
  41032. * Creates a new ground geometry
  41033. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41034. */
  41035. var GroundGeometry = /** @class */ (function (_super) {
  41036. __extends(GroundGeometry, _super);
  41037. /**
  41038. * Creates a new ground geometry
  41039. * @param id defines the unique ID of the geometry
  41040. * @param scene defines the hosting scene
  41041. * @param width defines the width of the ground
  41042. * @param height defines the height of the ground
  41043. * @param subdivisions defines the subdivisions to apply to the ground
  41044. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41045. * @param mesh defines the hosting mesh (can be null)
  41046. */
  41047. function GroundGeometry(id, scene,
  41048. /**
  41049. * Defines the width of the ground
  41050. */
  41051. width,
  41052. /**
  41053. * Defines the height of the ground
  41054. */
  41055. height,
  41056. /**
  41057. * Defines the subdivisions to apply to the ground
  41058. */
  41059. subdivisions, canBeRegenerated, mesh) {
  41060. if (mesh === void 0) { mesh = null; }
  41061. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41062. _this.width = width;
  41063. _this.height = height;
  41064. _this.subdivisions = subdivisions;
  41065. return _this;
  41066. }
  41067. /** @hidden */
  41068. GroundGeometry.prototype._regenerateVertexData = function () {
  41069. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41070. };
  41071. GroundGeometry.prototype.copy = function (id) {
  41072. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41073. };
  41074. GroundGeometry.prototype.serialize = function () {
  41075. var serializationObject = _super.prototype.serialize.call(this);
  41076. serializationObject.width = this.width;
  41077. serializationObject.height = this.height;
  41078. serializationObject.subdivisions = this.subdivisions;
  41079. return serializationObject;
  41080. };
  41081. GroundGeometry.Parse = function (parsedGround, scene) {
  41082. if (scene.getGeometryByID(parsedGround.id)) {
  41083. return null; // null since geometry could be something else than a ground...
  41084. }
  41085. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41086. if (BABYLON.Tags) {
  41087. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41088. }
  41089. scene.pushGeometry(ground, true);
  41090. return ground;
  41091. };
  41092. return GroundGeometry;
  41093. }(_PrimitiveGeometry));
  41094. BABYLON.GroundGeometry = GroundGeometry;
  41095. /**
  41096. * Creates a tiled ground geometry
  41097. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41098. */
  41099. var TiledGroundGeometry = /** @class */ (function (_super) {
  41100. __extends(TiledGroundGeometry, _super);
  41101. /**
  41102. * Creates a tiled ground geometry
  41103. * @param id defines the unique ID of the geometry
  41104. * @param scene defines the hosting scene
  41105. * @param xmin defines the minimum value on X axis
  41106. * @param zmin defines the minimum value on Z axis
  41107. * @param xmax defines the maximum value on X axis
  41108. * @param zmax defines the maximum value on Z axis
  41109. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41110. * @param precision defines the precision to use when computing the tiles
  41111. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41112. * @param mesh defines the hosting mesh (can be null)
  41113. */
  41114. function TiledGroundGeometry(id, scene,
  41115. /**
  41116. * Defines the minimum value on X axis
  41117. */
  41118. xmin,
  41119. /**
  41120. * Defines the minimum value on Z axis
  41121. */
  41122. zmin,
  41123. /**
  41124. * Defines the maximum value on X axis
  41125. */
  41126. xmax,
  41127. /**
  41128. * Defines the maximum value on Z axis
  41129. */
  41130. zmax,
  41131. /**
  41132. * Defines the subdivisions to apply to the ground
  41133. */
  41134. subdivisions,
  41135. /**
  41136. * Defines the precision to use when computing the tiles
  41137. */
  41138. precision, canBeRegenerated, mesh) {
  41139. if (mesh === void 0) { mesh = null; }
  41140. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41141. _this.xmin = xmin;
  41142. _this.zmin = zmin;
  41143. _this.xmax = xmax;
  41144. _this.zmax = zmax;
  41145. _this.subdivisions = subdivisions;
  41146. _this.precision = precision;
  41147. return _this;
  41148. }
  41149. /** @hidden */
  41150. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41151. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41152. };
  41153. TiledGroundGeometry.prototype.copy = function (id) {
  41154. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41155. };
  41156. return TiledGroundGeometry;
  41157. }(_PrimitiveGeometry));
  41158. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41159. /**
  41160. * Creates a plane geometry
  41161. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41162. */
  41163. var PlaneGeometry = /** @class */ (function (_super) {
  41164. __extends(PlaneGeometry, _super);
  41165. /**
  41166. * Creates a plane geometry
  41167. * @param id defines the unique ID of the geometry
  41168. * @param scene defines the hosting scene
  41169. * @param size defines the size of the plane (width === height)
  41170. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41171. * @param mesh defines the hosting mesh (can be null)
  41172. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41173. */
  41174. function PlaneGeometry(id, scene,
  41175. /**
  41176. * Defines the size of the plane (width === height)
  41177. */
  41178. size, canBeRegenerated, mesh,
  41179. /**
  41180. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41181. */
  41182. side) {
  41183. if (mesh === void 0) { mesh = null; }
  41184. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41185. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41186. _this.size = size;
  41187. _this.side = side;
  41188. return _this;
  41189. }
  41190. /** @hidden */
  41191. PlaneGeometry.prototype._regenerateVertexData = function () {
  41192. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41193. };
  41194. PlaneGeometry.prototype.copy = function (id) {
  41195. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41196. };
  41197. PlaneGeometry.prototype.serialize = function () {
  41198. var serializationObject = _super.prototype.serialize.call(this);
  41199. serializationObject.size = this.size;
  41200. return serializationObject;
  41201. };
  41202. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41203. if (scene.getGeometryByID(parsedPlane.id)) {
  41204. return null; // null since geometry could be something else than a ground...
  41205. }
  41206. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41207. if (BABYLON.Tags) {
  41208. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41209. }
  41210. scene.pushGeometry(plane, true);
  41211. return plane;
  41212. };
  41213. return PlaneGeometry;
  41214. }(_PrimitiveGeometry));
  41215. BABYLON.PlaneGeometry = PlaneGeometry;
  41216. /**
  41217. * Creates a torus knot geometry
  41218. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41219. */
  41220. var TorusKnotGeometry = /** @class */ (function (_super) {
  41221. __extends(TorusKnotGeometry, _super);
  41222. /**
  41223. * Creates a torus knot geometry
  41224. * @param id defines the unique ID of the geometry
  41225. * @param scene defines the hosting scene
  41226. * @param radius defines the radius of the torus knot
  41227. * @param tube defines the thickness of the torus knot tube
  41228. * @param radialSegments defines the number of radial segments
  41229. * @param tubularSegments defines the number of tubular segments
  41230. * @param p defines the first number of windings
  41231. * @param q defines the second number of windings
  41232. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41233. * @param mesh defines the hosting mesh (can be null)
  41234. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41235. */
  41236. function TorusKnotGeometry(id, scene,
  41237. /**
  41238. * Defines the radius of the torus knot
  41239. */
  41240. radius,
  41241. /**
  41242. * Defines the thickness of the torus knot tube
  41243. */
  41244. tube,
  41245. /**
  41246. * Defines the number of radial segments
  41247. */
  41248. radialSegments,
  41249. /**
  41250. * Defines the number of tubular segments
  41251. */
  41252. tubularSegments,
  41253. /**
  41254. * Defines the first number of windings
  41255. */
  41256. p,
  41257. /**
  41258. * Defines the second number of windings
  41259. */
  41260. q, canBeRegenerated, mesh,
  41261. /**
  41262. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41263. */
  41264. side) {
  41265. if (mesh === void 0) { mesh = null; }
  41266. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41267. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41268. _this.radius = radius;
  41269. _this.tube = tube;
  41270. _this.radialSegments = radialSegments;
  41271. _this.tubularSegments = tubularSegments;
  41272. _this.p = p;
  41273. _this.q = q;
  41274. _this.side = side;
  41275. return _this;
  41276. }
  41277. /** @hidden */
  41278. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41279. 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 });
  41280. };
  41281. TorusKnotGeometry.prototype.copy = function (id) {
  41282. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41283. };
  41284. TorusKnotGeometry.prototype.serialize = function () {
  41285. var serializationObject = _super.prototype.serialize.call(this);
  41286. serializationObject.radius = this.radius;
  41287. serializationObject.tube = this.tube;
  41288. serializationObject.radialSegments = this.radialSegments;
  41289. serializationObject.tubularSegments = this.tubularSegments;
  41290. serializationObject.p = this.p;
  41291. serializationObject.q = this.q;
  41292. return serializationObject;
  41293. };
  41294. ;
  41295. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41296. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41297. return null; // null since geometry could be something else than a ground...
  41298. }
  41299. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41300. if (BABYLON.Tags) {
  41301. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41302. }
  41303. scene.pushGeometry(torusKnot, true);
  41304. return torusKnot;
  41305. };
  41306. return TorusKnotGeometry;
  41307. }(_PrimitiveGeometry));
  41308. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41309. //}
  41310. })(BABYLON || (BABYLON = {}));
  41311. //# sourceMappingURL=babylon.geometry.js.map
  41312. var BABYLON;
  41313. (function (BABYLON) {
  41314. /**
  41315. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41316. */
  41317. var PerformanceMonitor = /** @class */ (function () {
  41318. /**
  41319. * constructor
  41320. * @param frameSampleSize The number of samples required to saturate the sliding window
  41321. */
  41322. function PerformanceMonitor(frameSampleSize) {
  41323. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41324. this._enabled = true;
  41325. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41326. }
  41327. /**
  41328. * Samples current frame
  41329. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41330. */
  41331. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41332. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41333. if (!this._enabled)
  41334. return;
  41335. if (this._lastFrameTimeMs != null) {
  41336. var dt = timeMs - this._lastFrameTimeMs;
  41337. this._rollingFrameTime.add(dt);
  41338. }
  41339. this._lastFrameTimeMs = timeMs;
  41340. };
  41341. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41342. /**
  41343. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41344. */
  41345. get: function () {
  41346. return this._rollingFrameTime.average;
  41347. },
  41348. enumerable: true,
  41349. configurable: true
  41350. });
  41351. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41352. /**
  41353. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41354. */
  41355. get: function () {
  41356. return this._rollingFrameTime.variance;
  41357. },
  41358. enumerable: true,
  41359. configurable: true
  41360. });
  41361. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41362. /**
  41363. * Returns the frame time of the most recent frame
  41364. */
  41365. get: function () {
  41366. return this._rollingFrameTime.history(0);
  41367. },
  41368. enumerable: true,
  41369. configurable: true
  41370. });
  41371. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41372. /**
  41373. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41374. */
  41375. get: function () {
  41376. return 1000.0 / this._rollingFrameTime.average;
  41377. },
  41378. enumerable: true,
  41379. configurable: true
  41380. });
  41381. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41382. /**
  41383. * Returns the average framerate in frames per second using the most recent frame time
  41384. */
  41385. get: function () {
  41386. var history = this._rollingFrameTime.history(0);
  41387. if (history === 0) {
  41388. return 0;
  41389. }
  41390. return 1000.0 / history;
  41391. },
  41392. enumerable: true,
  41393. configurable: true
  41394. });
  41395. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41396. /**
  41397. * Returns true if enough samples have been taken to completely fill the sliding window
  41398. */
  41399. get: function () {
  41400. return this._rollingFrameTime.isSaturated();
  41401. },
  41402. enumerable: true,
  41403. configurable: true
  41404. });
  41405. /**
  41406. * Enables contributions to the sliding window sample set
  41407. */
  41408. PerformanceMonitor.prototype.enable = function () {
  41409. this._enabled = true;
  41410. };
  41411. /**
  41412. * Disables contributions to the sliding window sample set
  41413. * Samples will not be interpolated over the disabled period
  41414. */
  41415. PerformanceMonitor.prototype.disable = function () {
  41416. this._enabled = false;
  41417. //clear last sample to avoid interpolating over the disabled period when next enabled
  41418. this._lastFrameTimeMs = null;
  41419. };
  41420. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41421. /**
  41422. * Returns true if sampling is enabled
  41423. */
  41424. get: function () {
  41425. return this._enabled;
  41426. },
  41427. enumerable: true,
  41428. configurable: true
  41429. });
  41430. /**
  41431. * Resets performance monitor
  41432. */
  41433. PerformanceMonitor.prototype.reset = function () {
  41434. //clear last sample to avoid interpolating over the disabled period when next enabled
  41435. this._lastFrameTimeMs = null;
  41436. //wipe record
  41437. this._rollingFrameTime.reset();
  41438. };
  41439. return PerformanceMonitor;
  41440. }());
  41441. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41442. /**
  41443. * RollingAverage
  41444. *
  41445. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41446. */
  41447. var RollingAverage = /** @class */ (function () {
  41448. /**
  41449. * constructor
  41450. * @param length The number of samples required to saturate the sliding window
  41451. */
  41452. function RollingAverage(length) {
  41453. this._samples = new Array(length);
  41454. this.reset();
  41455. }
  41456. /**
  41457. * Adds a sample to the sample set
  41458. * @param v The sample value
  41459. */
  41460. RollingAverage.prototype.add = function (v) {
  41461. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41462. var delta;
  41463. //we need to check if we've already wrapped round
  41464. if (this.isSaturated()) {
  41465. //remove bottom of stack from mean
  41466. var bottomValue = this._samples[this._pos];
  41467. delta = bottomValue - this.average;
  41468. this.average -= delta / (this._sampleCount - 1);
  41469. this._m2 -= delta * (bottomValue - this.average);
  41470. }
  41471. else {
  41472. this._sampleCount++;
  41473. }
  41474. //add new value to mean
  41475. delta = v - this.average;
  41476. this.average += delta / (this._sampleCount);
  41477. this._m2 += delta * (v - this.average);
  41478. //set the new variance
  41479. this.variance = this._m2 / (this._sampleCount - 1);
  41480. this._samples[this._pos] = v;
  41481. this._pos++;
  41482. this._pos %= this._samples.length; //positive wrap around
  41483. };
  41484. /**
  41485. * Returns previously added values or null if outside of history or outside the sliding window domain
  41486. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41487. * @return Value previously recorded with add() or null if outside of range
  41488. */
  41489. RollingAverage.prototype.history = function (i) {
  41490. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41491. return 0;
  41492. }
  41493. var i0 = this._wrapPosition(this._pos - 1.0);
  41494. return this._samples[this._wrapPosition(i0 - i)];
  41495. };
  41496. /**
  41497. * Returns true if enough samples have been taken to completely fill the sliding window
  41498. * @return true if sample-set saturated
  41499. */
  41500. RollingAverage.prototype.isSaturated = function () {
  41501. return this._sampleCount >= this._samples.length;
  41502. };
  41503. /**
  41504. * Resets the rolling average (equivalent to 0 samples taken so far)
  41505. */
  41506. RollingAverage.prototype.reset = function () {
  41507. this.average = 0;
  41508. this.variance = 0;
  41509. this._sampleCount = 0;
  41510. this._pos = 0;
  41511. this._m2 = 0;
  41512. };
  41513. /**
  41514. * Wraps a value around the sample range boundaries
  41515. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41516. * @return Wrapped position in sample range
  41517. */
  41518. RollingAverage.prototype._wrapPosition = function (i) {
  41519. var max = this._samples.length;
  41520. return ((i % max) + max) % max;
  41521. };
  41522. return RollingAverage;
  41523. }());
  41524. BABYLON.RollingAverage = RollingAverage;
  41525. })(BABYLON || (BABYLON = {}));
  41526. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41527. var BABYLON;
  41528. (function (BABYLON) {
  41529. /**
  41530. * "Static Class" containing the most commonly used helper while dealing with material for
  41531. * rendering purpose.
  41532. *
  41533. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41534. *
  41535. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41536. */
  41537. var MaterialHelper = /** @class */ (function () {
  41538. function MaterialHelper() {
  41539. }
  41540. /**
  41541. * Bind the current view position to an effect.
  41542. * @param effect The effect to be bound
  41543. * @param scene The scene the eyes position is used from
  41544. */
  41545. MaterialHelper.BindEyePosition = function (effect, scene) {
  41546. if (scene._forcedViewPosition) {
  41547. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41548. return;
  41549. }
  41550. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41551. };
  41552. /**
  41553. * Helps preparing the defines values about the UVs in used in the effect.
  41554. * UVs are shared as much as we can accross channels in the shaders.
  41555. * @param texture The texture we are preparing the UVs for
  41556. * @param defines The defines to update
  41557. * @param key The channel key "diffuse", "specular"... used in the shader
  41558. */
  41559. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41560. defines._needUVs = true;
  41561. defines[key] = true;
  41562. if (texture.getTextureMatrix().isIdentity(true)) {
  41563. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41564. if (texture.coordinatesIndex === 0) {
  41565. defines["MAINUV1"] = true;
  41566. }
  41567. else {
  41568. defines["MAINUV2"] = true;
  41569. }
  41570. }
  41571. else {
  41572. defines[key + "DIRECTUV"] = 0;
  41573. }
  41574. };
  41575. /**
  41576. * Binds a texture matrix value to its corrsponding uniform
  41577. * @param texture The texture to bind the matrix for
  41578. * @param uniformBuffer The uniform buffer receivin the data
  41579. * @param key The channel key "diffuse", "specular"... used in the shader
  41580. */
  41581. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41582. var matrix = texture.getTextureMatrix();
  41583. if (!matrix.isIdentity(true)) {
  41584. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41585. }
  41586. };
  41587. /**
  41588. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41589. * @param mesh defines the current mesh
  41590. * @param scene defines the current scene
  41591. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41592. * @param pointsCloud defines if point cloud rendering has to be turned on
  41593. * @param fogEnabled defines if fog has to be turned on
  41594. * @param alphaTest defines if alpha testing has to be turned on
  41595. * @param defines defines the current list of defines
  41596. */
  41597. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41598. if (defines._areMiscDirty) {
  41599. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41600. defines["POINTSIZE"] = pointsCloud;
  41601. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41602. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41603. defines["ALPHATEST"] = alphaTest;
  41604. }
  41605. };
  41606. /**
  41607. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41608. * @param scene defines the current scene
  41609. * @param engine defines the current engine
  41610. * @param defines specifies the list of active defines
  41611. * @param useInstances defines if instances have to be turned on
  41612. * @param useClipPlane defines if clip plane have to be turned on
  41613. */
  41614. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41615. if (useClipPlane === void 0) { useClipPlane = null; }
  41616. var changed = false;
  41617. var useClipPlane1 = false;
  41618. var useClipPlane2 = false;
  41619. var useClipPlane3 = false;
  41620. var useClipPlane4 = false;
  41621. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41622. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41623. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41624. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41625. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41626. defines["CLIPPLANE"] = useClipPlane1;
  41627. changed = true;
  41628. }
  41629. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41630. defines["CLIPPLANE2"] = useClipPlane2;
  41631. changed = true;
  41632. }
  41633. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41634. defines["CLIPPLANE3"] = useClipPlane3;
  41635. changed = true;
  41636. }
  41637. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41638. defines["CLIPPLANE4"] = useClipPlane4;
  41639. changed = true;
  41640. }
  41641. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41642. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41643. changed = true;
  41644. }
  41645. if (defines["INSTANCES"] !== useInstances) {
  41646. defines["INSTANCES"] = useInstances;
  41647. changed = true;
  41648. }
  41649. if (changed) {
  41650. defines.markAsUnprocessed();
  41651. }
  41652. };
  41653. /**
  41654. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41655. * @param mesh The mesh containing the geometry data we will draw
  41656. * @param defines The defines to update
  41657. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41658. * @param useBones Precise whether bones should be used or not (override mesh info)
  41659. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41660. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41661. * @returns false if defines are considered not dirty and have not been checked
  41662. */
  41663. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41664. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41665. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41666. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41667. return false;
  41668. }
  41669. defines._normals = defines._needNormals;
  41670. defines._uvs = defines._needUVs;
  41671. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41672. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41673. defines["TANGENT"] = true;
  41674. }
  41675. if (defines._needUVs) {
  41676. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41677. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41678. }
  41679. else {
  41680. defines["UV1"] = false;
  41681. defines["UV2"] = false;
  41682. }
  41683. if (useVertexColor) {
  41684. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41685. defines["VERTEXCOLOR"] = hasVertexColors;
  41686. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41687. }
  41688. if (useBones) {
  41689. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41690. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41691. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41692. }
  41693. else {
  41694. defines["NUM_BONE_INFLUENCERS"] = 0;
  41695. defines["BonesPerMesh"] = 0;
  41696. }
  41697. }
  41698. if (useMorphTargets) {
  41699. var manager = mesh.morphTargetManager;
  41700. if (manager) {
  41701. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41702. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41703. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41704. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41705. }
  41706. else {
  41707. defines["MORPHTARGETS_TANGENT"] = false;
  41708. defines["MORPHTARGETS_NORMAL"] = false;
  41709. defines["MORPHTARGETS"] = false;
  41710. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41711. }
  41712. }
  41713. return true;
  41714. };
  41715. /**
  41716. * Prepares the defines related to the light information passed in parameter
  41717. * @param scene The scene we are intending to draw
  41718. * @param mesh The mesh the effect is compiling for
  41719. * @param defines The defines to update
  41720. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41721. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41722. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41723. * @returns true if normals will be required for the rest of the effect
  41724. */
  41725. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41726. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41727. if (disableLighting === void 0) { disableLighting = false; }
  41728. if (!defines._areLightsDirty) {
  41729. return defines._needNormals;
  41730. }
  41731. var lightIndex = 0;
  41732. var needNormals = false;
  41733. var needRebuild = false;
  41734. var lightmapMode = false;
  41735. var shadowEnabled = false;
  41736. var specularEnabled = false;
  41737. if (scene.lightsEnabled && !disableLighting) {
  41738. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41739. var light = _a[_i];
  41740. needNormals = true;
  41741. if (defines["LIGHT" + lightIndex] === undefined) {
  41742. needRebuild = true;
  41743. }
  41744. defines["LIGHT" + lightIndex] = true;
  41745. defines["SPOTLIGHT" + lightIndex] = false;
  41746. defines["HEMILIGHT" + lightIndex] = false;
  41747. defines["POINTLIGHT" + lightIndex] = false;
  41748. defines["DIRLIGHT" + lightIndex] = false;
  41749. light.prepareLightSpecificDefines(defines, lightIndex);
  41750. // FallOff.
  41751. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41752. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41753. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41754. switch (light.falloffType) {
  41755. case BABYLON.Light.FALLOFF_GLTF:
  41756. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41757. break;
  41758. case BABYLON.Light.FALLOFF_PHYSICAL:
  41759. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41760. break;
  41761. case BABYLON.Light.FALLOFF_STANDARD:
  41762. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41763. break;
  41764. }
  41765. // Specular
  41766. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41767. specularEnabled = true;
  41768. }
  41769. // Shadows
  41770. defines["SHADOW" + lightIndex] = false;
  41771. defines["SHADOWPCF" + lightIndex] = false;
  41772. defines["SHADOWPCSS" + lightIndex] = false;
  41773. defines["SHADOWPOISSON" + lightIndex] = false;
  41774. defines["SHADOWESM" + lightIndex] = false;
  41775. defines["SHADOWCUBE" + lightIndex] = false;
  41776. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41777. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41778. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41779. var shadowGenerator = light.getShadowGenerator();
  41780. if (shadowGenerator) {
  41781. var shadowMap = shadowGenerator.getShadowMap();
  41782. if (shadowMap) {
  41783. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41784. shadowEnabled = true;
  41785. shadowGenerator.prepareDefines(defines, lightIndex);
  41786. }
  41787. }
  41788. }
  41789. }
  41790. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41791. lightmapMode = true;
  41792. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41793. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41794. }
  41795. else {
  41796. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41797. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41798. }
  41799. lightIndex++;
  41800. if (lightIndex === maxSimultaneousLights)
  41801. break;
  41802. }
  41803. }
  41804. defines["SPECULARTERM"] = specularEnabled;
  41805. defines["SHADOWS"] = shadowEnabled;
  41806. // Resetting all other lights if any
  41807. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41808. if (defines["LIGHT" + index] !== undefined) {
  41809. defines["LIGHT" + index] = false;
  41810. defines["HEMILIGHT" + lightIndex] = false;
  41811. defines["POINTLIGHT" + lightIndex] = false;
  41812. defines["DIRLIGHT" + lightIndex] = false;
  41813. defines["SPOTLIGHT" + lightIndex] = false;
  41814. defines["SHADOW" + lightIndex] = false;
  41815. }
  41816. }
  41817. var caps = scene.getEngine().getCaps();
  41818. if (defines["SHADOWFLOAT"] === undefined) {
  41819. needRebuild = true;
  41820. }
  41821. defines["SHADOWFLOAT"] = shadowEnabled &&
  41822. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41823. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41824. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41825. if (needRebuild) {
  41826. defines.rebuild();
  41827. }
  41828. return needNormals;
  41829. };
  41830. /**
  41831. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41832. * that won t be acctive due to defines being turned off.
  41833. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41834. * @param samplersList The samplers list
  41835. * @param defines The defines helping in the list generation
  41836. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41837. */
  41838. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41839. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41840. var uniformsList;
  41841. var uniformBuffersList = null;
  41842. if (uniformsListOrOptions.uniformsNames) {
  41843. var options = uniformsListOrOptions;
  41844. uniformsList = options.uniformsNames;
  41845. uniformBuffersList = options.uniformBuffersNames;
  41846. samplersList = options.samplers;
  41847. defines = options.defines;
  41848. maxSimultaneousLights = options.maxSimultaneousLights;
  41849. }
  41850. else {
  41851. uniformsList = uniformsListOrOptions;
  41852. if (!samplersList) {
  41853. samplersList = [];
  41854. }
  41855. }
  41856. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41857. if (!defines["LIGHT" + lightIndex]) {
  41858. break;
  41859. }
  41860. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41861. if (uniformBuffersList) {
  41862. uniformBuffersList.push("Light" + lightIndex);
  41863. }
  41864. samplersList.push("shadowSampler" + lightIndex);
  41865. samplersList.push("depthSampler" + lightIndex);
  41866. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41867. samplersList.push("projectionLightSampler" + lightIndex);
  41868. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41869. }
  41870. }
  41871. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41872. uniformsList.push("morphTargetInfluences");
  41873. }
  41874. };
  41875. /**
  41876. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41877. * @param defines The defines to update while falling back
  41878. * @param fallbacks The authorized effect fallbacks
  41879. * @param maxSimultaneousLights The maximum number of lights allowed
  41880. * @param rank the current rank of the Effect
  41881. * @returns The newly affected rank
  41882. */
  41883. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41884. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41885. if (rank === void 0) { rank = 0; }
  41886. var lightFallbackRank = 0;
  41887. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41888. if (!defines["LIGHT" + lightIndex]) {
  41889. break;
  41890. }
  41891. if (lightIndex > 0) {
  41892. lightFallbackRank = rank + lightIndex;
  41893. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41894. }
  41895. if (!defines["SHADOWS"]) {
  41896. if (defines["SHADOW" + lightIndex]) {
  41897. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41898. }
  41899. if (defines["SHADOWPCF" + lightIndex]) {
  41900. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41901. }
  41902. if (defines["SHADOWPCSS" + lightIndex]) {
  41903. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41904. }
  41905. if (defines["SHADOWPOISSON" + lightIndex]) {
  41906. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41907. }
  41908. if (defines["SHADOWESM" + lightIndex]) {
  41909. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41910. }
  41911. }
  41912. }
  41913. return lightFallbackRank++;
  41914. };
  41915. /**
  41916. * Prepares the list of attributes required for morph targets according to the effect defines.
  41917. * @param attribs The current list of supported attribs
  41918. * @param mesh The mesh to prepare the morph targets attributes for
  41919. * @param defines The current Defines of the effect
  41920. */
  41921. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41922. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41923. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41924. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41925. var manager = mesh.morphTargetManager;
  41926. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41927. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41928. for (var index = 0; index < influencers; index++) {
  41929. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41930. if (normal) {
  41931. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41932. }
  41933. if (tangent) {
  41934. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41935. }
  41936. if (attribs.length > maxAttributesCount) {
  41937. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41938. }
  41939. }
  41940. }
  41941. };
  41942. /**
  41943. * Prepares the list of attributes required for bones according to the effect defines.
  41944. * @param attribs The current list of supported attribs
  41945. * @param mesh The mesh to prepare the bones attributes for
  41946. * @param defines The current Defines of the effect
  41947. * @param fallbacks The current efffect fallback strategy
  41948. */
  41949. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41950. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41951. fallbacks.addCPUSkinningFallback(0, mesh);
  41952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41954. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41957. }
  41958. }
  41959. };
  41960. /**
  41961. * Prepares the list of attributes required for instances according to the effect defines.
  41962. * @param attribs The current list of supported attribs
  41963. * @param defines The current Defines of the effect
  41964. */
  41965. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41966. if (defines["INSTANCES"]) {
  41967. attribs.push("world0");
  41968. attribs.push("world1");
  41969. attribs.push("world2");
  41970. attribs.push("world3");
  41971. }
  41972. };
  41973. /**
  41974. * Binds the light shadow information to the effect for the given mesh.
  41975. * @param light The light containing the generator
  41976. * @param scene The scene the lights belongs to
  41977. * @param mesh The mesh we are binding the information to render
  41978. * @param lightIndex The light index in the effect used to render the mesh
  41979. * @param effect The effect we are binding the data to
  41980. */
  41981. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41982. if (light.shadowEnabled && mesh.receiveShadows) {
  41983. var shadowGenerator = light.getShadowGenerator();
  41984. if (shadowGenerator) {
  41985. shadowGenerator.bindShadowLight(lightIndex, effect);
  41986. }
  41987. }
  41988. };
  41989. /**
  41990. * Binds the light information to the effect.
  41991. * @param light The light containing the generator
  41992. * @param effect The effect we are binding the data to
  41993. * @param lightIndex The light index in the effect used to render
  41994. */
  41995. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41996. light.transferToEffect(effect, lightIndex + "");
  41997. };
  41998. /**
  41999. * Binds the lights information from the scene to the effect for the given mesh.
  42000. * @param scene The scene the lights belongs to
  42001. * @param mesh The mesh we are binding the information to render
  42002. * @param effect The effect we are binding the data to
  42003. * @param defines The generated defines for the effect
  42004. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42005. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42006. */
  42007. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42008. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42009. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42010. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42011. for (var i = 0; i < len; i++) {
  42012. var light = mesh._lightSources[i];
  42013. var iAsString = i.toString();
  42014. var scaledIntensity = light.getScaledIntensity();
  42015. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42016. MaterialHelper.BindLightProperties(light, effect, i);
  42017. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42018. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42019. if (defines["SPECULARTERM"]) {
  42020. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42021. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42022. }
  42023. // Shadows
  42024. if (scene.shadowsEnabled) {
  42025. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42026. }
  42027. light._uniformBuffer.update();
  42028. }
  42029. };
  42030. /**
  42031. * Binds the fog information from the scene to the effect for the given mesh.
  42032. * @param scene The scene the lights belongs to
  42033. * @param mesh The mesh we are binding the information to render
  42034. * @param effect The effect we are binding the data to
  42035. * @param linearSpace Defines if the fog effect is applied in linear space
  42036. */
  42037. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42038. if (linearSpace === void 0) { linearSpace = false; }
  42039. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42040. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42041. // Convert fog color to linear space if used in a linear space computed shader.
  42042. if (linearSpace) {
  42043. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42044. effect.setColor3("vFogColor", this._tempFogColor);
  42045. }
  42046. else {
  42047. effect.setColor3("vFogColor", scene.fogColor);
  42048. }
  42049. }
  42050. };
  42051. /**
  42052. * Binds the bones information from the mesh to the effect.
  42053. * @param mesh The mesh we are binding the information to render
  42054. * @param effect The effect we are binding the data to
  42055. */
  42056. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42057. if (!effect || !mesh) {
  42058. return;
  42059. }
  42060. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42061. mesh.computeBonesUsingShaders = false;
  42062. }
  42063. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42064. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42065. if (matrices) {
  42066. effect.setMatrices("mBones", matrices);
  42067. }
  42068. }
  42069. };
  42070. /**
  42071. * Binds the morph targets information from the mesh to the effect.
  42072. * @param abstractMesh The mesh we are binding the information to render
  42073. * @param effect The effect we are binding the data to
  42074. */
  42075. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42076. var manager = abstractMesh.morphTargetManager;
  42077. if (!abstractMesh || !manager) {
  42078. return;
  42079. }
  42080. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42081. };
  42082. /**
  42083. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42084. * @param defines The generated defines used in the effect
  42085. * @param effect The effect we are binding the data to
  42086. * @param scene The scene we are willing to render with logarithmic scale for
  42087. */
  42088. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42089. if (defines["LOGARITHMICDEPTH"]) {
  42090. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42091. }
  42092. };
  42093. /**
  42094. * Binds the clip plane information from the scene to the effect.
  42095. * @param scene The scene the clip plane information are extracted from
  42096. * @param effect The effect we are binding the data to
  42097. */
  42098. MaterialHelper.BindClipPlane = function (effect, scene) {
  42099. if (scene.clipPlane) {
  42100. var clipPlane = scene.clipPlane;
  42101. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42102. }
  42103. if (scene.clipPlane2) {
  42104. var clipPlane = scene.clipPlane2;
  42105. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42106. }
  42107. if (scene.clipPlane3) {
  42108. var clipPlane = scene.clipPlane3;
  42109. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42110. }
  42111. if (scene.clipPlane4) {
  42112. var clipPlane = scene.clipPlane4;
  42113. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42114. }
  42115. };
  42116. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42117. return MaterialHelper;
  42118. }());
  42119. BABYLON.MaterialHelper = MaterialHelper;
  42120. })(BABYLON || (BABYLON = {}));
  42121. //# sourceMappingURL=babylon.materialHelper.js.map
  42122. var BABYLON;
  42123. (function (BABYLON) {
  42124. /**
  42125. * Base class of materials working in push mode in babylon JS
  42126. * @hidden
  42127. */
  42128. var PushMaterial = /** @class */ (function (_super) {
  42129. __extends(PushMaterial, _super);
  42130. function PushMaterial(name, scene) {
  42131. var _this = _super.call(this, name, scene) || this;
  42132. _this._normalMatrix = new BABYLON.Matrix();
  42133. _this.storeEffectOnSubMeshes = true;
  42134. return _this;
  42135. }
  42136. PushMaterial.prototype.getEffect = function () {
  42137. return this._activeEffect;
  42138. };
  42139. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42140. if (!mesh) {
  42141. return false;
  42142. }
  42143. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42144. return true;
  42145. }
  42146. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42147. };
  42148. /**
  42149. * Binds the given world matrix to the active effect
  42150. *
  42151. * @param world the matrix to bind
  42152. */
  42153. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42154. this._activeEffect.setMatrix("world", world);
  42155. };
  42156. /**
  42157. * Binds the given normal matrix to the active effect
  42158. *
  42159. * @param normalMatrix the matrix to bind
  42160. */
  42161. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42162. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42163. };
  42164. PushMaterial.prototype.bind = function (world, mesh) {
  42165. if (!mesh) {
  42166. return;
  42167. }
  42168. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42169. };
  42170. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42171. if (effect === void 0) { effect = null; }
  42172. _super.prototype._afterBind.call(this, mesh);
  42173. this.getScene()._cachedEffect = effect;
  42174. };
  42175. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42176. if (visibility === void 0) { visibility = 1; }
  42177. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42178. };
  42179. return PushMaterial;
  42180. }(BABYLON.Material));
  42181. BABYLON.PushMaterial = PushMaterial;
  42182. })(BABYLON || (BABYLON = {}));
  42183. //# sourceMappingURL=babylon.pushMaterial.js.map
  42184. var BABYLON;
  42185. (function (BABYLON) {
  42186. /** @hidden */
  42187. var StandardMaterialDefines = /** @class */ (function (_super) {
  42188. __extends(StandardMaterialDefines, _super);
  42189. function StandardMaterialDefines() {
  42190. var _this = _super.call(this) || this;
  42191. _this.MAINUV1 = false;
  42192. _this.MAINUV2 = false;
  42193. _this.DIFFUSE = false;
  42194. _this.DIFFUSEDIRECTUV = 0;
  42195. _this.AMBIENT = false;
  42196. _this.AMBIENTDIRECTUV = 0;
  42197. _this.OPACITY = false;
  42198. _this.OPACITYDIRECTUV = 0;
  42199. _this.OPACITYRGB = false;
  42200. _this.REFLECTION = false;
  42201. _this.EMISSIVE = false;
  42202. _this.EMISSIVEDIRECTUV = 0;
  42203. _this.SPECULAR = false;
  42204. _this.SPECULARDIRECTUV = 0;
  42205. _this.BUMP = false;
  42206. _this.BUMPDIRECTUV = 0;
  42207. _this.PARALLAX = false;
  42208. _this.PARALLAXOCCLUSION = false;
  42209. _this.SPECULAROVERALPHA = false;
  42210. _this.CLIPPLANE = false;
  42211. _this.CLIPPLANE2 = false;
  42212. _this.CLIPPLANE3 = false;
  42213. _this.CLIPPLANE4 = false;
  42214. _this.ALPHATEST = false;
  42215. _this.DEPTHPREPASS = false;
  42216. _this.ALPHAFROMDIFFUSE = false;
  42217. _this.POINTSIZE = false;
  42218. _this.FOG = false;
  42219. _this.SPECULARTERM = false;
  42220. _this.DIFFUSEFRESNEL = false;
  42221. _this.OPACITYFRESNEL = false;
  42222. _this.REFLECTIONFRESNEL = false;
  42223. _this.REFRACTIONFRESNEL = false;
  42224. _this.EMISSIVEFRESNEL = false;
  42225. _this.FRESNEL = false;
  42226. _this.NORMAL = false;
  42227. _this.UV1 = false;
  42228. _this.UV2 = false;
  42229. _this.VERTEXCOLOR = false;
  42230. _this.VERTEXALPHA = false;
  42231. _this.NUM_BONE_INFLUENCERS = 0;
  42232. _this.BonesPerMesh = 0;
  42233. _this.INSTANCES = false;
  42234. _this.GLOSSINESS = false;
  42235. _this.ROUGHNESS = false;
  42236. _this.EMISSIVEASILLUMINATION = false;
  42237. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42238. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42239. _this.LIGHTMAP = false;
  42240. _this.LIGHTMAPDIRECTUV = 0;
  42241. _this.OBJECTSPACE_NORMALMAP = false;
  42242. _this.USELIGHTMAPASSHADOWMAP = false;
  42243. _this.REFLECTIONMAP_3D = false;
  42244. _this.REFLECTIONMAP_SPHERICAL = false;
  42245. _this.REFLECTIONMAP_PLANAR = false;
  42246. _this.REFLECTIONMAP_CUBIC = false;
  42247. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42248. _this.REFLECTIONMAP_PROJECTION = false;
  42249. _this.REFLECTIONMAP_SKYBOX = false;
  42250. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42251. _this.REFLECTIONMAP_EXPLICIT = false;
  42252. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42253. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42254. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42255. _this.INVERTCUBICMAP = false;
  42256. _this.LOGARITHMICDEPTH = false;
  42257. _this.REFRACTION = false;
  42258. _this.REFRACTIONMAP_3D = false;
  42259. _this.REFLECTIONOVERALPHA = false;
  42260. _this.TWOSIDEDLIGHTING = false;
  42261. _this.SHADOWFLOAT = false;
  42262. _this.MORPHTARGETS = false;
  42263. _this.MORPHTARGETS_NORMAL = false;
  42264. _this.MORPHTARGETS_TANGENT = false;
  42265. _this.NUM_MORPH_INFLUENCERS = 0;
  42266. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42267. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42268. _this.IMAGEPROCESSING = false;
  42269. _this.VIGNETTE = false;
  42270. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42271. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42272. _this.TONEMAPPING = false;
  42273. _this.TONEMAPPING_ACES = false;
  42274. _this.CONTRAST = false;
  42275. _this.COLORCURVES = false;
  42276. _this.COLORGRADING = false;
  42277. _this.COLORGRADING3D = false;
  42278. _this.SAMPLER3DGREENDEPTH = false;
  42279. _this.SAMPLER3DBGRMAP = false;
  42280. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42281. /**
  42282. * If the reflection texture on this material is in linear color space
  42283. * @hidden
  42284. */
  42285. _this.IS_REFLECTION_LINEAR = false;
  42286. /**
  42287. * If the refraction texture on this material is in linear color space
  42288. * @hidden
  42289. */
  42290. _this.IS_REFRACTION_LINEAR = false;
  42291. _this.EXPOSURE = false;
  42292. _this.rebuild();
  42293. return _this;
  42294. }
  42295. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42296. var modes = [
  42297. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42298. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42299. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42300. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42301. ];
  42302. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42303. var mode = modes_1[_i];
  42304. this[mode] = (mode === modeToEnable);
  42305. }
  42306. };
  42307. return StandardMaterialDefines;
  42308. }(BABYLON.MaterialDefines));
  42309. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42310. /**
  42311. * This is the default material used in Babylon. It is the best trade off between quality
  42312. * and performances.
  42313. * @see http://doc.babylonjs.com/babylon101/materials
  42314. */
  42315. var StandardMaterial = /** @class */ (function (_super) {
  42316. __extends(StandardMaterial, _super);
  42317. /**
  42318. * Instantiates a new standard material.
  42319. * This is the default material used in Babylon. It is the best trade off between quality
  42320. * and performances.
  42321. * @see http://doc.babylonjs.com/babylon101/materials
  42322. * @param name Define the name of the material in the scene
  42323. * @param scene Define the scene the material belong to
  42324. */
  42325. function StandardMaterial(name, scene) {
  42326. var _this = _super.call(this, name, scene) || this;
  42327. /**
  42328. * The color of the material lit by the environmental background lighting.
  42329. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42330. */
  42331. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42332. /**
  42333. * The basic color of the material as viewed under a light.
  42334. */
  42335. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42336. /**
  42337. * Define how the color and intensity of the highlight given by the light in the material.
  42338. */
  42339. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42340. /**
  42341. * Define the color of the material as if self lit.
  42342. * This will be mixed in the final result even in the absence of light.
  42343. */
  42344. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42345. /**
  42346. * Defines how sharp are the highlights in the material.
  42347. * The bigger the value the sharper giving a more glossy feeling to the result.
  42348. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  42349. */
  42350. _this.specularPower = 64;
  42351. _this._useAlphaFromDiffuseTexture = false;
  42352. _this._useEmissiveAsIllumination = false;
  42353. _this._linkEmissiveWithDiffuse = false;
  42354. _this._useSpecularOverAlpha = false;
  42355. _this._useReflectionOverAlpha = false;
  42356. _this._disableLighting = false;
  42357. _this._useObjectSpaceNormalMap = false;
  42358. _this._useParallax = false;
  42359. _this._useParallaxOcclusion = false;
  42360. /**
  42361. * 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.
  42362. */
  42363. _this.parallaxScaleBias = 0.05;
  42364. _this._roughness = 0;
  42365. /**
  42366. * In case of refraction, define the value of the indice of refraction.
  42367. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42368. */
  42369. _this.indexOfRefraction = 0.98;
  42370. /**
  42371. * Invert the refraction texture alongside the y axis.
  42372. * It can be usefull with procedural textures or probe for instance.
  42373. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42374. */
  42375. _this.invertRefractionY = true;
  42376. /**
  42377. * Defines the alpha limits in alpha test mode.
  42378. */
  42379. _this.alphaCutOff = 0.4;
  42380. _this._useLightmapAsShadowmap = false;
  42381. _this._useReflectionFresnelFromSpecular = false;
  42382. _this._useGlossinessFromSpecularMapAlpha = false;
  42383. _this._maxSimultaneousLights = 4;
  42384. _this._invertNormalMapX = false;
  42385. _this._invertNormalMapY = false;
  42386. _this._twoSidedLighting = false;
  42387. _this._renderTargets = new BABYLON.SmartArray(16);
  42388. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42389. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42390. // Setup the default processing configuration to the scene.
  42391. _this._attachImageProcessingConfiguration(null);
  42392. _this.getRenderTargetTextures = function () {
  42393. _this._renderTargets.reset();
  42394. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42395. _this._renderTargets.push(_this._reflectionTexture);
  42396. }
  42397. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42398. _this._renderTargets.push(_this._refractionTexture);
  42399. }
  42400. return _this._renderTargets;
  42401. };
  42402. return _this;
  42403. }
  42404. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42405. /**
  42406. * Gets the image processing configuration used either in this material.
  42407. */
  42408. get: function () {
  42409. return this._imageProcessingConfiguration;
  42410. },
  42411. /**
  42412. * Sets the Default image processing configuration used either in the this material.
  42413. *
  42414. * If sets to null, the scene one is in use.
  42415. */
  42416. set: function (value) {
  42417. this._attachImageProcessingConfiguration(value);
  42418. // Ensure the effect will be rebuilt.
  42419. this._markAllSubMeshesAsTexturesDirty();
  42420. },
  42421. enumerable: true,
  42422. configurable: true
  42423. });
  42424. /**
  42425. * Attaches a new image processing configuration to the Standard Material.
  42426. * @param configuration
  42427. */
  42428. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42429. var _this = this;
  42430. if (configuration === this._imageProcessingConfiguration) {
  42431. return;
  42432. }
  42433. // Detaches observer.
  42434. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42435. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42436. }
  42437. // Pick the scene configuration if needed.
  42438. if (!configuration) {
  42439. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42440. }
  42441. else {
  42442. this._imageProcessingConfiguration = configuration;
  42443. }
  42444. // Attaches observer.
  42445. if (this._imageProcessingConfiguration) {
  42446. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42447. _this._markAllSubMeshesAsImageProcessingDirty();
  42448. });
  42449. }
  42450. };
  42451. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42452. /**
  42453. * Gets wether the color curves effect is enabled.
  42454. */
  42455. get: function () {
  42456. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42457. },
  42458. /**
  42459. * Sets wether the color curves effect is enabled.
  42460. */
  42461. set: function (value) {
  42462. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42463. },
  42464. enumerable: true,
  42465. configurable: true
  42466. });
  42467. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42468. /**
  42469. * Gets wether the color grading effect is enabled.
  42470. */
  42471. get: function () {
  42472. return this.imageProcessingConfiguration.colorGradingEnabled;
  42473. },
  42474. /**
  42475. * Gets wether the color grading effect is enabled.
  42476. */
  42477. set: function (value) {
  42478. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42479. },
  42480. enumerable: true,
  42481. configurable: true
  42482. });
  42483. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42484. /**
  42485. * Gets wether tonemapping is enabled or not.
  42486. */
  42487. get: function () {
  42488. return this._imageProcessingConfiguration.toneMappingEnabled;
  42489. },
  42490. /**
  42491. * Sets wether tonemapping is enabled or not
  42492. */
  42493. set: function (value) {
  42494. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42495. },
  42496. enumerable: true,
  42497. configurable: true
  42498. });
  42499. ;
  42500. ;
  42501. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42502. /**
  42503. * The camera exposure used on this material.
  42504. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42505. * This corresponds to a photographic exposure.
  42506. */
  42507. get: function () {
  42508. return this._imageProcessingConfiguration.exposure;
  42509. },
  42510. /**
  42511. * The camera exposure used on this material.
  42512. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42513. * This corresponds to a photographic exposure.
  42514. */
  42515. set: function (value) {
  42516. this._imageProcessingConfiguration.exposure = value;
  42517. },
  42518. enumerable: true,
  42519. configurable: true
  42520. });
  42521. ;
  42522. ;
  42523. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42524. /**
  42525. * Gets The camera contrast used on this material.
  42526. */
  42527. get: function () {
  42528. return this._imageProcessingConfiguration.contrast;
  42529. },
  42530. /**
  42531. * Sets The camera contrast used on this material.
  42532. */
  42533. set: function (value) {
  42534. this._imageProcessingConfiguration.contrast = value;
  42535. },
  42536. enumerable: true,
  42537. configurable: true
  42538. });
  42539. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42540. /**
  42541. * Gets the Color Grading 2D Lookup Texture.
  42542. */
  42543. get: function () {
  42544. return this._imageProcessingConfiguration.colorGradingTexture;
  42545. },
  42546. /**
  42547. * Sets the Color Grading 2D Lookup Texture.
  42548. */
  42549. set: function (value) {
  42550. this._imageProcessingConfiguration.colorGradingTexture = value;
  42551. },
  42552. enumerable: true,
  42553. configurable: true
  42554. });
  42555. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42556. /**
  42557. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42558. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42559. * 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;
  42560. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42561. */
  42562. get: function () {
  42563. return this._imageProcessingConfiguration.colorCurves;
  42564. },
  42565. /**
  42566. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42567. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42568. * 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;
  42569. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42570. */
  42571. set: function (value) {
  42572. this._imageProcessingConfiguration.colorCurves = value;
  42573. },
  42574. enumerable: true,
  42575. configurable: true
  42576. });
  42577. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42578. /**
  42579. * Gets a boolean indicating that current material needs to register RTT
  42580. */
  42581. get: function () {
  42582. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42583. return true;
  42584. }
  42585. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42586. return true;
  42587. }
  42588. return false;
  42589. },
  42590. enumerable: true,
  42591. configurable: true
  42592. });
  42593. /**
  42594. * Gets the current class name of the material e.g. "StandardMaterial"
  42595. * Mainly use in serialization.
  42596. * @returns the class name
  42597. */
  42598. StandardMaterial.prototype.getClassName = function () {
  42599. return "StandardMaterial";
  42600. };
  42601. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42602. /**
  42603. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  42604. * You can try switching to logarithmic depth.
  42605. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  42606. */
  42607. get: function () {
  42608. return this._useLogarithmicDepth;
  42609. },
  42610. set: function (value) {
  42611. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42612. this._markAllSubMeshesAsMiscDirty();
  42613. },
  42614. enumerable: true,
  42615. configurable: true
  42616. });
  42617. /**
  42618. * Specifies if the material will require alpha blending
  42619. * @returns a boolean specifying if alpha blending is needed
  42620. */
  42621. StandardMaterial.prototype.needAlphaBlending = function () {
  42622. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42623. };
  42624. /**
  42625. * Specifies if this material should be rendered in alpha test mode
  42626. * @returns a boolean specifying if an alpha test is needed.
  42627. */
  42628. StandardMaterial.prototype.needAlphaTesting = function () {
  42629. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42630. };
  42631. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42632. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42633. };
  42634. /**
  42635. * Get the texture used for alpha test purpose.
  42636. * @returns the diffuse texture in case of the standard material.
  42637. */
  42638. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42639. return this._diffuseTexture;
  42640. };
  42641. /**
  42642. * Get if the submesh is ready to be used and all its information available.
  42643. * Child classes can use it to update shaders
  42644. * @param mesh defines the mesh to check
  42645. * @param subMesh defines which submesh to check
  42646. * @param useInstances specifies that instances should be used
  42647. * @returns a boolean indicating that the submesh is ready or not
  42648. */
  42649. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42650. if (useInstances === void 0) { useInstances = false; }
  42651. if (subMesh.effect && this.isFrozen) {
  42652. if (this._wasPreviouslyReady) {
  42653. return true;
  42654. }
  42655. }
  42656. if (!subMesh._materialDefines) {
  42657. subMesh._materialDefines = new StandardMaterialDefines();
  42658. }
  42659. var scene = this.getScene();
  42660. var defines = subMesh._materialDefines;
  42661. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42662. if (defines._renderId === scene.getRenderId()) {
  42663. return true;
  42664. }
  42665. }
  42666. var engine = scene.getEngine();
  42667. // Lights
  42668. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42669. // Textures
  42670. if (defines._areTexturesDirty) {
  42671. defines._needUVs = false;
  42672. defines.MAINUV1 = false;
  42673. defines.MAINUV2 = false;
  42674. if (scene.texturesEnabled) {
  42675. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42676. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42677. return false;
  42678. }
  42679. else {
  42680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42681. }
  42682. }
  42683. else {
  42684. defines.DIFFUSE = false;
  42685. }
  42686. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42687. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42688. return false;
  42689. }
  42690. else {
  42691. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42692. }
  42693. }
  42694. else {
  42695. defines.AMBIENT = false;
  42696. }
  42697. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42698. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42699. return false;
  42700. }
  42701. else {
  42702. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42703. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42704. }
  42705. }
  42706. else {
  42707. defines.OPACITY = false;
  42708. }
  42709. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42710. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42711. return false;
  42712. }
  42713. else {
  42714. defines._needNormals = true;
  42715. defines.REFLECTION = true;
  42716. defines.ROUGHNESS = (this._roughness > 0);
  42717. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42718. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42719. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42720. switch (this._reflectionTexture.coordinatesMode) {
  42721. case BABYLON.Texture.EXPLICIT_MODE:
  42722. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42723. break;
  42724. case BABYLON.Texture.PLANAR_MODE:
  42725. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42726. break;
  42727. case BABYLON.Texture.PROJECTION_MODE:
  42728. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42729. break;
  42730. case BABYLON.Texture.SKYBOX_MODE:
  42731. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42732. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42733. break;
  42734. case BABYLON.Texture.SPHERICAL_MODE:
  42735. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42736. break;
  42737. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42738. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42739. break;
  42740. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42741. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42742. break;
  42743. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42744. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42745. break;
  42746. case BABYLON.Texture.CUBIC_MODE:
  42747. case BABYLON.Texture.INVCUBIC_MODE:
  42748. default:
  42749. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42750. break;
  42751. }
  42752. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42753. }
  42754. }
  42755. else {
  42756. defines.REFLECTION = false;
  42757. }
  42758. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42759. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42760. return false;
  42761. }
  42762. else {
  42763. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42764. }
  42765. }
  42766. else {
  42767. defines.EMISSIVE = false;
  42768. }
  42769. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42770. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42771. return false;
  42772. }
  42773. else {
  42774. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42775. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42776. }
  42777. }
  42778. else {
  42779. defines.LIGHTMAP = false;
  42780. }
  42781. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42782. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42783. return false;
  42784. }
  42785. else {
  42786. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42787. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42788. }
  42789. }
  42790. else {
  42791. defines.SPECULAR = false;
  42792. }
  42793. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42794. // Bump texure can not be not blocking.
  42795. if (!this._bumpTexture.isReady()) {
  42796. return false;
  42797. }
  42798. else {
  42799. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42800. defines.PARALLAX = this._useParallax;
  42801. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42802. }
  42803. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42804. }
  42805. else {
  42806. defines.BUMP = false;
  42807. }
  42808. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42809. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42810. return false;
  42811. }
  42812. else {
  42813. defines._needUVs = true;
  42814. defines.REFRACTION = true;
  42815. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42816. }
  42817. }
  42818. else {
  42819. defines.REFRACTION = false;
  42820. }
  42821. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42822. }
  42823. else {
  42824. defines.DIFFUSE = false;
  42825. defines.AMBIENT = false;
  42826. defines.OPACITY = false;
  42827. defines.REFLECTION = false;
  42828. defines.EMISSIVE = false;
  42829. defines.LIGHTMAP = false;
  42830. defines.BUMP = false;
  42831. defines.REFRACTION = false;
  42832. }
  42833. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42834. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42835. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42836. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42837. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42838. }
  42839. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42840. if (!this._imageProcessingConfiguration.isReady()) {
  42841. return false;
  42842. }
  42843. this._imageProcessingConfiguration.prepareDefines(defines);
  42844. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42845. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42846. }
  42847. if (defines._areFresnelDirty) {
  42848. if (StandardMaterial.FresnelEnabled) {
  42849. // Fresnel
  42850. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42851. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42852. this._reflectionFresnelParameters) {
  42853. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42854. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42855. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42856. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42857. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42858. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42859. defines._needNormals = true;
  42860. defines.FRESNEL = true;
  42861. }
  42862. }
  42863. else {
  42864. defines.FRESNEL = false;
  42865. }
  42866. }
  42867. // Misc.
  42868. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42869. // Attribs
  42870. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42871. // Values that need to be evaluated on every frame
  42872. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42873. // Get correct effect
  42874. if (defines.isDirty) {
  42875. defines.markAsProcessed();
  42876. scene.resetCachedMaterial();
  42877. // Fallbacks
  42878. var fallbacks = new BABYLON.EffectFallbacks();
  42879. if (defines.REFLECTION) {
  42880. fallbacks.addFallback(0, "REFLECTION");
  42881. }
  42882. if (defines.SPECULAR) {
  42883. fallbacks.addFallback(0, "SPECULAR");
  42884. }
  42885. if (defines.BUMP) {
  42886. fallbacks.addFallback(0, "BUMP");
  42887. }
  42888. if (defines.PARALLAX) {
  42889. fallbacks.addFallback(1, "PARALLAX");
  42890. }
  42891. if (defines.PARALLAXOCCLUSION) {
  42892. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42893. }
  42894. if (defines.SPECULAROVERALPHA) {
  42895. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42896. }
  42897. if (defines.FOG) {
  42898. fallbacks.addFallback(1, "FOG");
  42899. }
  42900. if (defines.POINTSIZE) {
  42901. fallbacks.addFallback(0, "POINTSIZE");
  42902. }
  42903. if (defines.LOGARITHMICDEPTH) {
  42904. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42905. }
  42906. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42907. if (defines.SPECULARTERM) {
  42908. fallbacks.addFallback(0, "SPECULARTERM");
  42909. }
  42910. if (defines.DIFFUSEFRESNEL) {
  42911. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42912. }
  42913. if (defines.OPACITYFRESNEL) {
  42914. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42915. }
  42916. if (defines.REFLECTIONFRESNEL) {
  42917. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42918. }
  42919. if (defines.EMISSIVEFRESNEL) {
  42920. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42921. }
  42922. if (defines.FRESNEL) {
  42923. fallbacks.addFallback(4, "FRESNEL");
  42924. }
  42925. //Attributes
  42926. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42927. if (defines.NORMAL) {
  42928. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42929. }
  42930. if (defines.UV1) {
  42931. attribs.push(BABYLON.VertexBuffer.UVKind);
  42932. }
  42933. if (defines.UV2) {
  42934. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42935. }
  42936. if (defines.VERTEXCOLOR) {
  42937. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42938. }
  42939. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42940. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42941. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42942. var shaderName = "default";
  42943. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42944. "vFogInfos", "vFogColor", "pointSize",
  42945. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42946. "mBones",
  42947. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42948. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42949. "vReflectionPosition", "vReflectionSize",
  42950. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42951. ];
  42952. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42953. var uniformBuffers = ["Material", "Scene"];
  42954. if (BABYLON.ImageProcessingConfiguration) {
  42955. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42956. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42957. }
  42958. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42959. uniformsNames: uniforms,
  42960. uniformBuffersNames: uniformBuffers,
  42961. samplers: samplers,
  42962. defines: defines,
  42963. maxSimultaneousLights: this._maxSimultaneousLights
  42964. });
  42965. if (this.customShaderNameResolve) {
  42966. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42967. }
  42968. var join = defines.toString();
  42969. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42970. attributes: attribs,
  42971. uniformsNames: uniforms,
  42972. uniformBuffersNames: uniformBuffers,
  42973. samplers: samplers,
  42974. defines: join,
  42975. fallbacks: fallbacks,
  42976. onCompiled: this.onCompiled,
  42977. onError: this.onError,
  42978. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42979. }, engine), defines);
  42980. this.buildUniformLayout();
  42981. }
  42982. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42983. return false;
  42984. }
  42985. defines._renderId = scene.getRenderId();
  42986. this._wasPreviouslyReady = true;
  42987. return true;
  42988. };
  42989. /**
  42990. * Builds the material UBO layouts.
  42991. * Used internally during the effect preparation.
  42992. */
  42993. StandardMaterial.prototype.buildUniformLayout = function () {
  42994. // Order is important !
  42995. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42996. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42997. this._uniformBuffer.addUniform("opacityParts", 4);
  42998. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42999. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43000. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43001. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43002. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43003. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43004. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43005. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43006. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43007. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43008. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43009. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43010. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43011. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43012. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43013. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43014. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43015. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43016. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43017. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43018. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43019. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43020. this._uniformBuffer.addUniform("specularMatrix", 16);
  43021. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43022. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43023. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43024. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43025. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43026. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43027. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43028. this._uniformBuffer.addUniform("pointSize", 1);
  43029. this._uniformBuffer.create();
  43030. };
  43031. /**
  43032. * Unbinds the material from the mesh
  43033. */
  43034. StandardMaterial.prototype.unbind = function () {
  43035. if (this._activeEffect) {
  43036. var needFlag = false;
  43037. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43038. this._activeEffect.setTexture("reflection2DSampler", null);
  43039. needFlag = true;
  43040. }
  43041. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43042. this._activeEffect.setTexture("refraction2DSampler", null);
  43043. needFlag = true;
  43044. }
  43045. if (needFlag) {
  43046. this._markAllSubMeshesAsTexturesDirty();
  43047. }
  43048. }
  43049. _super.prototype.unbind.call(this);
  43050. };
  43051. /**
  43052. * Binds the submesh to this material by preparing the effect and shader to draw
  43053. * @param world defines the world transformation matrix
  43054. * @param mesh defines the mesh containing the submesh
  43055. * @param subMesh defines the submesh to bind the material to
  43056. */
  43057. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43058. var scene = this.getScene();
  43059. var defines = subMesh._materialDefines;
  43060. if (!defines) {
  43061. return;
  43062. }
  43063. var effect = subMesh.effect;
  43064. if (!effect) {
  43065. return;
  43066. }
  43067. this._activeEffect = effect;
  43068. // Matrices
  43069. this.bindOnlyWorldMatrix(world);
  43070. // Normal Matrix
  43071. if (defines.OBJECTSPACE_NORMALMAP) {
  43072. world.toNormalMatrix(this._normalMatrix);
  43073. this.bindOnlyNormalMatrix(this._normalMatrix);
  43074. }
  43075. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43076. // Bones
  43077. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43078. if (mustRebind) {
  43079. this._uniformBuffer.bindToEffect(effect, "Material");
  43080. this.bindViewProjection(effect);
  43081. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43082. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43083. // Fresnel
  43084. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43085. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43086. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43087. }
  43088. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43089. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43090. }
  43091. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43092. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43093. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43094. }
  43095. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43096. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43097. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43098. }
  43099. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43100. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43101. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43102. }
  43103. }
  43104. // Textures
  43105. if (scene.texturesEnabled) {
  43106. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43107. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43108. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43109. if (this._diffuseTexture.hasAlpha) {
  43110. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43111. }
  43112. }
  43113. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43114. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43115. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43116. }
  43117. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43118. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43119. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43120. }
  43121. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43122. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43123. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43124. if (this._reflectionTexture.boundingBoxSize) {
  43125. var cubeTexture = this._reflectionTexture;
  43126. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43127. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43128. }
  43129. }
  43130. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43131. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43132. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43133. }
  43134. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43135. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43136. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43137. }
  43138. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43139. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43140. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43141. }
  43142. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43143. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43144. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43145. if (scene._mirroredCameraPosition) {
  43146. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43147. }
  43148. else {
  43149. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43150. }
  43151. }
  43152. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43153. var depth = 1.0;
  43154. if (!this._refractionTexture.isCube) {
  43155. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43156. if (this._refractionTexture.depth) {
  43157. depth = this._refractionTexture.depth;
  43158. }
  43159. }
  43160. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43161. }
  43162. }
  43163. // Point size
  43164. if (this.pointsCloud) {
  43165. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43166. }
  43167. if (defines.SPECULARTERM) {
  43168. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43169. }
  43170. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43171. // Diffuse
  43172. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43173. }
  43174. // Textures
  43175. if (scene.texturesEnabled) {
  43176. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43177. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43178. }
  43179. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43180. effect.setTexture("ambientSampler", this._ambientTexture);
  43181. }
  43182. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43183. effect.setTexture("opacitySampler", this._opacityTexture);
  43184. }
  43185. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43186. if (this._reflectionTexture.isCube) {
  43187. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43188. }
  43189. else {
  43190. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43191. }
  43192. }
  43193. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43194. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43195. }
  43196. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43197. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43198. }
  43199. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43200. effect.setTexture("specularSampler", this._specularTexture);
  43201. }
  43202. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43203. effect.setTexture("bumpSampler", this._bumpTexture);
  43204. }
  43205. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43206. var depth = 1.0;
  43207. if (this._refractionTexture.isCube) {
  43208. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43209. }
  43210. else {
  43211. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43212. }
  43213. }
  43214. }
  43215. // Clip plane
  43216. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43217. // Colors
  43218. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43219. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43220. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43221. }
  43222. if (mustRebind || !this.isFrozen) {
  43223. // Lights
  43224. if (scene.lightsEnabled && !this._disableLighting) {
  43225. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43226. }
  43227. // View
  43228. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43229. this.bindView(effect);
  43230. }
  43231. // Fog
  43232. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43233. // Morph targets
  43234. if (defines.NUM_MORPH_INFLUENCERS) {
  43235. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43236. }
  43237. // Log. depth
  43238. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43239. // image processing
  43240. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43241. this._imageProcessingConfiguration.bind(this._activeEffect);
  43242. }
  43243. }
  43244. this._uniformBuffer.update();
  43245. this._afterBind(mesh, this._activeEffect);
  43246. };
  43247. /**
  43248. * Get the list of animatables in the material.
  43249. * @returns the list of animatables object used in the material
  43250. */
  43251. StandardMaterial.prototype.getAnimatables = function () {
  43252. var results = [];
  43253. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43254. results.push(this._diffuseTexture);
  43255. }
  43256. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43257. results.push(this._ambientTexture);
  43258. }
  43259. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43260. results.push(this._opacityTexture);
  43261. }
  43262. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43263. results.push(this._reflectionTexture);
  43264. }
  43265. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43266. results.push(this._emissiveTexture);
  43267. }
  43268. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43269. results.push(this._specularTexture);
  43270. }
  43271. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43272. results.push(this._bumpTexture);
  43273. }
  43274. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43275. results.push(this._lightmapTexture);
  43276. }
  43277. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43278. results.push(this._refractionTexture);
  43279. }
  43280. return results;
  43281. };
  43282. /**
  43283. * Gets the active textures from the material
  43284. * @returns an array of textures
  43285. */
  43286. StandardMaterial.prototype.getActiveTextures = function () {
  43287. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43288. if (this._diffuseTexture) {
  43289. activeTextures.push(this._diffuseTexture);
  43290. }
  43291. if (this._ambientTexture) {
  43292. activeTextures.push(this._ambientTexture);
  43293. }
  43294. if (this._opacityTexture) {
  43295. activeTextures.push(this._opacityTexture);
  43296. }
  43297. if (this._reflectionTexture) {
  43298. activeTextures.push(this._reflectionTexture);
  43299. }
  43300. if (this._emissiveTexture) {
  43301. activeTextures.push(this._emissiveTexture);
  43302. }
  43303. if (this._specularTexture) {
  43304. activeTextures.push(this._specularTexture);
  43305. }
  43306. if (this._bumpTexture) {
  43307. activeTextures.push(this._bumpTexture);
  43308. }
  43309. if (this._lightmapTexture) {
  43310. activeTextures.push(this._lightmapTexture);
  43311. }
  43312. if (this._refractionTexture) {
  43313. activeTextures.push(this._refractionTexture);
  43314. }
  43315. return activeTextures;
  43316. };
  43317. /**
  43318. * Specifies if the material uses a texture
  43319. * @param texture defines the texture to check against the material
  43320. * @returns a boolean specifying if the material uses the texture
  43321. */
  43322. StandardMaterial.prototype.hasTexture = function (texture) {
  43323. if (_super.prototype.hasTexture.call(this, texture)) {
  43324. return true;
  43325. }
  43326. if (this._diffuseTexture === texture) {
  43327. return true;
  43328. }
  43329. if (this._ambientTexture === texture) {
  43330. return true;
  43331. }
  43332. if (this._opacityTexture === texture) {
  43333. return true;
  43334. }
  43335. if (this._reflectionTexture === texture) {
  43336. return true;
  43337. }
  43338. if (this._emissiveTexture === texture) {
  43339. return true;
  43340. }
  43341. if (this._specularTexture === texture) {
  43342. return true;
  43343. }
  43344. if (this._bumpTexture === texture) {
  43345. return true;
  43346. }
  43347. if (this._lightmapTexture === texture) {
  43348. return true;
  43349. }
  43350. if (this._refractionTexture === texture) {
  43351. return true;
  43352. }
  43353. return false;
  43354. };
  43355. /**
  43356. * Disposes the material
  43357. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  43358. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  43359. */
  43360. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43361. if (forceDisposeTextures) {
  43362. if (this._diffuseTexture) {
  43363. this._diffuseTexture.dispose();
  43364. }
  43365. if (this._ambientTexture) {
  43366. this._ambientTexture.dispose();
  43367. }
  43368. if (this._opacityTexture) {
  43369. this._opacityTexture.dispose();
  43370. }
  43371. if (this._reflectionTexture) {
  43372. this._reflectionTexture.dispose();
  43373. }
  43374. if (this._emissiveTexture) {
  43375. this._emissiveTexture.dispose();
  43376. }
  43377. if (this._specularTexture) {
  43378. this._specularTexture.dispose();
  43379. }
  43380. if (this._bumpTexture) {
  43381. this._bumpTexture.dispose();
  43382. }
  43383. if (this._lightmapTexture) {
  43384. this._lightmapTexture.dispose();
  43385. }
  43386. if (this._refractionTexture) {
  43387. this._refractionTexture.dispose();
  43388. }
  43389. }
  43390. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43391. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43392. }
  43393. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43394. };
  43395. /**
  43396. * Makes a duplicate of the material, and gives it a new name
  43397. * @param name defines the new name for the duplicated material
  43398. * @returns the cloned material
  43399. */
  43400. StandardMaterial.prototype.clone = function (name) {
  43401. var _this = this;
  43402. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43403. result.name = name;
  43404. result.id = name;
  43405. return result;
  43406. };
  43407. /**
  43408. * Serializes this material in a JSON representation
  43409. * @returns the serialized material object
  43410. */
  43411. StandardMaterial.prototype.serialize = function () {
  43412. return BABYLON.SerializationHelper.Serialize(this);
  43413. };
  43414. /**
  43415. * Creates a standard material from parsed material data
  43416. * @param source defines the JSON represnetation of the material
  43417. * @param scene defines the hosting scene
  43418. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  43419. * @returns a new material
  43420. */
  43421. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43422. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43423. };
  43424. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43425. /**
  43426. * Are diffuse textures enabled in the application.
  43427. */
  43428. get: function () {
  43429. return StandardMaterial._DiffuseTextureEnabled;
  43430. },
  43431. set: function (value) {
  43432. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43433. return;
  43434. }
  43435. StandardMaterial._DiffuseTextureEnabled = value;
  43436. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43437. },
  43438. enumerable: true,
  43439. configurable: true
  43440. });
  43441. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43442. /**
  43443. * Are ambient textures enabled in the application.
  43444. */
  43445. get: function () {
  43446. return StandardMaterial._AmbientTextureEnabled;
  43447. },
  43448. set: function (value) {
  43449. if (StandardMaterial._AmbientTextureEnabled === value) {
  43450. return;
  43451. }
  43452. StandardMaterial._AmbientTextureEnabled = value;
  43453. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43454. },
  43455. enumerable: true,
  43456. configurable: true
  43457. });
  43458. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43459. /**
  43460. * Are opacity textures enabled in the application.
  43461. */
  43462. get: function () {
  43463. return StandardMaterial._OpacityTextureEnabled;
  43464. },
  43465. set: function (value) {
  43466. if (StandardMaterial._OpacityTextureEnabled === value) {
  43467. return;
  43468. }
  43469. StandardMaterial._OpacityTextureEnabled = value;
  43470. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43471. },
  43472. enumerable: true,
  43473. configurable: true
  43474. });
  43475. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43476. /**
  43477. * Are reflection textures enabled in the application.
  43478. */
  43479. get: function () {
  43480. return StandardMaterial._ReflectionTextureEnabled;
  43481. },
  43482. set: function (value) {
  43483. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43484. return;
  43485. }
  43486. StandardMaterial._ReflectionTextureEnabled = value;
  43487. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43488. },
  43489. enumerable: true,
  43490. configurable: true
  43491. });
  43492. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43493. /**
  43494. * Are emissive textures enabled in the application.
  43495. */
  43496. get: function () {
  43497. return StandardMaterial._EmissiveTextureEnabled;
  43498. },
  43499. set: function (value) {
  43500. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43501. return;
  43502. }
  43503. StandardMaterial._EmissiveTextureEnabled = value;
  43504. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43505. },
  43506. enumerable: true,
  43507. configurable: true
  43508. });
  43509. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43510. /**
  43511. * Are specular textures enabled in the application.
  43512. */
  43513. get: function () {
  43514. return StandardMaterial._SpecularTextureEnabled;
  43515. },
  43516. set: function (value) {
  43517. if (StandardMaterial._SpecularTextureEnabled === value) {
  43518. return;
  43519. }
  43520. StandardMaterial._SpecularTextureEnabled = value;
  43521. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43522. },
  43523. enumerable: true,
  43524. configurable: true
  43525. });
  43526. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43527. /**
  43528. * Are bump textures enabled in the application.
  43529. */
  43530. get: function () {
  43531. return StandardMaterial._BumpTextureEnabled;
  43532. },
  43533. set: function (value) {
  43534. if (StandardMaterial._BumpTextureEnabled === value) {
  43535. return;
  43536. }
  43537. StandardMaterial._BumpTextureEnabled = value;
  43538. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43539. },
  43540. enumerable: true,
  43541. configurable: true
  43542. });
  43543. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43544. /**
  43545. * Are lightmap textures enabled in the application.
  43546. */
  43547. get: function () {
  43548. return StandardMaterial._LightmapTextureEnabled;
  43549. },
  43550. set: function (value) {
  43551. if (StandardMaterial._LightmapTextureEnabled === value) {
  43552. return;
  43553. }
  43554. StandardMaterial._LightmapTextureEnabled = value;
  43555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43556. },
  43557. enumerable: true,
  43558. configurable: true
  43559. });
  43560. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43561. /**
  43562. * Are refraction textures enabled in the application.
  43563. */
  43564. get: function () {
  43565. return StandardMaterial._RefractionTextureEnabled;
  43566. },
  43567. set: function (value) {
  43568. if (StandardMaterial._RefractionTextureEnabled === value) {
  43569. return;
  43570. }
  43571. StandardMaterial._RefractionTextureEnabled = value;
  43572. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43573. },
  43574. enumerable: true,
  43575. configurable: true
  43576. });
  43577. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43578. /**
  43579. * Are color grading textures enabled in the application.
  43580. */
  43581. get: function () {
  43582. return StandardMaterial._ColorGradingTextureEnabled;
  43583. },
  43584. set: function (value) {
  43585. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43586. return;
  43587. }
  43588. StandardMaterial._ColorGradingTextureEnabled = value;
  43589. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43590. },
  43591. enumerable: true,
  43592. configurable: true
  43593. });
  43594. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43595. /**
  43596. * Are fresnels enabled in the application.
  43597. */
  43598. get: function () {
  43599. return StandardMaterial._FresnelEnabled;
  43600. },
  43601. set: function (value) {
  43602. if (StandardMaterial._FresnelEnabled === value) {
  43603. return;
  43604. }
  43605. StandardMaterial._FresnelEnabled = value;
  43606. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43607. },
  43608. enumerable: true,
  43609. configurable: true
  43610. });
  43611. // Flags used to enable or disable a type of texture for all Standard Materials
  43612. StandardMaterial._DiffuseTextureEnabled = true;
  43613. StandardMaterial._AmbientTextureEnabled = true;
  43614. StandardMaterial._OpacityTextureEnabled = true;
  43615. StandardMaterial._ReflectionTextureEnabled = true;
  43616. StandardMaterial._EmissiveTextureEnabled = true;
  43617. StandardMaterial._SpecularTextureEnabled = true;
  43618. StandardMaterial._BumpTextureEnabled = true;
  43619. StandardMaterial._LightmapTextureEnabled = true;
  43620. StandardMaterial._RefractionTextureEnabled = true;
  43621. StandardMaterial._ColorGradingTextureEnabled = true;
  43622. StandardMaterial._FresnelEnabled = true;
  43623. __decorate([
  43624. BABYLON.serializeAsTexture("diffuseTexture")
  43625. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43626. __decorate([
  43627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43628. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43629. __decorate([
  43630. BABYLON.serializeAsTexture("ambientTexture")
  43631. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43632. __decorate([
  43633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43634. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43635. __decorate([
  43636. BABYLON.serializeAsTexture("opacityTexture")
  43637. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43638. __decorate([
  43639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43640. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43641. __decorate([
  43642. BABYLON.serializeAsTexture("reflectionTexture")
  43643. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43644. __decorate([
  43645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43646. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43647. __decorate([
  43648. BABYLON.serializeAsTexture("emissiveTexture")
  43649. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43650. __decorate([
  43651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43652. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43653. __decorate([
  43654. BABYLON.serializeAsTexture("specularTexture")
  43655. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43656. __decorate([
  43657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43658. ], StandardMaterial.prototype, "specularTexture", void 0);
  43659. __decorate([
  43660. BABYLON.serializeAsTexture("bumpTexture")
  43661. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43662. __decorate([
  43663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43664. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43665. __decorate([
  43666. BABYLON.serializeAsTexture("lightmapTexture")
  43667. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43668. __decorate([
  43669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43670. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43671. __decorate([
  43672. BABYLON.serializeAsTexture("refractionTexture")
  43673. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43674. __decorate([
  43675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43676. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43677. __decorate([
  43678. BABYLON.serializeAsColor3("ambient")
  43679. ], StandardMaterial.prototype, "ambientColor", void 0);
  43680. __decorate([
  43681. BABYLON.serializeAsColor3("diffuse")
  43682. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43683. __decorate([
  43684. BABYLON.serializeAsColor3("specular")
  43685. ], StandardMaterial.prototype, "specularColor", void 0);
  43686. __decorate([
  43687. BABYLON.serializeAsColor3("emissive")
  43688. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43689. __decorate([
  43690. BABYLON.serialize()
  43691. ], StandardMaterial.prototype, "specularPower", void 0);
  43692. __decorate([
  43693. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43694. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43695. __decorate([
  43696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43697. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43698. __decorate([
  43699. BABYLON.serialize("useEmissiveAsIllumination")
  43700. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43701. __decorate([
  43702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43703. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43704. __decorate([
  43705. BABYLON.serialize("linkEmissiveWithDiffuse")
  43706. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43707. __decorate([
  43708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43709. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43710. __decorate([
  43711. BABYLON.serialize("useSpecularOverAlpha")
  43712. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43713. __decorate([
  43714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43715. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43716. __decorate([
  43717. BABYLON.serialize("useReflectionOverAlpha")
  43718. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43719. __decorate([
  43720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43721. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43722. __decorate([
  43723. BABYLON.serialize("disableLighting")
  43724. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43725. __decorate([
  43726. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43727. ], StandardMaterial.prototype, "disableLighting", void 0);
  43728. __decorate([
  43729. BABYLON.serialize("useObjectSpaceNormalMap")
  43730. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43731. __decorate([
  43732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43733. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43734. __decorate([
  43735. BABYLON.serialize("useParallax")
  43736. ], StandardMaterial.prototype, "_useParallax", void 0);
  43737. __decorate([
  43738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43739. ], StandardMaterial.prototype, "useParallax", void 0);
  43740. __decorate([
  43741. BABYLON.serialize("useParallaxOcclusion")
  43742. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43743. __decorate([
  43744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43745. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43746. __decorate([
  43747. BABYLON.serialize()
  43748. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43749. __decorate([
  43750. BABYLON.serialize("roughness")
  43751. ], StandardMaterial.prototype, "_roughness", void 0);
  43752. __decorate([
  43753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43754. ], StandardMaterial.prototype, "roughness", void 0);
  43755. __decorate([
  43756. BABYLON.serialize()
  43757. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43758. __decorate([
  43759. BABYLON.serialize()
  43760. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43761. __decorate([
  43762. BABYLON.serialize()
  43763. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43764. __decorate([
  43765. BABYLON.serialize("useLightmapAsShadowmap")
  43766. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43767. __decorate([
  43768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43769. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43770. __decorate([
  43771. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43772. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43773. __decorate([
  43774. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43775. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43776. __decorate([
  43777. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43778. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43779. __decorate([
  43780. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43781. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43782. __decorate([
  43783. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43784. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43785. __decorate([
  43786. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43787. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43788. __decorate([
  43789. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43790. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43791. __decorate([
  43792. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43793. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43794. __decorate([
  43795. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43796. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43797. __decorate([
  43798. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43799. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43800. __decorate([
  43801. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43802. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43803. __decorate([
  43804. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43805. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43806. __decorate([
  43807. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43808. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43809. __decorate([
  43810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43811. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43812. __decorate([
  43813. BABYLON.serialize("maxSimultaneousLights")
  43814. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43815. __decorate([
  43816. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43817. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43818. __decorate([
  43819. BABYLON.serialize("invertNormalMapX")
  43820. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43821. __decorate([
  43822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43823. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43824. __decorate([
  43825. BABYLON.serialize("invertNormalMapY")
  43826. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43827. __decorate([
  43828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43829. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43830. __decorate([
  43831. BABYLON.serialize("twoSidedLighting")
  43832. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43833. __decorate([
  43834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43835. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43836. __decorate([
  43837. BABYLON.serialize()
  43838. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43839. return StandardMaterial;
  43840. }(BABYLON.PushMaterial));
  43841. BABYLON.StandardMaterial = StandardMaterial;
  43842. })(BABYLON || (BABYLON = {}));
  43843. //# sourceMappingURL=babylon.standardMaterial.js.map
  43844. var BABYLON;
  43845. (function (BABYLON) {
  43846. /**
  43847. * Class representing spherical polynomial coefficients to the 3rd degree
  43848. */
  43849. var SphericalPolynomial = /** @class */ (function () {
  43850. function SphericalPolynomial() {
  43851. /**
  43852. * The x coefficients of the spherical polynomial
  43853. */
  43854. this.x = BABYLON.Vector3.Zero();
  43855. /**
  43856. * The y coefficients of the spherical polynomial
  43857. */
  43858. this.y = BABYLON.Vector3.Zero();
  43859. /**
  43860. * The z coefficients of the spherical polynomial
  43861. */
  43862. this.z = BABYLON.Vector3.Zero();
  43863. /**
  43864. * The xx coefficients of the spherical polynomial
  43865. */
  43866. this.xx = BABYLON.Vector3.Zero();
  43867. /**
  43868. * The yy coefficients of the spherical polynomial
  43869. */
  43870. this.yy = BABYLON.Vector3.Zero();
  43871. /**
  43872. * The zz coefficients of the spherical polynomial
  43873. */
  43874. this.zz = BABYLON.Vector3.Zero();
  43875. /**
  43876. * The xy coefficients of the spherical polynomial
  43877. */
  43878. this.xy = BABYLON.Vector3.Zero();
  43879. /**
  43880. * The yz coefficients of the spherical polynomial
  43881. */
  43882. this.yz = BABYLON.Vector3.Zero();
  43883. /**
  43884. * The zx coefficients of the spherical polynomial
  43885. */
  43886. this.zx = BABYLON.Vector3.Zero();
  43887. }
  43888. /**
  43889. * Adds an ambient color to the spherical polynomial
  43890. * @param color the color to add
  43891. */
  43892. SphericalPolynomial.prototype.addAmbient = function (color) {
  43893. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43894. this.xx = this.xx.add(colorVector);
  43895. this.yy = this.yy.add(colorVector);
  43896. this.zz = this.zz.add(colorVector);
  43897. };
  43898. /**
  43899. * Scales the spherical polynomial by the given amount
  43900. * @param scale the amount to scale
  43901. */
  43902. SphericalPolynomial.prototype.scale = function (scale) {
  43903. this.x = this.x.scale(scale);
  43904. this.y = this.y.scale(scale);
  43905. this.z = this.z.scale(scale);
  43906. this.xx = this.xx.scale(scale);
  43907. this.yy = this.yy.scale(scale);
  43908. this.zz = this.zz.scale(scale);
  43909. this.yz = this.yz.scale(scale);
  43910. this.zx = this.zx.scale(scale);
  43911. this.xy = this.xy.scale(scale);
  43912. };
  43913. /**
  43914. * Gets the spherical polynomial from harmonics
  43915. * @param harmonics the spherical harmonics
  43916. * @returns the spherical polynomial
  43917. */
  43918. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43919. var result = new SphericalPolynomial();
  43920. result.x = harmonics.l11.scale(1.02333);
  43921. result.y = harmonics.l1_1.scale(1.02333);
  43922. result.z = harmonics.l10.scale(1.02333);
  43923. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43924. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43925. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43926. result.yz = harmonics.l2_1.scale(0.858086);
  43927. result.zx = harmonics.l21.scale(0.858086);
  43928. result.xy = harmonics.l2_2.scale(0.858086);
  43929. result.scale(1.0 / Math.PI);
  43930. return result;
  43931. };
  43932. /**
  43933. * Constructs a spherical polynomial from an array.
  43934. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43935. * @returns the spherical polynomial
  43936. */
  43937. SphericalPolynomial.FromArray = function (data) {
  43938. var sp = new SphericalPolynomial();
  43939. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43940. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43941. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43942. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43943. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43944. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43945. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43946. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43947. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43948. return sp;
  43949. };
  43950. return SphericalPolynomial;
  43951. }());
  43952. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43953. /**
  43954. * Class representing spherical harmonics coefficients to the 3rd degree
  43955. */
  43956. var SphericalHarmonics = /** @class */ (function () {
  43957. function SphericalHarmonics() {
  43958. /**
  43959. * The l0,0 coefficients of the spherical harmonics
  43960. */
  43961. this.l00 = BABYLON.Vector3.Zero();
  43962. /**
  43963. * The l1,-1 coefficients of the spherical harmonics
  43964. */
  43965. this.l1_1 = BABYLON.Vector3.Zero();
  43966. /**
  43967. * The l1,0 coefficients of the spherical harmonics
  43968. */
  43969. this.l10 = BABYLON.Vector3.Zero();
  43970. /**
  43971. * The l1,1 coefficients of the spherical harmonics
  43972. */
  43973. this.l11 = BABYLON.Vector3.Zero();
  43974. /**
  43975. * The l2,-2 coefficients of the spherical harmonics
  43976. */
  43977. this.l2_2 = BABYLON.Vector3.Zero();
  43978. /**
  43979. * The l2,-1 coefficients of the spherical harmonics
  43980. */
  43981. this.l2_1 = BABYLON.Vector3.Zero();
  43982. /**
  43983. * The l2,0 coefficients of the spherical harmonics
  43984. */
  43985. this.l20 = BABYLON.Vector3.Zero();
  43986. /**
  43987. * The l2,1 coefficients of the spherical harmonics
  43988. */
  43989. this.l21 = BABYLON.Vector3.Zero();
  43990. /**
  43991. * The l2,2 coefficients of the spherical harmonics
  43992. */
  43993. this.lL22 = BABYLON.Vector3.Zero();
  43994. }
  43995. /**
  43996. * Adds a light to the spherical harmonics
  43997. * @param direction the direction of the light
  43998. * @param color the color of the light
  43999. * @param deltaSolidAngle the delta solid angle of the light
  44000. */
  44001. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44002. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44003. var c = colorVector.scale(deltaSolidAngle);
  44004. this.l00 = this.l00.add(c.scale(0.282095));
  44005. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44006. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44007. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44008. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44009. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44010. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44011. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44012. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44013. };
  44014. /**
  44015. * Scales the spherical harmonics by the given amount
  44016. * @param scale the amount to scale
  44017. */
  44018. SphericalHarmonics.prototype.scale = function (scale) {
  44019. this.l00 = this.l00.scale(scale);
  44020. this.l1_1 = this.l1_1.scale(scale);
  44021. this.l10 = this.l10.scale(scale);
  44022. this.l11 = this.l11.scale(scale);
  44023. this.l2_2 = this.l2_2.scale(scale);
  44024. this.l2_1 = this.l2_1.scale(scale);
  44025. this.l20 = this.l20.scale(scale);
  44026. this.l21 = this.l21.scale(scale);
  44027. this.lL22 = this.lL22.scale(scale);
  44028. };
  44029. /**
  44030. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44031. *
  44032. * ```
  44033. * E_lm = A_l * L_lm
  44034. * ```
  44035. *
  44036. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44037. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44038. * the scaling factors are given in equation 9.
  44039. */
  44040. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44041. // Constant (Band 0)
  44042. this.l00 = this.l00.scale(3.141593);
  44043. // Linear (Band 1)
  44044. this.l1_1 = this.l1_1.scale(2.094395);
  44045. this.l10 = this.l10.scale(2.094395);
  44046. this.l11 = this.l11.scale(2.094395);
  44047. // Quadratic (Band 2)
  44048. this.l2_2 = this.l2_2.scale(0.785398);
  44049. this.l2_1 = this.l2_1.scale(0.785398);
  44050. this.l20 = this.l20.scale(0.785398);
  44051. this.l21 = this.l21.scale(0.785398);
  44052. this.lL22 = this.lL22.scale(0.785398);
  44053. };
  44054. /**
  44055. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44056. *
  44057. * ```
  44058. * L = (1/pi) * E * rho
  44059. * ```
  44060. *
  44061. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44062. */
  44063. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44064. this.scale(1.0 / Math.PI);
  44065. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44066. // (The pixel shader must apply albedo after texture fetches, etc).
  44067. };
  44068. /**
  44069. * Gets the spherical harmonics from polynomial
  44070. * @param polynomial the spherical polynomial
  44071. * @returns the spherical harmonics
  44072. */
  44073. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44074. var result = new SphericalHarmonics();
  44075. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44076. result.l1_1 = polynomial.y.scale(0.977204);
  44077. result.l10 = polynomial.z.scale(0.977204);
  44078. result.l11 = polynomial.x.scale(0.977204);
  44079. result.l2_2 = polynomial.xy.scale(1.16538);
  44080. result.l2_1 = polynomial.yz.scale(1.16538);
  44081. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44082. result.l21 = polynomial.zx.scale(1.16538);
  44083. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44084. result.scale(Math.PI);
  44085. return result;
  44086. };
  44087. /**
  44088. * Constructs a spherical harmonics from an array.
  44089. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44090. * @returns the spherical harmonics
  44091. */
  44092. SphericalHarmonics.FromArray = function (data) {
  44093. var sh = new SphericalHarmonics();
  44094. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44095. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44096. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44097. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44098. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44099. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44100. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44101. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44102. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44103. return sh;
  44104. };
  44105. return SphericalHarmonics;
  44106. }());
  44107. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44108. })(BABYLON || (BABYLON = {}));
  44109. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44110. var BABYLON;
  44111. (function (BABYLON) {
  44112. var FileFaceOrientation = /** @class */ (function () {
  44113. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44114. this.name = name;
  44115. this.worldAxisForNormal = worldAxisForNormal;
  44116. this.worldAxisForFileX = worldAxisForFileX;
  44117. this.worldAxisForFileY = worldAxisForFileY;
  44118. }
  44119. return FileFaceOrientation;
  44120. }());
  44121. ;
  44122. /**
  44123. * Helper class dealing with the extraction of spherical polynomial dataArray
  44124. * from a cube map.
  44125. */
  44126. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44127. function CubeMapToSphericalPolynomialTools() {
  44128. }
  44129. /**
  44130. * Converts a texture to the according Spherical Polynomial data.
  44131. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44132. *
  44133. * @param texture The texture to extract the information from.
  44134. * @return The Spherical Polynomial data.
  44135. */
  44136. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44137. if (!texture.isCube) {
  44138. // Only supports cube Textures currently.
  44139. return null;
  44140. }
  44141. var size = texture.getSize().width;
  44142. var right = texture.readPixels(0);
  44143. var left = texture.readPixels(1);
  44144. var up;
  44145. var down;
  44146. if (texture.isRenderTarget) {
  44147. up = texture.readPixels(3);
  44148. down = texture.readPixels(2);
  44149. }
  44150. else {
  44151. up = texture.readPixels(2);
  44152. down = texture.readPixels(3);
  44153. }
  44154. var front = texture.readPixels(4);
  44155. var back = texture.readPixels(5);
  44156. var gammaSpace = texture.gammaSpace;
  44157. // Always read as RGBA.
  44158. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44159. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44160. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44161. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44162. }
  44163. var cubeInfo = {
  44164. size: size,
  44165. right: right,
  44166. left: left,
  44167. up: up,
  44168. down: down,
  44169. front: front,
  44170. back: back,
  44171. format: format,
  44172. type: type,
  44173. gammaSpace: gammaSpace,
  44174. };
  44175. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44176. };
  44177. /**
  44178. * Converts a cubemap to the according Spherical Polynomial data.
  44179. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44180. *
  44181. * @param cubeInfo The Cube map to extract the information from.
  44182. * @return The Spherical Polynomial data.
  44183. */
  44184. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44185. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44186. var totalSolidAngle = 0.0;
  44187. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44188. var du = 2.0 / cubeInfo.size;
  44189. var dv = du;
  44190. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44191. var minUV = du * 0.5 - 1.0;
  44192. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44193. var fileFace = this.FileFaces[faceIndex];
  44194. var dataArray = cubeInfo[fileFace.name];
  44195. var v = minUV;
  44196. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44197. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44198. // Because SP is still linear, so summation is fine in that basis.
  44199. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44200. for (var y = 0; y < cubeInfo.size; y++) {
  44201. var u = minUV;
  44202. for (var x = 0; x < cubeInfo.size; x++) {
  44203. // World direction (not normalised)
  44204. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44205. worldDirection.normalize();
  44206. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44207. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44208. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44209. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44210. // Handle Integer types.
  44211. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44212. r /= 255;
  44213. g /= 255;
  44214. b /= 255;
  44215. }
  44216. // Handle Gamma space textures.
  44217. if (cubeInfo.gammaSpace) {
  44218. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44219. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44220. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44221. }
  44222. var color = new BABYLON.Color3(r, g, b);
  44223. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44224. totalSolidAngle += deltaSolidAngle;
  44225. u += du;
  44226. }
  44227. v += dv;
  44228. }
  44229. }
  44230. // Solid angle for entire sphere is 4*pi
  44231. var sphereSolidAngle = 4.0 * Math.PI;
  44232. // Adjust the solid angle to allow for how many faces we processed.
  44233. var facesProcessed = 6.0;
  44234. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44235. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44236. // This is needed because the numerical integration over the cube uses a
  44237. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44238. // and also to compensate for accumulative error due to float precision in the summation.
  44239. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44240. sphericalHarmonics.scale(correctionFactor);
  44241. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44242. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44243. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44244. };
  44245. CubeMapToSphericalPolynomialTools.FileFaces = [
  44246. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44247. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44248. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44249. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44250. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44251. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44252. ];
  44253. return CubeMapToSphericalPolynomialTools;
  44254. }());
  44255. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44256. })(BABYLON || (BABYLON = {}));
  44257. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44258. var BABYLON;
  44259. (function (BABYLON) {
  44260. /**
  44261. * Manages the defines for the PBR Material.
  44262. * @hiddenChildren
  44263. */
  44264. var PBRMaterialDefines = /** @class */ (function (_super) {
  44265. __extends(PBRMaterialDefines, _super);
  44266. /**
  44267. * Initializes the PBR Material defines.
  44268. */
  44269. function PBRMaterialDefines() {
  44270. var _this = _super.call(this) || this;
  44271. _this.PBR = true;
  44272. _this.MAINUV1 = false;
  44273. _this.MAINUV2 = false;
  44274. _this.UV1 = false;
  44275. _this.UV2 = false;
  44276. _this.ALBEDO = false;
  44277. _this.ALBEDODIRECTUV = 0;
  44278. _this.VERTEXCOLOR = false;
  44279. _this.AMBIENT = false;
  44280. _this.AMBIENTDIRECTUV = 0;
  44281. _this.AMBIENTINGRAYSCALE = false;
  44282. _this.OPACITY = false;
  44283. _this.VERTEXALPHA = false;
  44284. _this.OPACITYDIRECTUV = 0;
  44285. _this.OPACITYRGB = false;
  44286. _this.ALPHATEST = false;
  44287. _this.DEPTHPREPASS = false;
  44288. _this.ALPHABLEND = false;
  44289. _this.ALPHAFROMALBEDO = false;
  44290. _this.ALPHATESTVALUE = "0.5";
  44291. _this.SPECULAROVERALPHA = false;
  44292. _this.RADIANCEOVERALPHA = false;
  44293. _this.ALPHAFRESNEL = false;
  44294. _this.LINEARALPHAFRESNEL = false;
  44295. _this.PREMULTIPLYALPHA = false;
  44296. _this.EMISSIVE = false;
  44297. _this.EMISSIVEDIRECTUV = 0;
  44298. _this.REFLECTIVITY = false;
  44299. _this.REFLECTIVITYDIRECTUV = 0;
  44300. _this.SPECULARTERM = false;
  44301. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44302. _this.MICROSURFACEAUTOMATIC = false;
  44303. _this.LODBASEDMICROSFURACE = false;
  44304. _this.MICROSURFACEMAP = false;
  44305. _this.MICROSURFACEMAPDIRECTUV = 0;
  44306. _this.METALLICWORKFLOW = false;
  44307. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44308. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44309. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44310. _this.AOSTOREINMETALMAPRED = false;
  44311. _this.ENVIRONMENTBRDF = false;
  44312. _this.NORMAL = false;
  44313. _this.TANGENT = false;
  44314. _this.BUMP = false;
  44315. _this.BUMPDIRECTUV = 0;
  44316. _this.OBJECTSPACE_NORMALMAP = false;
  44317. _this.PARALLAX = false;
  44318. _this.PARALLAXOCCLUSION = false;
  44319. _this.NORMALXYSCALE = true;
  44320. _this.LIGHTMAP = false;
  44321. _this.LIGHTMAPDIRECTUV = 0;
  44322. _this.USELIGHTMAPASSHADOWMAP = false;
  44323. _this.GAMMALIGHTMAP = false;
  44324. _this.REFLECTION = false;
  44325. _this.REFLECTIONMAP_3D = false;
  44326. _this.REFLECTIONMAP_SPHERICAL = false;
  44327. _this.REFLECTIONMAP_PLANAR = false;
  44328. _this.REFLECTIONMAP_CUBIC = false;
  44329. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44330. _this.REFLECTIONMAP_PROJECTION = false;
  44331. _this.REFLECTIONMAP_SKYBOX = false;
  44332. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44333. _this.REFLECTIONMAP_EXPLICIT = false;
  44334. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44335. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44336. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44337. _this.INVERTCUBICMAP = false;
  44338. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44339. _this.USESPHERICALINVERTEX = false;
  44340. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44341. _this.LODINREFLECTIONALPHA = false;
  44342. _this.GAMMAREFLECTION = false;
  44343. _this.RGBDREFLECTION = false;
  44344. _this.RADIANCEOCCLUSION = false;
  44345. _this.HORIZONOCCLUSION = false;
  44346. _this.REFRACTION = false;
  44347. _this.REFRACTIONMAP_3D = false;
  44348. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44349. _this.LODINREFRACTIONALPHA = false;
  44350. _this.GAMMAREFRACTION = false;
  44351. _this.RGBDREFRACTION = false;
  44352. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44353. _this.INSTANCES = false;
  44354. _this.NUM_BONE_INFLUENCERS = 0;
  44355. _this.BonesPerMesh = 0;
  44356. _this.NONUNIFORMSCALING = false;
  44357. _this.MORPHTARGETS = false;
  44358. _this.MORPHTARGETS_NORMAL = false;
  44359. _this.MORPHTARGETS_TANGENT = false;
  44360. _this.NUM_MORPH_INFLUENCERS = 0;
  44361. _this.IMAGEPROCESSING = false;
  44362. _this.VIGNETTE = false;
  44363. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44364. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44365. _this.TONEMAPPING = false;
  44366. _this.TONEMAPPING_ACES = false;
  44367. _this.CONTRAST = false;
  44368. _this.COLORCURVES = false;
  44369. _this.COLORGRADING = false;
  44370. _this.COLORGRADING3D = false;
  44371. _this.SAMPLER3DGREENDEPTH = false;
  44372. _this.SAMPLER3DBGRMAP = false;
  44373. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44374. _this.EXPOSURE = false;
  44375. _this.USEPHYSICALLIGHTFALLOFF = false;
  44376. _this.USEGLTFLIGHTFALLOFF = false;
  44377. _this.TWOSIDEDLIGHTING = false;
  44378. _this.SHADOWFLOAT = false;
  44379. _this.CLIPPLANE = false;
  44380. _this.CLIPPLANE2 = false;
  44381. _this.CLIPPLANE3 = false;
  44382. _this.CLIPPLANE4 = false;
  44383. _this.POINTSIZE = false;
  44384. _this.FOG = false;
  44385. _this.LOGARITHMICDEPTH = false;
  44386. _this.FORCENORMALFORWARD = false;
  44387. _this.SPECULARAA = false;
  44388. _this.UNLIT = false;
  44389. _this.rebuild();
  44390. return _this;
  44391. }
  44392. /**
  44393. * Resets the PBR Material defines.
  44394. */
  44395. PBRMaterialDefines.prototype.reset = function () {
  44396. _super.prototype.reset.call(this);
  44397. this.ALPHATESTVALUE = "0.5";
  44398. this.PBR = true;
  44399. };
  44400. return PBRMaterialDefines;
  44401. }(BABYLON.MaterialDefines));
  44402. /**
  44403. * The Physically based material base class of BJS.
  44404. *
  44405. * This offers the main features of a standard PBR material.
  44406. * For more information, please refer to the documentation :
  44407. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44408. */
  44409. var PBRBaseMaterial = /** @class */ (function (_super) {
  44410. __extends(PBRBaseMaterial, _super);
  44411. /**
  44412. * Instantiates a new PBRMaterial instance.
  44413. *
  44414. * @param name The material name
  44415. * @param scene The scene the material will be use in.
  44416. */
  44417. function PBRBaseMaterial(name, scene) {
  44418. var _this = _super.call(this, name, scene) || this;
  44419. /**
  44420. * Intensity of the direct lights e.g. the four lights available in your scene.
  44421. * This impacts both the direct diffuse and specular highlights.
  44422. */
  44423. _this._directIntensity = 1.0;
  44424. /**
  44425. * Intensity of the emissive part of the material.
  44426. * This helps controlling the emissive effect without modifying the emissive color.
  44427. */
  44428. _this._emissiveIntensity = 1.0;
  44429. /**
  44430. * Intensity of the environment e.g. how much the environment will light the object
  44431. * either through harmonics for rough material or through the refelction for shiny ones.
  44432. */
  44433. _this._environmentIntensity = 1.0;
  44434. /**
  44435. * This is a special control allowing the reduction of the specular highlights coming from the
  44436. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44437. */
  44438. _this._specularIntensity = 1.0;
  44439. /**
  44440. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44441. */
  44442. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44443. /**
  44444. * Debug Control allowing disabling the bump map on this material.
  44445. */
  44446. _this._disableBumpMap = false;
  44447. /**
  44448. * AKA Occlusion Texture Intensity in other nomenclature.
  44449. */
  44450. _this._ambientTextureStrength = 1.0;
  44451. /**
  44452. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44453. * 1 means it completely occludes it
  44454. * 0 mean it has no impact
  44455. */
  44456. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44457. /**
  44458. * The color of a material in ambient lighting.
  44459. */
  44460. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44461. /**
  44462. * AKA Diffuse Color in other nomenclature.
  44463. */
  44464. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44465. /**
  44466. * AKA Specular Color in other nomenclature.
  44467. */
  44468. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44469. /**
  44470. * The color applied when light is reflected from a material.
  44471. */
  44472. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44473. /**
  44474. * The color applied when light is emitted from a material.
  44475. */
  44476. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44477. /**
  44478. * AKA Glossiness in other nomenclature.
  44479. */
  44480. _this._microSurface = 0.9;
  44481. /**
  44482. * source material index of refraction (IOR)' / 'destination material IOR.
  44483. */
  44484. _this._indexOfRefraction = 0.66;
  44485. /**
  44486. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44487. */
  44488. _this._invertRefractionY = false;
  44489. /**
  44490. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44491. * Materials half opaque for instance using refraction could benefit from this control.
  44492. */
  44493. _this._linkRefractionWithTransparency = false;
  44494. /**
  44495. * Specifies that the material will use the light map as a show map.
  44496. */
  44497. _this._useLightmapAsShadowmap = false;
  44498. /**
  44499. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44500. * makes the reflect vector face the model (under horizon).
  44501. */
  44502. _this._useHorizonOcclusion = true;
  44503. /**
  44504. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44505. * too much the area relying on ambient texture to define their ambient occlusion.
  44506. */
  44507. _this._useRadianceOcclusion = true;
  44508. /**
  44509. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44510. */
  44511. _this._useAlphaFromAlbedoTexture = false;
  44512. /**
  44513. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44514. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44515. */
  44516. _this._useSpecularOverAlpha = true;
  44517. /**
  44518. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44519. */
  44520. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44521. /**
  44522. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44523. */
  44524. _this._useRoughnessFromMetallicTextureAlpha = true;
  44525. /**
  44526. * Specifies if the metallic texture contains the roughness information in its green channel.
  44527. */
  44528. _this._useRoughnessFromMetallicTextureGreen = false;
  44529. /**
  44530. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44531. */
  44532. _this._useMetallnessFromMetallicTextureBlue = false;
  44533. /**
  44534. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44535. */
  44536. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44537. /**
  44538. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44539. */
  44540. _this._useAmbientInGrayScale = false;
  44541. /**
  44542. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44543. * The material will try to infer what glossiness each pixel should be.
  44544. */
  44545. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44546. /**
  44547. * Defines the falloff type used in this material.
  44548. * It by default is Physical.
  44549. */
  44550. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44551. /**
  44552. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44553. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44554. */
  44555. _this._useRadianceOverAlpha = true;
  44556. /**
  44557. * Allows using an object space normal map (instead of tangent space).
  44558. */
  44559. _this._useObjectSpaceNormalMap = false;
  44560. /**
  44561. * Allows using the bump map in parallax mode.
  44562. */
  44563. _this._useParallax = false;
  44564. /**
  44565. * Allows using the bump map in parallax occlusion mode.
  44566. */
  44567. _this._useParallaxOcclusion = false;
  44568. /**
  44569. * Controls the scale bias of the parallax mode.
  44570. */
  44571. _this._parallaxScaleBias = 0.05;
  44572. /**
  44573. * If sets to true, disables all the lights affecting the material.
  44574. */
  44575. _this._disableLighting = false;
  44576. /**
  44577. * Number of Simultaneous lights allowed on the material.
  44578. */
  44579. _this._maxSimultaneousLights = 4;
  44580. /**
  44581. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44582. */
  44583. _this._invertNormalMapX = false;
  44584. /**
  44585. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44586. */
  44587. _this._invertNormalMapY = false;
  44588. /**
  44589. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44590. */
  44591. _this._twoSidedLighting = false;
  44592. /**
  44593. * Defines the alpha limits in alpha test mode.
  44594. */
  44595. _this._alphaCutOff = 0.4;
  44596. /**
  44597. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44598. */
  44599. _this._forceAlphaTest = false;
  44600. /**
  44601. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44602. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44603. */
  44604. _this._useAlphaFresnel = false;
  44605. /**
  44606. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44607. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44608. */
  44609. _this._useLinearAlphaFresnel = false;
  44610. /**
  44611. * The transparency mode of the material.
  44612. */
  44613. _this._transparencyMode = null;
  44614. /**
  44615. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44616. * from cos thetav and roughness:
  44617. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44618. */
  44619. _this._environmentBRDFTexture = null;
  44620. /**
  44621. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44622. */
  44623. _this._forceIrradianceInFragment = false;
  44624. /**
  44625. * Force normal to face away from face.
  44626. */
  44627. _this._forceNormalForward = false;
  44628. /**
  44629. * Enables specular anti aliasing in the PBR shader.
  44630. * It will both interacts on the Geometry for analytical and IBL lighting.
  44631. * It also prefilter the roughness map based on the bump values.
  44632. */
  44633. _this._enableSpecularAntiAliasing = false;
  44634. /**
  44635. * Stores the available render targets.
  44636. */
  44637. _this._renderTargets = new BABYLON.SmartArray(16);
  44638. /**
  44639. * Sets the global ambient color for the material used in lighting calculations.
  44640. */
  44641. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44642. /**
  44643. * If set to true, no lighting calculations will be applied.
  44644. */
  44645. _this._unlit = false;
  44646. // Setup the default processing configuration to the scene.
  44647. _this._attachImageProcessingConfiguration(null);
  44648. _this.getRenderTargetTextures = function () {
  44649. _this._renderTargets.reset();
  44650. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44651. _this._renderTargets.push(_this._reflectionTexture);
  44652. }
  44653. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44654. _this._renderTargets.push(_this._refractionTexture);
  44655. }
  44656. return _this._renderTargets;
  44657. };
  44658. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44659. return _this;
  44660. }
  44661. /**
  44662. * Attaches a new image processing configuration to the PBR Material.
  44663. * @param configuration
  44664. */
  44665. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44666. var _this = this;
  44667. if (configuration === this._imageProcessingConfiguration) {
  44668. return;
  44669. }
  44670. // Detaches observer.
  44671. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44672. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44673. }
  44674. // Pick the scene configuration if needed.
  44675. if (!configuration) {
  44676. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44677. }
  44678. else {
  44679. this._imageProcessingConfiguration = configuration;
  44680. }
  44681. // Attaches observer.
  44682. if (this._imageProcessingConfiguration) {
  44683. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44684. _this._markAllSubMeshesAsImageProcessingDirty();
  44685. });
  44686. }
  44687. };
  44688. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44689. /**
  44690. * Gets a boolean indicating that current material needs to register RTT
  44691. */
  44692. get: function () {
  44693. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44694. return true;
  44695. }
  44696. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44697. return true;
  44698. }
  44699. return false;
  44700. },
  44701. enumerable: true,
  44702. configurable: true
  44703. });
  44704. /**
  44705. * Gets the name of the material class.
  44706. */
  44707. PBRBaseMaterial.prototype.getClassName = function () {
  44708. return "PBRBaseMaterial";
  44709. };
  44710. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44711. /**
  44712. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44713. */
  44714. get: function () {
  44715. return this._useLogarithmicDepth;
  44716. },
  44717. /**
  44718. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44719. */
  44720. set: function (value) {
  44721. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44722. },
  44723. enumerable: true,
  44724. configurable: true
  44725. });
  44726. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44727. /**
  44728. * Gets the current transparency mode.
  44729. */
  44730. get: function () {
  44731. return this._transparencyMode;
  44732. },
  44733. /**
  44734. * Sets the transparency mode of the material.
  44735. *
  44736. * | Value | Type | Description |
  44737. * | ----- | ----------------------------------- | ----------- |
  44738. * | 0 | OPAQUE | |
  44739. * | 1 | ALPHATEST | |
  44740. * | 2 | ALPHABLEND | |
  44741. * | 3 | ALPHATESTANDBLEND | |
  44742. *
  44743. */
  44744. set: function (value) {
  44745. if (this._transparencyMode === value) {
  44746. return;
  44747. }
  44748. this._transparencyMode = value;
  44749. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44750. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44751. },
  44752. enumerable: true,
  44753. configurable: true
  44754. });
  44755. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44756. /**
  44757. * Returns true if alpha blending should be disabled.
  44758. */
  44759. get: function () {
  44760. return (this._linkRefractionWithTransparency ||
  44761. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44762. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44763. },
  44764. enumerable: true,
  44765. configurable: true
  44766. });
  44767. /**
  44768. * Specifies whether or not this material should be rendered in alpha blend mode.
  44769. */
  44770. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44771. if (this._disableAlphaBlending) {
  44772. return false;
  44773. }
  44774. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44775. };
  44776. /**
  44777. * Specifies if the mesh will require alpha blending.
  44778. * @param mesh - BJS mesh.
  44779. */
  44780. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44781. if (this._disableAlphaBlending) {
  44782. return false;
  44783. }
  44784. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44785. };
  44786. /**
  44787. * Specifies whether or not this material should be rendered in alpha test mode.
  44788. */
  44789. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44790. if (this._forceAlphaTest) {
  44791. return true;
  44792. }
  44793. if (this._linkRefractionWithTransparency) {
  44794. return false;
  44795. }
  44796. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44797. };
  44798. /**
  44799. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44800. */
  44801. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44802. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44803. };
  44804. /**
  44805. * Gets the texture used for the alpha test.
  44806. */
  44807. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44808. return this._albedoTexture;
  44809. };
  44810. /**
  44811. * Specifies that the submesh is ready to be used.
  44812. * @param mesh - BJS mesh.
  44813. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44814. * @param useInstances - Specifies that instances should be used.
  44815. * @returns - boolean indicating that the submesh is ready or not.
  44816. */
  44817. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44818. if (subMesh.effect && this.isFrozen) {
  44819. if (this._wasPreviouslyReady) {
  44820. return true;
  44821. }
  44822. }
  44823. if (!subMesh._materialDefines) {
  44824. subMesh._materialDefines = new PBRMaterialDefines();
  44825. }
  44826. var defines = subMesh._materialDefines;
  44827. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44828. if (defines._renderId === this.getScene().getRenderId()) {
  44829. return true;
  44830. }
  44831. }
  44832. var scene = this.getScene();
  44833. var engine = scene.getEngine();
  44834. if (defines._areTexturesDirty) {
  44835. if (scene.texturesEnabled) {
  44836. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44837. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44838. return false;
  44839. }
  44840. }
  44841. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44842. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44843. return false;
  44844. }
  44845. }
  44846. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44847. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44848. return false;
  44849. }
  44850. }
  44851. var reflectionTexture = this._getReflectionTexture();
  44852. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44853. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44854. return false;
  44855. }
  44856. }
  44857. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44858. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44859. return false;
  44860. }
  44861. }
  44862. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44863. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44864. return false;
  44865. }
  44866. }
  44867. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44868. if (this._metallicTexture) {
  44869. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44870. return false;
  44871. }
  44872. }
  44873. else if (this._reflectivityTexture) {
  44874. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44875. return false;
  44876. }
  44877. }
  44878. if (this._microSurfaceTexture) {
  44879. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44880. return false;
  44881. }
  44882. }
  44883. }
  44884. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44885. // Bump texture cannot be not blocking.
  44886. if (!this._bumpTexture.isReady()) {
  44887. return false;
  44888. }
  44889. }
  44890. var refractionTexture = this._getRefractionTexture();
  44891. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44892. if (!refractionTexture.isReadyOrNotBlocking()) {
  44893. return false;
  44894. }
  44895. }
  44896. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44897. // This is blocking.
  44898. if (!this._environmentBRDFTexture.isReady()) {
  44899. return false;
  44900. }
  44901. }
  44902. }
  44903. }
  44904. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44905. if (!this._imageProcessingConfiguration.isReady()) {
  44906. return false;
  44907. }
  44908. }
  44909. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44910. mesh.createNormals(true);
  44911. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44912. }
  44913. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44914. if (effect) {
  44915. scene.resetCachedMaterial();
  44916. subMesh.setEffect(effect, defines);
  44917. this.buildUniformLayout();
  44918. }
  44919. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44920. return false;
  44921. }
  44922. defines._renderId = scene.getRenderId();
  44923. this._wasPreviouslyReady = true;
  44924. return true;
  44925. };
  44926. /**
  44927. * Specifies if the material uses metallic roughness workflow.
  44928. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44929. */
  44930. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44931. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44932. return true;
  44933. }
  44934. return false;
  44935. };
  44936. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44937. if (onCompiled === void 0) { onCompiled = null; }
  44938. if (onError === void 0) { onError = null; }
  44939. if (useInstances === void 0) { useInstances = null; }
  44940. if (useClipPlane === void 0) { useClipPlane = null; }
  44941. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44942. if (!defines.isDirty) {
  44943. return null;
  44944. }
  44945. defines.markAsProcessed();
  44946. var scene = this.getScene();
  44947. var engine = scene.getEngine();
  44948. // Fallbacks
  44949. var fallbacks = new BABYLON.EffectFallbacks();
  44950. var fallbackRank = 0;
  44951. if (defines.USESPHERICALINVERTEX) {
  44952. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44953. }
  44954. if (defines.FOG) {
  44955. fallbacks.addFallback(fallbackRank, "FOG");
  44956. }
  44957. if (defines.SPECULARAA) {
  44958. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44959. }
  44960. if (defines.POINTSIZE) {
  44961. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44962. }
  44963. if (defines.LOGARITHMICDEPTH) {
  44964. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44965. }
  44966. if (defines.PARALLAX) {
  44967. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44968. }
  44969. if (defines.PARALLAXOCCLUSION) {
  44970. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44971. }
  44972. if (defines.ENVIRONMENTBRDF) {
  44973. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44974. }
  44975. if (defines.TANGENT) {
  44976. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44977. }
  44978. if (defines.BUMP) {
  44979. fallbacks.addFallback(fallbackRank++, "BUMP");
  44980. }
  44981. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44982. if (defines.SPECULARTERM) {
  44983. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44984. }
  44985. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44986. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44987. }
  44988. if (defines.LIGHTMAP) {
  44989. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44990. }
  44991. if (defines.NORMAL) {
  44992. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44993. }
  44994. if (defines.AMBIENT) {
  44995. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44996. }
  44997. if (defines.EMISSIVE) {
  44998. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44999. }
  45000. if (defines.VERTEXCOLOR) {
  45001. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45002. }
  45003. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45004. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45005. }
  45006. if (defines.MORPHTARGETS) {
  45007. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45008. }
  45009. //Attributes
  45010. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45011. if (defines.NORMAL) {
  45012. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45013. }
  45014. if (defines.TANGENT) {
  45015. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45016. }
  45017. if (defines.UV1) {
  45018. attribs.push(BABYLON.VertexBuffer.UVKind);
  45019. }
  45020. if (defines.UV2) {
  45021. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45022. }
  45023. if (defines.VERTEXCOLOR) {
  45024. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45025. }
  45026. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45027. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45028. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45029. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45030. "vFogInfos", "vFogColor", "pointSize",
  45031. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45032. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45033. "mBones",
  45034. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45035. "vLightingIntensity",
  45036. "logarithmicDepthConstant",
  45037. "vSphericalX", "vSphericalY", "vSphericalZ",
  45038. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45039. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45040. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45041. "vTangentSpaceParams"
  45042. ];
  45043. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45044. "bumpSampler", "lightmapSampler", "opacitySampler",
  45045. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45046. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45047. "microSurfaceSampler", "environmentBrdfSampler"];
  45048. var uniformBuffers = ["Material", "Scene"];
  45049. if (BABYLON.ImageProcessingConfiguration) {
  45050. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45051. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45052. }
  45053. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45054. uniformsNames: uniforms,
  45055. uniformBuffersNames: uniformBuffers,
  45056. samplers: samplers,
  45057. defines: defines,
  45058. maxSimultaneousLights: this._maxSimultaneousLights
  45059. });
  45060. var join = defines.toString();
  45061. return engine.createEffect("pbr", {
  45062. attributes: attribs,
  45063. uniformsNames: uniforms,
  45064. uniformBuffersNames: uniformBuffers,
  45065. samplers: samplers,
  45066. defines: join,
  45067. fallbacks: fallbacks,
  45068. onCompiled: onCompiled,
  45069. onError: onError,
  45070. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45071. }, engine);
  45072. };
  45073. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45074. if (useInstances === void 0) { useInstances = null; }
  45075. if (useClipPlane === void 0) { useClipPlane = null; }
  45076. var scene = this.getScene();
  45077. var engine = scene.getEngine();
  45078. // Lights
  45079. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45080. defines._needNormals = true;
  45081. // Textures
  45082. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45083. if (defines._areTexturesDirty) {
  45084. defines._needUVs = false;
  45085. if (scene.texturesEnabled) {
  45086. if (scene.getEngine().getCaps().textureLOD) {
  45087. defines.LODBASEDMICROSFURACE = true;
  45088. }
  45089. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45090. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45091. }
  45092. else {
  45093. defines.ALBEDO = false;
  45094. }
  45095. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45096. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45097. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45098. }
  45099. else {
  45100. defines.AMBIENT = false;
  45101. }
  45102. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45103. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45104. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45105. }
  45106. else {
  45107. defines.OPACITY = false;
  45108. }
  45109. var reflectionTexture = this._getReflectionTexture();
  45110. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45111. defines.REFLECTION = true;
  45112. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45113. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45114. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45115. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45116. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45117. defines.INVERTCUBICMAP = true;
  45118. }
  45119. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45120. switch (reflectionTexture.coordinatesMode) {
  45121. case BABYLON.Texture.EXPLICIT_MODE:
  45122. defines.REFLECTIONMAP_EXPLICIT = true;
  45123. break;
  45124. case BABYLON.Texture.PLANAR_MODE:
  45125. defines.REFLECTIONMAP_PLANAR = true;
  45126. break;
  45127. case BABYLON.Texture.PROJECTION_MODE:
  45128. defines.REFLECTIONMAP_PROJECTION = true;
  45129. break;
  45130. case BABYLON.Texture.SKYBOX_MODE:
  45131. defines.REFLECTIONMAP_SKYBOX = true;
  45132. break;
  45133. case BABYLON.Texture.SPHERICAL_MODE:
  45134. defines.REFLECTIONMAP_SPHERICAL = true;
  45135. break;
  45136. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45137. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45138. break;
  45139. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45140. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45141. break;
  45142. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45143. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45144. break;
  45145. case BABYLON.Texture.CUBIC_MODE:
  45146. case BABYLON.Texture.INVCUBIC_MODE:
  45147. default:
  45148. defines.REFLECTIONMAP_CUBIC = true;
  45149. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45150. break;
  45151. }
  45152. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45153. if (reflectionTexture.sphericalPolynomial) {
  45154. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45155. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45156. defines.USESPHERICALINVERTEX = false;
  45157. }
  45158. else {
  45159. defines.USESPHERICALINVERTEX = true;
  45160. }
  45161. }
  45162. }
  45163. else {
  45164. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45165. }
  45166. }
  45167. else {
  45168. defines.REFLECTION = false;
  45169. defines.REFLECTIONMAP_3D = false;
  45170. defines.REFLECTIONMAP_SPHERICAL = false;
  45171. defines.REFLECTIONMAP_PLANAR = false;
  45172. defines.REFLECTIONMAP_CUBIC = false;
  45173. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45174. defines.REFLECTIONMAP_PROJECTION = false;
  45175. defines.REFLECTIONMAP_SKYBOX = false;
  45176. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45177. defines.REFLECTIONMAP_EXPLICIT = false;
  45178. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45179. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45180. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45181. defines.INVERTCUBICMAP = false;
  45182. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45183. defines.USESPHERICALINVERTEX = false;
  45184. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45185. defines.LODINREFLECTIONALPHA = false;
  45186. defines.GAMMAREFLECTION = false;
  45187. defines.RGBDREFLECTION = false;
  45188. }
  45189. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45190. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45191. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45192. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45193. }
  45194. else {
  45195. defines.LIGHTMAP = false;
  45196. }
  45197. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45198. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45199. }
  45200. else {
  45201. defines.EMISSIVE = false;
  45202. }
  45203. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45204. if (this._metallicTexture) {
  45205. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45206. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45207. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45208. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45209. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45210. }
  45211. else if (this._reflectivityTexture) {
  45212. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45213. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45214. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45215. }
  45216. else {
  45217. defines.REFLECTIVITY = false;
  45218. }
  45219. if (this._microSurfaceTexture) {
  45220. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45221. }
  45222. else {
  45223. defines.MICROSURFACEMAP = false;
  45224. }
  45225. }
  45226. else {
  45227. defines.REFLECTIVITY = false;
  45228. defines.MICROSURFACEMAP = false;
  45229. }
  45230. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45231. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45232. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45233. defines.PARALLAX = true;
  45234. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45235. }
  45236. else {
  45237. defines.PARALLAX = false;
  45238. }
  45239. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45240. }
  45241. else {
  45242. defines.BUMP = false;
  45243. }
  45244. var refractionTexture = this._getRefractionTexture();
  45245. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45246. defines.REFRACTION = true;
  45247. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45248. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45249. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45250. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45251. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45252. if (this._linkRefractionWithTransparency) {
  45253. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45254. }
  45255. }
  45256. else {
  45257. defines.REFRACTION = false;
  45258. }
  45259. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45260. defines.ENVIRONMENTBRDF = true;
  45261. }
  45262. else {
  45263. defines.ENVIRONMENTBRDF = false;
  45264. }
  45265. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45266. defines.ALPHAFROMALBEDO = true;
  45267. }
  45268. else {
  45269. defines.ALPHAFROMALBEDO = false;
  45270. }
  45271. }
  45272. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45273. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45274. defines.USEPHYSICALLIGHTFALLOFF = false;
  45275. defines.USEGLTFLIGHTFALLOFF = false;
  45276. }
  45277. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45278. defines.USEPHYSICALLIGHTFALLOFF = false;
  45279. defines.USEGLTFLIGHTFALLOFF = true;
  45280. }
  45281. else {
  45282. defines.USEPHYSICALLIGHTFALLOFF = true;
  45283. defines.USEGLTFLIGHTFALLOFF = false;
  45284. }
  45285. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45286. if (!this.backFaceCulling && this._twoSidedLighting) {
  45287. defines.TWOSIDEDLIGHTING = true;
  45288. }
  45289. else {
  45290. defines.TWOSIDEDLIGHTING = false;
  45291. }
  45292. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45293. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45294. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45295. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45296. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45297. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45298. }
  45299. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45300. this._imageProcessingConfiguration.prepareDefines(defines);
  45301. }
  45302. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45303. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45304. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45305. // Misc.
  45306. if (defines._areMiscDirty) {
  45307. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45308. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45309. }
  45310. // Values that need to be evaluated on every frame
  45311. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45312. // Attribs
  45313. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45314. };
  45315. /**
  45316. * Force shader compilation
  45317. */
  45318. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45319. var _this = this;
  45320. var localOptions = __assign({ clipPlane: false }, options);
  45321. var defines = new PBRMaterialDefines();
  45322. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45323. if (effect.isReady()) {
  45324. if (onCompiled) {
  45325. onCompiled(this);
  45326. }
  45327. }
  45328. else {
  45329. effect.onCompileObservable.add(function () {
  45330. if (onCompiled) {
  45331. onCompiled(_this);
  45332. }
  45333. });
  45334. }
  45335. };
  45336. /**
  45337. * Initializes the uniform buffer layout for the shader.
  45338. */
  45339. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45340. // Order is important !
  45341. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45342. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  45343. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45344. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45345. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45346. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45347. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45348. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45349. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45350. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45351. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45352. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45353. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45354. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45355. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45356. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45357. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45358. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45359. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45360. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45361. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45362. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45363. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45364. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45365. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45366. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45367. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45368. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45369. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45370. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45371. this._uniformBuffer.addUniform("pointSize", 1);
  45372. this._uniformBuffer.create();
  45373. };
  45374. /**
  45375. * Unbinds the textures.
  45376. */
  45377. PBRBaseMaterial.prototype.unbind = function () {
  45378. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45379. this._uniformBuffer.setTexture("reflectionSampler", null);
  45380. }
  45381. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45382. this._uniformBuffer.setTexture("refractionSampler", null);
  45383. }
  45384. _super.prototype.unbind.call(this);
  45385. };
  45386. /**
  45387. * Binds the submesh data.
  45388. * @param world - The world matrix.
  45389. * @param mesh - The BJS mesh.
  45390. * @param subMesh - A submesh of the BJS mesh.
  45391. */
  45392. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45393. var scene = this.getScene();
  45394. var defines = subMesh._materialDefines;
  45395. if (!defines) {
  45396. return;
  45397. }
  45398. var effect = subMesh.effect;
  45399. if (!effect) {
  45400. return;
  45401. }
  45402. this._activeEffect = effect;
  45403. // Matrices
  45404. this.bindOnlyWorldMatrix(world);
  45405. // Normal Matrix
  45406. if (defines.OBJECTSPACE_NORMALMAP) {
  45407. world.toNormalMatrix(this._normalMatrix);
  45408. this.bindOnlyNormalMatrix(this._normalMatrix);
  45409. }
  45410. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45411. // Bones
  45412. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45413. var reflectionTexture = null;
  45414. if (mustRebind) {
  45415. this._uniformBuffer.bindToEffect(effect, "Material");
  45416. this.bindViewProjection(effect);
  45417. reflectionTexture = this._getReflectionTexture();
  45418. var refractionTexture = this._getRefractionTexture();
  45419. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45420. // Texture uniforms
  45421. if (scene.texturesEnabled) {
  45422. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45423. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45424. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45425. }
  45426. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45427. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  45428. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45429. }
  45430. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45431. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45432. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45433. }
  45434. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45435. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45436. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45437. if (reflectionTexture.boundingBoxSize) {
  45438. var cubeTexture = reflectionTexture;
  45439. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45440. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45441. }
  45442. var polynomials = reflectionTexture.sphericalPolynomial;
  45443. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45444. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45445. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45446. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45447. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45448. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45449. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45450. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45451. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45452. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45453. }
  45454. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45455. }
  45456. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45457. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45458. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45459. }
  45460. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45461. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45462. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45463. }
  45464. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45465. if (this._metallicTexture) {
  45466. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45467. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45468. }
  45469. else if (this._reflectivityTexture) {
  45470. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45471. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45472. }
  45473. if (this._microSurfaceTexture) {
  45474. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45475. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45476. }
  45477. }
  45478. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45479. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45480. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45481. if (scene._mirroredCameraPosition) {
  45482. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45483. }
  45484. else {
  45485. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45486. }
  45487. }
  45488. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45489. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45490. var depth = 1.0;
  45491. if (!refractionTexture.isCube) {
  45492. if (refractionTexture.depth) {
  45493. depth = refractionTexture.depth;
  45494. }
  45495. }
  45496. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45497. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45498. }
  45499. }
  45500. // Point size
  45501. if (this.pointsCloud) {
  45502. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45503. }
  45504. // Colors
  45505. if (defines.METALLICWORKFLOW) {
  45506. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45507. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45508. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45509. }
  45510. else {
  45511. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45512. }
  45513. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45514. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45515. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45516. // Misc
  45517. this._lightingInfos.x = this._directIntensity;
  45518. this._lightingInfos.y = this._emissiveIntensity;
  45519. this._lightingInfos.z = this._environmentIntensity;
  45520. this._lightingInfos.w = this._specularIntensity;
  45521. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45522. }
  45523. // Textures
  45524. if (scene.texturesEnabled) {
  45525. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45526. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45527. }
  45528. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45529. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45530. }
  45531. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45532. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45533. }
  45534. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45535. if (defines.LODBASEDMICROSFURACE) {
  45536. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45537. }
  45538. else {
  45539. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45540. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45541. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45542. }
  45543. }
  45544. if (defines.ENVIRONMENTBRDF) {
  45545. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45546. }
  45547. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45548. if (defines.LODBASEDMICROSFURACE) {
  45549. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45550. }
  45551. else {
  45552. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45553. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45554. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45555. }
  45556. }
  45557. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45558. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45559. }
  45560. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45561. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45562. }
  45563. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45564. if (this._metallicTexture) {
  45565. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45566. }
  45567. else if (this._reflectivityTexture) {
  45568. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45569. }
  45570. if (this._microSurfaceTexture) {
  45571. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45572. }
  45573. }
  45574. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45575. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45576. }
  45577. }
  45578. // Clip plane
  45579. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45580. // Colors
  45581. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45582. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45583. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45584. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45585. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45586. }
  45587. if (mustRebind || !this.isFrozen) {
  45588. // Lights
  45589. if (scene.lightsEnabled && !this._disableLighting) {
  45590. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45591. }
  45592. // View
  45593. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45594. this.bindView(effect);
  45595. }
  45596. // Fog
  45597. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45598. // Morph targets
  45599. if (defines.NUM_MORPH_INFLUENCERS) {
  45600. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45601. }
  45602. // image processing
  45603. this._imageProcessingConfiguration.bind(this._activeEffect);
  45604. // Log. depth
  45605. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45606. }
  45607. this._uniformBuffer.update();
  45608. this._afterBind(mesh, this._activeEffect);
  45609. };
  45610. /**
  45611. * Returns the animatable textures.
  45612. * @returns - Array of animatable textures.
  45613. */
  45614. PBRBaseMaterial.prototype.getAnimatables = function () {
  45615. var results = [];
  45616. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45617. results.push(this._albedoTexture);
  45618. }
  45619. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45620. results.push(this._ambientTexture);
  45621. }
  45622. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45623. results.push(this._opacityTexture);
  45624. }
  45625. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45626. results.push(this._reflectionTexture);
  45627. }
  45628. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45629. results.push(this._emissiveTexture);
  45630. }
  45631. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45632. results.push(this._metallicTexture);
  45633. }
  45634. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45635. results.push(this._reflectivityTexture);
  45636. }
  45637. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45638. results.push(this._bumpTexture);
  45639. }
  45640. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45641. results.push(this._lightmapTexture);
  45642. }
  45643. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45644. results.push(this._refractionTexture);
  45645. }
  45646. return results;
  45647. };
  45648. /**
  45649. * Returns the texture used for reflections.
  45650. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45651. */
  45652. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45653. if (this._reflectionTexture) {
  45654. return this._reflectionTexture;
  45655. }
  45656. return this.getScene().environmentTexture;
  45657. };
  45658. /**
  45659. * Returns the texture used for refraction or null if none is used.
  45660. * @returns - Refection texture if present. If no refraction texture and refraction
  45661. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45662. */
  45663. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45664. if (this._refractionTexture) {
  45665. return this._refractionTexture;
  45666. }
  45667. if (this._linkRefractionWithTransparency) {
  45668. return this.getScene().environmentTexture;
  45669. }
  45670. return null;
  45671. };
  45672. /**
  45673. * Disposes the resources of the material.
  45674. * @param forceDisposeEffect - Forces the disposal of effects.
  45675. * @param forceDisposeTextures - Forces the disposal of all textures.
  45676. */
  45677. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45678. if (forceDisposeTextures) {
  45679. if (this._albedoTexture) {
  45680. this._albedoTexture.dispose();
  45681. }
  45682. if (this._ambientTexture) {
  45683. this._ambientTexture.dispose();
  45684. }
  45685. if (this._opacityTexture) {
  45686. this._opacityTexture.dispose();
  45687. }
  45688. if (this._reflectionTexture) {
  45689. this._reflectionTexture.dispose();
  45690. }
  45691. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45692. this._environmentBRDFTexture.dispose();
  45693. }
  45694. if (this._emissiveTexture) {
  45695. this._emissiveTexture.dispose();
  45696. }
  45697. if (this._metallicTexture) {
  45698. this._metallicTexture.dispose();
  45699. }
  45700. if (this._reflectivityTexture) {
  45701. this._reflectivityTexture.dispose();
  45702. }
  45703. if (this._bumpTexture) {
  45704. this._bumpTexture.dispose();
  45705. }
  45706. if (this._lightmapTexture) {
  45707. this._lightmapTexture.dispose();
  45708. }
  45709. if (this._refractionTexture) {
  45710. this._refractionTexture.dispose();
  45711. }
  45712. }
  45713. this._renderTargets.dispose();
  45714. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45715. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45716. }
  45717. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45718. };
  45719. /**
  45720. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45721. */
  45722. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45723. /**
  45724. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45725. * to enhance interoperability with other engines.
  45726. */
  45727. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45728. /**
  45729. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45730. * to enhance interoperability with other materials.
  45731. */
  45732. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45733. /**
  45734. * Stores the reflectivity values based on metallic roughness workflow.
  45735. */
  45736. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45737. __decorate([
  45738. BABYLON.serializeAsImageProcessingConfiguration()
  45739. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45740. __decorate([
  45741. BABYLON.serialize()
  45742. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45743. __decorate([
  45744. BABYLON.serialize()
  45745. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45746. return PBRBaseMaterial;
  45747. }(BABYLON.PushMaterial));
  45748. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45749. })(BABYLON || (BABYLON = {}));
  45750. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45751. var BABYLON;
  45752. (function (BABYLON) {
  45753. /**
  45754. * The Physically based simple base material of BJS.
  45755. *
  45756. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45757. * It is used as the base class for both the specGloss and metalRough conventions.
  45758. */
  45759. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45760. __extends(PBRBaseSimpleMaterial, _super);
  45761. /**
  45762. * Instantiates a new PBRMaterial instance.
  45763. *
  45764. * @param name The material name
  45765. * @param scene The scene the material will be use in.
  45766. */
  45767. function PBRBaseSimpleMaterial(name, scene) {
  45768. var _this = _super.call(this, name, scene) || this;
  45769. /**
  45770. * Number of Simultaneous lights allowed on the material.
  45771. */
  45772. _this.maxSimultaneousLights = 4;
  45773. /**
  45774. * If sets to true, disables all the lights affecting the material.
  45775. */
  45776. _this.disableLighting = false;
  45777. /**
  45778. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45779. */
  45780. _this.invertNormalMapX = false;
  45781. /**
  45782. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45783. */
  45784. _this.invertNormalMapY = false;
  45785. /**
  45786. * Emissivie color used to self-illuminate the model.
  45787. */
  45788. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45789. /**
  45790. * Occlusion Channel Strenght.
  45791. */
  45792. _this.occlusionStrength = 1.0;
  45793. /**
  45794. * If true, the light map contains occlusion information instead of lighting info.
  45795. */
  45796. _this.useLightmapAsShadowmap = false;
  45797. _this._useAlphaFromAlbedoTexture = true;
  45798. _this._useAmbientInGrayScale = true;
  45799. return _this;
  45800. }
  45801. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45802. /**
  45803. * Gets the current double sided mode.
  45804. */
  45805. get: function () {
  45806. return this._twoSidedLighting;
  45807. },
  45808. /**
  45809. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45810. */
  45811. set: function (value) {
  45812. if (this._twoSidedLighting === value) {
  45813. return;
  45814. }
  45815. this._twoSidedLighting = value;
  45816. this.backFaceCulling = !value;
  45817. this._markAllSubMeshesAsTexturesDirty();
  45818. },
  45819. enumerable: true,
  45820. configurable: true
  45821. });
  45822. /**
  45823. * Return the active textures of the material.
  45824. */
  45825. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45826. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45827. if (this.environmentTexture) {
  45828. activeTextures.push(this.environmentTexture);
  45829. }
  45830. if (this.normalTexture) {
  45831. activeTextures.push(this.normalTexture);
  45832. }
  45833. if (this.emissiveTexture) {
  45834. activeTextures.push(this.emissiveTexture);
  45835. }
  45836. if (this.occlusionTexture) {
  45837. activeTextures.push(this.occlusionTexture);
  45838. }
  45839. if (this.lightmapTexture) {
  45840. activeTextures.push(this.lightmapTexture);
  45841. }
  45842. return activeTextures;
  45843. };
  45844. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45845. if (_super.prototype.hasTexture.call(this, texture)) {
  45846. return true;
  45847. }
  45848. if (this.lightmapTexture === texture) {
  45849. return true;
  45850. }
  45851. return false;
  45852. };
  45853. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45854. return "PBRBaseSimpleMaterial";
  45855. };
  45856. __decorate([
  45857. BABYLON.serialize(),
  45858. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45859. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45860. __decorate([
  45861. BABYLON.serialize(),
  45862. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45863. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45864. __decorate([
  45865. BABYLON.serializeAsTexture(),
  45866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45867. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45868. __decorate([
  45869. BABYLON.serialize(),
  45870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45871. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45872. __decorate([
  45873. BABYLON.serialize(),
  45874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45875. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45876. __decorate([
  45877. BABYLON.serializeAsTexture(),
  45878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45879. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45880. __decorate([
  45881. BABYLON.serializeAsColor3("emissive"),
  45882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45883. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45884. __decorate([
  45885. BABYLON.serializeAsTexture(),
  45886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45887. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45888. __decorate([
  45889. BABYLON.serialize(),
  45890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45891. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45892. __decorate([
  45893. BABYLON.serializeAsTexture(),
  45894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45895. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45896. __decorate([
  45897. BABYLON.serialize(),
  45898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45899. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45900. __decorate([
  45901. BABYLON.serialize()
  45902. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45903. __decorate([
  45904. BABYLON.serializeAsTexture(),
  45905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45906. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45907. __decorate([
  45908. BABYLON.serialize(),
  45909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45910. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45911. return PBRBaseSimpleMaterial;
  45912. }(BABYLON.PBRBaseMaterial));
  45913. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45914. })(BABYLON || (BABYLON = {}));
  45915. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45916. var BABYLON;
  45917. (function (BABYLON) {
  45918. /**
  45919. * The Physically based material of BJS.
  45920. *
  45921. * This offers the main features of a standard PBR material.
  45922. * For more information, please refer to the documentation :
  45923. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45924. */
  45925. var PBRMaterial = /** @class */ (function (_super) {
  45926. __extends(PBRMaterial, _super);
  45927. /**
  45928. * Instantiates a new PBRMaterial instance.
  45929. *
  45930. * @param name The material name
  45931. * @param scene The scene the material will be use in.
  45932. */
  45933. function PBRMaterial(name, scene) {
  45934. var _this = _super.call(this, name, scene) || this;
  45935. /**
  45936. * Intensity of the direct lights e.g. the four lights available in your scene.
  45937. * This impacts both the direct diffuse and specular highlights.
  45938. */
  45939. _this.directIntensity = 1.0;
  45940. /**
  45941. * Intensity of the emissive part of the material.
  45942. * This helps controlling the emissive effect without modifying the emissive color.
  45943. */
  45944. _this.emissiveIntensity = 1.0;
  45945. /**
  45946. * Intensity of the environment e.g. how much the environment will light the object
  45947. * either through harmonics for rough material or through the refelction for shiny ones.
  45948. */
  45949. _this.environmentIntensity = 1.0;
  45950. /**
  45951. * This is a special control allowing the reduction of the specular highlights coming from the
  45952. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45953. */
  45954. _this.specularIntensity = 1.0;
  45955. /**
  45956. * Debug Control allowing disabling the bump map on this material.
  45957. */
  45958. _this.disableBumpMap = false;
  45959. /**
  45960. * AKA Occlusion Texture Intensity in other nomenclature.
  45961. */
  45962. _this.ambientTextureStrength = 1.0;
  45963. /**
  45964. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45965. * 1 means it completely occludes it
  45966. * 0 mean it has no impact
  45967. */
  45968. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45969. /**
  45970. * The color of a material in ambient lighting.
  45971. */
  45972. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45973. /**
  45974. * AKA Diffuse Color in other nomenclature.
  45975. */
  45976. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45977. /**
  45978. * AKA Specular Color in other nomenclature.
  45979. */
  45980. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45981. /**
  45982. * The color reflected from the material.
  45983. */
  45984. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45985. /**
  45986. * The color emitted from the material.
  45987. */
  45988. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45989. /**
  45990. * AKA Glossiness in other nomenclature.
  45991. */
  45992. _this.microSurface = 1.0;
  45993. /**
  45994. * source material index of refraction (IOR)' / 'destination material IOR.
  45995. */
  45996. _this.indexOfRefraction = 0.66;
  45997. /**
  45998. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45999. */
  46000. _this.invertRefractionY = false;
  46001. /**
  46002. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46003. * Materials half opaque for instance using refraction could benefit from this control.
  46004. */
  46005. _this.linkRefractionWithTransparency = false;
  46006. /**
  46007. * If true, the light map contains occlusion information instead of lighting info.
  46008. */
  46009. _this.useLightmapAsShadowmap = false;
  46010. /**
  46011. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46012. */
  46013. _this.useAlphaFromAlbedoTexture = false;
  46014. /**
  46015. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46016. */
  46017. _this.forceAlphaTest = false;
  46018. /**
  46019. * Defines the alpha limits in alpha test mode.
  46020. */
  46021. _this.alphaCutOff = 0.4;
  46022. /**
  46023. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46024. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46025. */
  46026. _this.useSpecularOverAlpha = true;
  46027. /**
  46028. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46029. */
  46030. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46031. /**
  46032. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46033. */
  46034. _this.useRoughnessFromMetallicTextureAlpha = true;
  46035. /**
  46036. * Specifies if the metallic texture contains the roughness information in its green channel.
  46037. */
  46038. _this.useRoughnessFromMetallicTextureGreen = false;
  46039. /**
  46040. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46041. */
  46042. _this.useMetallnessFromMetallicTextureBlue = false;
  46043. /**
  46044. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46045. */
  46046. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46047. /**
  46048. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46049. */
  46050. _this.useAmbientInGrayScale = false;
  46051. /**
  46052. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46053. * The material will try to infer what glossiness each pixel should be.
  46054. */
  46055. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46056. /**
  46057. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46058. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46059. */
  46060. _this.useRadianceOverAlpha = true;
  46061. /**
  46062. * Allows using an object space normal map (instead of tangent space).
  46063. */
  46064. _this.useObjectSpaceNormalMap = false;
  46065. /**
  46066. * Allows using the bump map in parallax mode.
  46067. */
  46068. _this.useParallax = false;
  46069. /**
  46070. * Allows using the bump map in parallax occlusion mode.
  46071. */
  46072. _this.useParallaxOcclusion = false;
  46073. /**
  46074. * Controls the scale bias of the parallax mode.
  46075. */
  46076. _this.parallaxScaleBias = 0.05;
  46077. /**
  46078. * If sets to true, disables all the lights affecting the material.
  46079. */
  46080. _this.disableLighting = false;
  46081. /**
  46082. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46083. */
  46084. _this.forceIrradianceInFragment = false;
  46085. /**
  46086. * Number of Simultaneous lights allowed on the material.
  46087. */
  46088. _this.maxSimultaneousLights = 4;
  46089. /**
  46090. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46091. */
  46092. _this.invertNormalMapX = false;
  46093. /**
  46094. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46095. */
  46096. _this.invertNormalMapY = false;
  46097. /**
  46098. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46099. */
  46100. _this.twoSidedLighting = false;
  46101. /**
  46102. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46103. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46104. */
  46105. _this.useAlphaFresnel = false;
  46106. /**
  46107. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46108. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46109. */
  46110. _this.useLinearAlphaFresnel = false;
  46111. /**
  46112. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46113. * And/Or occlude the blended part.
  46114. */
  46115. _this.environmentBRDFTexture = null;
  46116. /**
  46117. * Force normal to face away from face.
  46118. */
  46119. _this.forceNormalForward = false;
  46120. /**
  46121. * Enables specular anti aliasing in the PBR shader.
  46122. * It will both interacts on the Geometry for analytical and IBL lighting.
  46123. * It also prefilter the roughness map based on the bump values.
  46124. */
  46125. _this.enableSpecularAntiAliasing = false;
  46126. /**
  46127. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46128. * makes the reflect vector face the model (under horizon).
  46129. */
  46130. _this.useHorizonOcclusion = true;
  46131. /**
  46132. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46133. * too much the area relying on ambient texture to define their ambient occlusion.
  46134. */
  46135. _this.useRadianceOcclusion = true;
  46136. /**
  46137. * If set to true, no lighting calculations will be applied.
  46138. */
  46139. _this.unlit = false;
  46140. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46141. return _this;
  46142. }
  46143. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46144. /**
  46145. * BJS is using an harcoded light falloff based on a manually sets up range.
  46146. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46147. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46148. */
  46149. get: function () {
  46150. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46151. },
  46152. /**
  46153. * BJS is using an harcoded light falloff based on a manually sets up range.
  46154. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46155. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46156. */
  46157. set: function (value) {
  46158. if (value !== this.usePhysicalLightFalloff) {
  46159. // Ensure the effect will be rebuilt.
  46160. this._markAllSubMeshesAsTexturesDirty();
  46161. if (value) {
  46162. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46163. }
  46164. else {
  46165. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46166. }
  46167. }
  46168. },
  46169. enumerable: true,
  46170. configurable: true
  46171. });
  46172. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46173. /**
  46174. * In order to support the falloff compatibility with gltf, a special mode has been added
  46175. * to reproduce the gltf light falloff.
  46176. */
  46177. get: function () {
  46178. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46179. },
  46180. /**
  46181. * In order to support the falloff compatibility with gltf, a special mode has been added
  46182. * to reproduce the gltf light falloff.
  46183. */
  46184. set: function (value) {
  46185. if (value !== this.useGLTFLightFalloff) {
  46186. // Ensure the effect will be rebuilt.
  46187. this._markAllSubMeshesAsTexturesDirty();
  46188. if (value) {
  46189. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46190. }
  46191. else {
  46192. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46193. }
  46194. }
  46195. },
  46196. enumerable: true,
  46197. configurable: true
  46198. });
  46199. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46200. /**
  46201. * Gets the image processing configuration used either in this material.
  46202. */
  46203. get: function () {
  46204. return this._imageProcessingConfiguration;
  46205. },
  46206. /**
  46207. * Sets the Default image processing configuration used either in the this material.
  46208. *
  46209. * If sets to null, the scene one is in use.
  46210. */
  46211. set: function (value) {
  46212. this._attachImageProcessingConfiguration(value);
  46213. // Ensure the effect will be rebuilt.
  46214. this._markAllSubMeshesAsTexturesDirty();
  46215. },
  46216. enumerable: true,
  46217. configurable: true
  46218. });
  46219. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46220. /**
  46221. * Gets wether the color curves effect is enabled.
  46222. */
  46223. get: function () {
  46224. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46225. },
  46226. /**
  46227. * Sets wether the color curves effect is enabled.
  46228. */
  46229. set: function (value) {
  46230. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46231. },
  46232. enumerable: true,
  46233. configurable: true
  46234. });
  46235. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46236. /**
  46237. * Gets wether the color grading effect is enabled.
  46238. */
  46239. get: function () {
  46240. return this.imageProcessingConfiguration.colorGradingEnabled;
  46241. },
  46242. /**
  46243. * Gets wether the color grading effect is enabled.
  46244. */
  46245. set: function (value) {
  46246. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46247. },
  46248. enumerable: true,
  46249. configurable: true
  46250. });
  46251. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46252. /**
  46253. * Gets wether tonemapping is enabled or not.
  46254. */
  46255. get: function () {
  46256. return this._imageProcessingConfiguration.toneMappingEnabled;
  46257. },
  46258. /**
  46259. * Sets wether tonemapping is enabled or not
  46260. */
  46261. set: function (value) {
  46262. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46263. },
  46264. enumerable: true,
  46265. configurable: true
  46266. });
  46267. ;
  46268. ;
  46269. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46270. /**
  46271. * The camera exposure used on this material.
  46272. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46273. * This corresponds to a photographic exposure.
  46274. */
  46275. get: function () {
  46276. return this._imageProcessingConfiguration.exposure;
  46277. },
  46278. /**
  46279. * The camera exposure used on this material.
  46280. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46281. * This corresponds to a photographic exposure.
  46282. */
  46283. set: function (value) {
  46284. this._imageProcessingConfiguration.exposure = value;
  46285. },
  46286. enumerable: true,
  46287. configurable: true
  46288. });
  46289. ;
  46290. ;
  46291. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46292. /**
  46293. * Gets The camera contrast used on this material.
  46294. */
  46295. get: function () {
  46296. return this._imageProcessingConfiguration.contrast;
  46297. },
  46298. /**
  46299. * Sets The camera contrast used on this material.
  46300. */
  46301. set: function (value) {
  46302. this._imageProcessingConfiguration.contrast = value;
  46303. },
  46304. enumerable: true,
  46305. configurable: true
  46306. });
  46307. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46308. /**
  46309. * Gets the Color Grading 2D Lookup Texture.
  46310. */
  46311. get: function () {
  46312. return this._imageProcessingConfiguration.colorGradingTexture;
  46313. },
  46314. /**
  46315. * Sets the Color Grading 2D Lookup Texture.
  46316. */
  46317. set: function (value) {
  46318. this._imageProcessingConfiguration.colorGradingTexture = value;
  46319. },
  46320. enumerable: true,
  46321. configurable: true
  46322. });
  46323. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46324. /**
  46325. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46326. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46327. * 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;
  46328. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46329. */
  46330. get: function () {
  46331. return this._imageProcessingConfiguration.colorCurves;
  46332. },
  46333. /**
  46334. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46335. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46336. * 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;
  46337. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46338. */
  46339. set: function (value) {
  46340. this._imageProcessingConfiguration.colorCurves = value;
  46341. },
  46342. enumerable: true,
  46343. configurable: true
  46344. });
  46345. /**
  46346. * Returns the name of this material class.
  46347. */
  46348. PBRMaterial.prototype.getClassName = function () {
  46349. return "PBRMaterial";
  46350. };
  46351. /**
  46352. * Returns an array of the actively used textures.
  46353. * @returns - Array of BaseTextures
  46354. */
  46355. PBRMaterial.prototype.getActiveTextures = function () {
  46356. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46357. if (this._albedoTexture) {
  46358. activeTextures.push(this._albedoTexture);
  46359. }
  46360. if (this._ambientTexture) {
  46361. activeTextures.push(this._ambientTexture);
  46362. }
  46363. if (this._opacityTexture) {
  46364. activeTextures.push(this._opacityTexture);
  46365. }
  46366. if (this._reflectionTexture) {
  46367. activeTextures.push(this._reflectionTexture);
  46368. }
  46369. if (this._emissiveTexture) {
  46370. activeTextures.push(this._emissiveTexture);
  46371. }
  46372. if (this._reflectivityTexture) {
  46373. activeTextures.push(this._reflectivityTexture);
  46374. }
  46375. if (this._metallicTexture) {
  46376. activeTextures.push(this._metallicTexture);
  46377. }
  46378. if (this._microSurfaceTexture) {
  46379. activeTextures.push(this._microSurfaceTexture);
  46380. }
  46381. if (this._bumpTexture) {
  46382. activeTextures.push(this._bumpTexture);
  46383. }
  46384. if (this._lightmapTexture) {
  46385. activeTextures.push(this._lightmapTexture);
  46386. }
  46387. if (this._refractionTexture) {
  46388. activeTextures.push(this._refractionTexture);
  46389. }
  46390. return activeTextures;
  46391. };
  46392. /**
  46393. * Checks to see if a texture is used in the material.
  46394. * @param texture - Base texture to use.
  46395. * @returns - Boolean specifying if a texture is used in the material.
  46396. */
  46397. PBRMaterial.prototype.hasTexture = function (texture) {
  46398. if (_super.prototype.hasTexture.call(this, texture)) {
  46399. return true;
  46400. }
  46401. if (this._albedoTexture === texture) {
  46402. return true;
  46403. }
  46404. if (this._ambientTexture === texture) {
  46405. return true;
  46406. }
  46407. if (this._opacityTexture === texture) {
  46408. return true;
  46409. }
  46410. if (this._reflectionTexture === texture) {
  46411. return true;
  46412. }
  46413. if (this._reflectivityTexture === texture) {
  46414. return true;
  46415. }
  46416. if (this._metallicTexture === texture) {
  46417. return true;
  46418. }
  46419. if (this._microSurfaceTexture === texture) {
  46420. return true;
  46421. }
  46422. if (this._bumpTexture === texture) {
  46423. return true;
  46424. }
  46425. if (this._lightmapTexture === texture) {
  46426. return true;
  46427. }
  46428. if (this._refractionTexture === texture) {
  46429. return true;
  46430. }
  46431. return false;
  46432. };
  46433. /**
  46434. * Makes a duplicate of the current material.
  46435. * @param name - name to use for the new material.
  46436. */
  46437. PBRMaterial.prototype.clone = function (name) {
  46438. var _this = this;
  46439. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46440. clone.id = name;
  46441. clone.name = name;
  46442. return clone;
  46443. };
  46444. /**
  46445. * Serializes this PBR Material.
  46446. * @returns - An object with the serialized material.
  46447. */
  46448. PBRMaterial.prototype.serialize = function () {
  46449. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46450. serializationObject.customType = "BABYLON.PBRMaterial";
  46451. return serializationObject;
  46452. };
  46453. // Statics
  46454. /**
  46455. * Parses a PBR Material from a serialized object.
  46456. * @param source - Serialized object.
  46457. * @param scene - BJS scene instance.
  46458. * @param rootUrl - url for the scene object
  46459. * @returns - PBRMaterial
  46460. */
  46461. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46462. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46463. };
  46464. /**
  46465. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46466. */
  46467. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  46468. /**
  46469. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46470. */
  46471. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  46472. /**
  46473. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46474. */
  46475. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  46476. /**
  46477. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46478. * They are also discarded below the alpha cutoff threshold to improve performances.
  46479. */
  46480. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46481. /**
  46482. * Defines the default value of how much AO map is occluding the analytical lights
  46483. * (point spot...).
  46484. */
  46485. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  46486. __decorate([
  46487. BABYLON.serialize(),
  46488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46489. ], PBRMaterial.prototype, "directIntensity", void 0);
  46490. __decorate([
  46491. BABYLON.serialize(),
  46492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46493. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46494. __decorate([
  46495. BABYLON.serialize(),
  46496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46497. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46498. __decorate([
  46499. BABYLON.serialize(),
  46500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46501. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46502. __decorate([
  46503. BABYLON.serialize(),
  46504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46505. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46506. __decorate([
  46507. BABYLON.serializeAsTexture(),
  46508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46509. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46510. __decorate([
  46511. BABYLON.serializeAsTexture(),
  46512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46513. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46514. __decorate([
  46515. BABYLON.serialize(),
  46516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46517. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46518. __decorate([
  46519. BABYLON.serialize(),
  46520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46521. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46522. __decorate([
  46523. BABYLON.serializeAsTexture(),
  46524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46525. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46526. __decorate([
  46527. BABYLON.serializeAsTexture(),
  46528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46529. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46530. __decorate([
  46531. BABYLON.serializeAsTexture(),
  46532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46533. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46534. __decorate([
  46535. BABYLON.serializeAsTexture(),
  46536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46537. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46538. __decorate([
  46539. BABYLON.serializeAsTexture(),
  46540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46541. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46542. __decorate([
  46543. BABYLON.serialize(),
  46544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46545. ], PBRMaterial.prototype, "metallic", void 0);
  46546. __decorate([
  46547. BABYLON.serialize(),
  46548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46549. ], PBRMaterial.prototype, "roughness", void 0);
  46550. __decorate([
  46551. BABYLON.serializeAsTexture(),
  46552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46553. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46554. __decorate([
  46555. BABYLON.serializeAsTexture(),
  46556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46557. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46558. __decorate([
  46559. BABYLON.serializeAsTexture(),
  46560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46561. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46562. __decorate([
  46563. BABYLON.serializeAsTexture(),
  46564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46565. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46566. __decorate([
  46567. BABYLON.serializeAsColor3("ambient"),
  46568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46569. ], PBRMaterial.prototype, "ambientColor", void 0);
  46570. __decorate([
  46571. BABYLON.serializeAsColor3("albedo"),
  46572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46573. ], PBRMaterial.prototype, "albedoColor", void 0);
  46574. __decorate([
  46575. BABYLON.serializeAsColor3("reflectivity"),
  46576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46577. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46578. __decorate([
  46579. BABYLON.serializeAsColor3("reflection"),
  46580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46581. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46582. __decorate([
  46583. BABYLON.serializeAsColor3("emissive"),
  46584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46585. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46586. __decorate([
  46587. BABYLON.serialize(),
  46588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46589. ], PBRMaterial.prototype, "microSurface", void 0);
  46590. __decorate([
  46591. BABYLON.serialize(),
  46592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46593. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46594. __decorate([
  46595. BABYLON.serialize(),
  46596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46597. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46598. __decorate([
  46599. BABYLON.serialize(),
  46600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46601. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46602. __decorate([
  46603. BABYLON.serialize(),
  46604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46605. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46606. __decorate([
  46607. BABYLON.serialize(),
  46608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46609. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46610. __decorate([
  46611. BABYLON.serialize(),
  46612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46613. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46614. __decorate([
  46615. BABYLON.serialize(),
  46616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46617. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46618. __decorate([
  46619. BABYLON.serialize(),
  46620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46621. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46622. __decorate([
  46623. BABYLON.serialize(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46625. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46626. __decorate([
  46627. BABYLON.serialize(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46629. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46630. __decorate([
  46631. BABYLON.serialize(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46633. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46634. __decorate([
  46635. BABYLON.serialize(),
  46636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46637. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46638. __decorate([
  46639. BABYLON.serialize(),
  46640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46641. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46642. __decorate([
  46643. BABYLON.serialize(),
  46644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46645. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46646. __decorate([
  46647. BABYLON.serialize(),
  46648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46649. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46650. __decorate([
  46651. BABYLON.serialize()
  46652. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46653. __decorate([
  46654. BABYLON.serialize()
  46655. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46656. __decorate([
  46657. BABYLON.serialize(),
  46658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46659. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46660. __decorate([
  46661. BABYLON.serialize(),
  46662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46663. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46664. __decorate([
  46665. BABYLON.serialize(),
  46666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46667. ], PBRMaterial.prototype, "useParallax", void 0);
  46668. __decorate([
  46669. BABYLON.serialize(),
  46670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46671. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46672. __decorate([
  46673. BABYLON.serialize(),
  46674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46675. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46676. __decorate([
  46677. BABYLON.serialize(),
  46678. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46679. ], PBRMaterial.prototype, "disableLighting", void 0);
  46680. __decorate([
  46681. BABYLON.serialize(),
  46682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46683. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46684. __decorate([
  46685. BABYLON.serialize(),
  46686. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46687. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46688. __decorate([
  46689. BABYLON.serialize(),
  46690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46691. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46692. __decorate([
  46693. BABYLON.serialize(),
  46694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46695. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46696. __decorate([
  46697. BABYLON.serialize(),
  46698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46699. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46700. __decorate([
  46701. BABYLON.serialize(),
  46702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46703. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46704. __decorate([
  46705. BABYLON.serialize(),
  46706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46707. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46708. __decorate([
  46709. BABYLON.serializeAsTexture(),
  46710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46711. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46712. __decorate([
  46713. BABYLON.serialize(),
  46714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46715. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46716. __decorate([
  46717. BABYLON.serialize(),
  46718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46719. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46720. __decorate([
  46721. BABYLON.serialize(),
  46722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46723. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46724. __decorate([
  46725. BABYLON.serialize(),
  46726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46727. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46728. __decorate([
  46729. BABYLON.serialize(),
  46730. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46731. ], PBRMaterial.prototype, "unlit", void 0);
  46732. return PBRMaterial;
  46733. }(BABYLON.PBRBaseMaterial));
  46734. BABYLON.PBRMaterial = PBRMaterial;
  46735. })(BABYLON || (BABYLON = {}));
  46736. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46737. var BABYLON;
  46738. (function (BABYLON) {
  46739. /**
  46740. * The PBR material of BJS following the metal roughness convention.
  46741. *
  46742. * This fits to the PBR convention in the GLTF definition:
  46743. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46744. */
  46745. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46746. __extends(PBRMetallicRoughnessMaterial, _super);
  46747. /**
  46748. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46749. *
  46750. * @param name The material name
  46751. * @param scene The scene the material will be use in.
  46752. */
  46753. function PBRMetallicRoughnessMaterial(name, scene) {
  46754. var _this = _super.call(this, name, scene) || this;
  46755. _this._useRoughnessFromMetallicTextureAlpha = false;
  46756. _this._useRoughnessFromMetallicTextureGreen = true;
  46757. _this._useMetallnessFromMetallicTextureBlue = true;
  46758. _this.metallic = 1.0;
  46759. _this.roughness = 1.0;
  46760. return _this;
  46761. }
  46762. /**
  46763. * Return the currrent class name of the material.
  46764. */
  46765. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46766. return "PBRMetallicRoughnessMaterial";
  46767. };
  46768. /**
  46769. * Return the active textures of the material.
  46770. */
  46771. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46772. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46773. if (this.baseTexture) {
  46774. activeTextures.push(this.baseTexture);
  46775. }
  46776. if (this.metallicRoughnessTexture) {
  46777. activeTextures.push(this.metallicRoughnessTexture);
  46778. }
  46779. return activeTextures;
  46780. };
  46781. /**
  46782. * Checks to see if a texture is used in the material.
  46783. * @param texture - Base texture to use.
  46784. * @returns - Boolean specifying if a texture is used in the material.
  46785. */
  46786. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46787. if (_super.prototype.hasTexture.call(this, texture)) {
  46788. return true;
  46789. }
  46790. if (this.baseTexture === texture) {
  46791. return true;
  46792. }
  46793. if (this.metallicRoughnessTexture === texture) {
  46794. return true;
  46795. }
  46796. return false;
  46797. };
  46798. /**
  46799. * Makes a duplicate of the current material.
  46800. * @param name - name to use for the new material.
  46801. */
  46802. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46803. var _this = this;
  46804. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46805. clone.id = name;
  46806. clone.name = name;
  46807. return clone;
  46808. };
  46809. /**
  46810. * Serialize the material to a parsable JSON object.
  46811. */
  46812. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46814. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46815. return serializationObject;
  46816. };
  46817. /**
  46818. * Parses a JSON object correponding to the serialize function.
  46819. */
  46820. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46821. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46822. };
  46823. __decorate([
  46824. BABYLON.serializeAsColor3(),
  46825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46826. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46827. __decorate([
  46828. BABYLON.serializeAsTexture(),
  46829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46830. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46831. __decorate([
  46832. BABYLON.serialize(),
  46833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46834. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46835. __decorate([
  46836. BABYLON.serialize(),
  46837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46838. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46839. __decorate([
  46840. BABYLON.serializeAsTexture(),
  46841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46842. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46843. return PBRMetallicRoughnessMaterial;
  46844. }(BABYLON.PBRBaseSimpleMaterial));
  46845. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46846. })(BABYLON || (BABYLON = {}));
  46847. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46848. var BABYLON;
  46849. (function (BABYLON) {
  46850. /**
  46851. * The PBR material of BJS following the specular glossiness convention.
  46852. *
  46853. * This fits to the PBR convention in the GLTF definition:
  46854. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46855. */
  46856. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46857. __extends(PBRSpecularGlossinessMaterial, _super);
  46858. /**
  46859. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46860. *
  46861. * @param name The material name
  46862. * @param scene The scene the material will be use in.
  46863. */
  46864. function PBRSpecularGlossinessMaterial(name, scene) {
  46865. var _this = _super.call(this, name, scene) || this;
  46866. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46867. return _this;
  46868. }
  46869. /**
  46870. * Return the currrent class name of the material.
  46871. */
  46872. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46873. return "PBRSpecularGlossinessMaterial";
  46874. };
  46875. /**
  46876. * Return the active textures of the material.
  46877. */
  46878. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46879. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46880. if (this.diffuseTexture) {
  46881. activeTextures.push(this.diffuseTexture);
  46882. }
  46883. if (this.specularGlossinessTexture) {
  46884. activeTextures.push(this.specularGlossinessTexture);
  46885. }
  46886. return activeTextures;
  46887. };
  46888. /**
  46889. * Checks to see if a texture is used in the material.
  46890. * @param texture - Base texture to use.
  46891. * @returns - Boolean specifying if a texture is used in the material.
  46892. */
  46893. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46894. if (_super.prototype.hasTexture.call(this, texture)) {
  46895. return true;
  46896. }
  46897. if (this.diffuseTexture === texture) {
  46898. return true;
  46899. }
  46900. if (this.specularGlossinessTexture === texture) {
  46901. return true;
  46902. }
  46903. return false;
  46904. };
  46905. /**
  46906. * Makes a duplicate of the current material.
  46907. * @param name - name to use for the new material.
  46908. */
  46909. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46910. var _this = this;
  46911. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46912. clone.id = name;
  46913. clone.name = name;
  46914. return clone;
  46915. };
  46916. /**
  46917. * Serialize the material to a parsable JSON object.
  46918. */
  46919. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46921. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46922. return serializationObject;
  46923. };
  46924. /**
  46925. * Parses a JSON object correponding to the serialize function.
  46926. */
  46927. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46928. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46929. };
  46930. __decorate([
  46931. BABYLON.serializeAsColor3("diffuse"),
  46932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46933. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46934. __decorate([
  46935. BABYLON.serializeAsTexture(),
  46936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46937. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46938. __decorate([
  46939. BABYLON.serializeAsColor3("specular"),
  46940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46941. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46942. __decorate([
  46943. BABYLON.serialize(),
  46944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46945. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46946. __decorate([
  46947. BABYLON.serializeAsTexture(),
  46948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46949. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46950. return PBRSpecularGlossinessMaterial;
  46951. }(BABYLON.PBRBaseSimpleMaterial));
  46952. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46953. })(BABYLON || (BABYLON = {}));
  46954. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46955. var BABYLON;
  46956. (function (BABYLON) {
  46957. /**
  46958. * This is a list of all the different input types that are available in the application.
  46959. * Fo instance: ArcRotateCameraGamepadInput...
  46960. */
  46961. BABYLON.CameraInputTypes = {};
  46962. /**
  46963. * This represents the input manager used within a camera.
  46964. * It helps dealing with all the different kind of input attached to a camera.
  46965. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46966. */
  46967. var CameraInputsManager = /** @class */ (function () {
  46968. /**
  46969. * Instantiate a new Camera Input Manager.
  46970. * @param camera Defines the camera the input manager blongs to
  46971. */
  46972. function CameraInputsManager(camera) {
  46973. this.attached = {};
  46974. this.camera = camera;
  46975. this.checkInputs = function () { };
  46976. }
  46977. /**
  46978. * Add an input method to a camera
  46979. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46980. * @param input camera input method
  46981. */
  46982. CameraInputsManager.prototype.add = function (input) {
  46983. var type = input.getSimpleName();
  46984. if (this.attached[type]) {
  46985. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46986. return;
  46987. }
  46988. this.attached[type] = input;
  46989. input.camera = this.camera;
  46990. //for checkInputs, we are dynamically creating a function
  46991. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46992. if (input.checkInputs) {
  46993. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46994. }
  46995. if (this.attachedElement) {
  46996. input.attachControl(this.attachedElement);
  46997. }
  46998. };
  46999. /**
  47000. * Remove a specific input method from a camera
  47001. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47002. * @param inputToRemove camera input method
  47003. */
  47004. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47005. for (var cam in this.attached) {
  47006. var input = this.attached[cam];
  47007. if (input === inputToRemove) {
  47008. input.detachControl(this.attachedElement);
  47009. input.camera = null;
  47010. delete this.attached[cam];
  47011. this.rebuildInputCheck();
  47012. }
  47013. }
  47014. };
  47015. /**
  47016. * Remove a specific input type from a camera
  47017. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47018. * @param inputType the type of the input to remove
  47019. */
  47020. CameraInputsManager.prototype.removeByType = function (inputType) {
  47021. for (var cam in this.attached) {
  47022. var input = this.attached[cam];
  47023. if (input.getClassName() === inputType) {
  47024. input.detachControl(this.attachedElement);
  47025. input.camera = null;
  47026. delete this.attached[cam];
  47027. this.rebuildInputCheck();
  47028. }
  47029. }
  47030. };
  47031. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47032. var current = this.checkInputs;
  47033. return function () {
  47034. current();
  47035. fn();
  47036. };
  47037. };
  47038. /**
  47039. * Attach the input controls to the currently attached dom element to listen the events from.
  47040. * @param input Defines the input to attach
  47041. */
  47042. CameraInputsManager.prototype.attachInput = function (input) {
  47043. if (this.attachedElement) {
  47044. input.attachControl(this.attachedElement, this.noPreventDefault);
  47045. }
  47046. };
  47047. /**
  47048. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47049. * @param element Defines the dom element to collect the events from
  47050. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47051. */
  47052. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47053. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47054. if (this.attachedElement) {
  47055. return;
  47056. }
  47057. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47058. this.attachedElement = element;
  47059. this.noPreventDefault = noPreventDefault;
  47060. for (var cam in this.attached) {
  47061. this.attached[cam].attachControl(element, noPreventDefault);
  47062. }
  47063. };
  47064. /**
  47065. * Detach the current manager inputs controls from a specific dom element.
  47066. * @param element Defines the dom element to collect the events from
  47067. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47068. */
  47069. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47070. if (disconnect === void 0) { disconnect = false; }
  47071. if (this.attachedElement !== element) {
  47072. return;
  47073. }
  47074. for (var cam in this.attached) {
  47075. this.attached[cam].detachControl(element);
  47076. if (disconnect) {
  47077. this.attached[cam].camera = null;
  47078. }
  47079. }
  47080. this.attachedElement = null;
  47081. };
  47082. /**
  47083. * Rebuild the dynamic inputCheck function from the current list of
  47084. * defined inputs in the manager.
  47085. */
  47086. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47087. this.checkInputs = function () { };
  47088. for (var cam in this.attached) {
  47089. var input = this.attached[cam];
  47090. if (input.checkInputs) {
  47091. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47092. }
  47093. }
  47094. };
  47095. /**
  47096. * Remove all attached input methods from a camera
  47097. */
  47098. CameraInputsManager.prototype.clear = function () {
  47099. if (this.attachedElement) {
  47100. this.detachElement(this.attachedElement, true);
  47101. }
  47102. this.attached = {};
  47103. this.attachedElement = null;
  47104. this.checkInputs = function () { };
  47105. };
  47106. /**
  47107. * Serialize the current input manager attached to a camera.
  47108. * This ensures than once parsed,
  47109. * the input associated to the camera will be identical to the current ones
  47110. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47111. */
  47112. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47113. var inputs = {};
  47114. for (var cam in this.attached) {
  47115. var input = this.attached[cam];
  47116. var res = BABYLON.SerializationHelper.Serialize(input);
  47117. inputs[input.getClassName()] = res;
  47118. }
  47119. serializedCamera.inputsmgr = inputs;
  47120. };
  47121. /**
  47122. * Parses an input manager serialized JSON to restore the previous list of inputs
  47123. * and states associated to a camera.
  47124. * @param parsedCamera Defines the JSON to parse
  47125. */
  47126. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47127. var parsedInputs = parsedCamera.inputsmgr;
  47128. if (parsedInputs) {
  47129. this.clear();
  47130. for (var n in parsedInputs) {
  47131. var construct = BABYLON.CameraInputTypes[n];
  47132. if (construct) {
  47133. var parsedinput = parsedInputs[n];
  47134. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47135. this.add(input);
  47136. }
  47137. }
  47138. }
  47139. else {
  47140. //2016-03-08 this part is for managing backward compatibility
  47141. for (var n in this.attached) {
  47142. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47143. if (construct) {
  47144. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47145. this.remove(this.attached[n]);
  47146. this.add(input);
  47147. }
  47148. }
  47149. }
  47150. };
  47151. return CameraInputsManager;
  47152. }());
  47153. BABYLON.CameraInputsManager = CameraInputsManager;
  47154. })(BABYLON || (BABYLON = {}));
  47155. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47156. var BABYLON;
  47157. (function (BABYLON) {
  47158. /**
  47159. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47160. * This is the base of the follow, arc rotate cameras and Free camera
  47161. * @see http://doc.babylonjs.com/features/cameras
  47162. */
  47163. var TargetCamera = /** @class */ (function (_super) {
  47164. __extends(TargetCamera, _super);
  47165. /**
  47166. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47167. * This is the base of the follow, arc rotate cameras and Free camera
  47168. * @see http://doc.babylonjs.com/features/cameras
  47169. * @param name Defines the name of the camera in the scene
  47170. * @param position Defines the start position of the camera in the scene
  47171. * @param scene Defines the scene the camera belongs to
  47172. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47173. */
  47174. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47175. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47176. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47177. /**
  47178. * Define the current direction the camera is moving to
  47179. */
  47180. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47181. /**
  47182. * Define the current rotation the camera is rotating to
  47183. */
  47184. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47185. /**
  47186. * Define the current rotation of the camera
  47187. */
  47188. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47189. /**
  47190. * Define the current speed of the camera
  47191. */
  47192. _this.speed = 2.0;
  47193. /**
  47194. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47195. * around all axis.
  47196. */
  47197. _this.noRotationConstraint = false;
  47198. /**
  47199. * Define the current target of the camera as an object or a position.
  47200. */
  47201. _this.lockedTarget = null;
  47202. /** @hidden */
  47203. _this._currentTarget = BABYLON.Vector3.Zero();
  47204. /** @hidden */
  47205. _this._viewMatrix = BABYLON.Matrix.Zero();
  47206. /** @hidden */
  47207. _this._camMatrix = BABYLON.Matrix.Zero();
  47208. /** @hidden */
  47209. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47210. /** @hidden */
  47211. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47212. /** @hidden */
  47213. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47214. /** @hidden */
  47215. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47216. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47217. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47218. _this._defaultUp = BABYLON.Vector3.Up();
  47219. _this._cachedRotationZ = 0;
  47220. return _this;
  47221. }
  47222. /**
  47223. * Gets the position in front of the camera at a given distance.
  47224. * @param distance The distance from the camera we want the position to be
  47225. * @returns the position
  47226. */
  47227. TargetCamera.prototype.getFrontPosition = function (distance) {
  47228. this.getWorldMatrix();
  47229. var direction = this.getTarget().subtract(this.position);
  47230. direction.normalize();
  47231. direction.scaleInPlace(distance);
  47232. return this.globalPosition.add(direction);
  47233. };
  47234. /** @hidden */
  47235. TargetCamera.prototype._getLockedTargetPosition = function () {
  47236. if (!this.lockedTarget) {
  47237. return null;
  47238. }
  47239. if (this.lockedTarget.absolutePosition) {
  47240. this.lockedTarget.computeWorldMatrix();
  47241. }
  47242. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47243. };
  47244. /**
  47245. * Store current camera state of the camera (fov, position, rotation, etc..)
  47246. * @returns the camera
  47247. */
  47248. TargetCamera.prototype.storeState = function () {
  47249. this._storedPosition = this.position.clone();
  47250. this._storedRotation = this.rotation.clone();
  47251. if (this.rotationQuaternion) {
  47252. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47253. }
  47254. return _super.prototype.storeState.call(this);
  47255. };
  47256. /**
  47257. * Restored camera state. You must call storeState() first
  47258. * @returns whether it was successful or not
  47259. * @hidden
  47260. */
  47261. TargetCamera.prototype._restoreStateValues = function () {
  47262. if (!_super.prototype._restoreStateValues.call(this)) {
  47263. return false;
  47264. }
  47265. this.position = this._storedPosition.clone();
  47266. this.rotation = this._storedRotation.clone();
  47267. if (this.rotationQuaternion) {
  47268. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47269. }
  47270. this.cameraDirection.copyFromFloats(0, 0, 0);
  47271. this.cameraRotation.copyFromFloats(0, 0);
  47272. return true;
  47273. };
  47274. /** @hidden */
  47275. TargetCamera.prototype._initCache = function () {
  47276. _super.prototype._initCache.call(this);
  47277. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47278. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47279. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47280. };
  47281. /** @hidden */
  47282. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47283. if (!ignoreParentClass) {
  47284. _super.prototype._updateCache.call(this);
  47285. }
  47286. var lockedTargetPosition = this._getLockedTargetPosition();
  47287. if (!lockedTargetPosition) {
  47288. this._cache.lockedTarget = null;
  47289. }
  47290. else {
  47291. if (!this._cache.lockedTarget) {
  47292. this._cache.lockedTarget = lockedTargetPosition.clone();
  47293. }
  47294. else {
  47295. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47296. }
  47297. }
  47298. this._cache.rotation.copyFrom(this.rotation);
  47299. if (this.rotationQuaternion)
  47300. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47301. };
  47302. // Synchronized
  47303. /** @hidden */
  47304. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47305. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47306. return false;
  47307. }
  47308. var lockedTargetPosition = this._getLockedTargetPosition();
  47309. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47310. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47311. };
  47312. // Methods
  47313. /** @hidden */
  47314. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47315. var engine = this.getEngine();
  47316. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47317. };
  47318. // Target
  47319. /** @hidden */
  47320. TargetCamera.prototype.setTarget = function (target) {
  47321. this.upVector.normalize();
  47322. if (this.position.z === target.z) {
  47323. this.position.z += BABYLON.Epsilon;
  47324. }
  47325. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47326. this._camMatrix.invert();
  47327. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47328. var vDir = target.subtract(this.position);
  47329. if (vDir.x >= 0.0) {
  47330. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47331. }
  47332. else {
  47333. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47334. }
  47335. this.rotation.z = 0;
  47336. if (isNaN(this.rotation.x)) {
  47337. this.rotation.x = 0;
  47338. }
  47339. if (isNaN(this.rotation.y)) {
  47340. this.rotation.y = 0;
  47341. }
  47342. if (isNaN(this.rotation.z)) {
  47343. this.rotation.z = 0;
  47344. }
  47345. if (this.rotationQuaternion) {
  47346. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47347. }
  47348. };
  47349. /**
  47350. * Return the current target position of the camera. This value is expressed in local space.
  47351. * @returns the target position
  47352. */
  47353. TargetCamera.prototype.getTarget = function () {
  47354. return this._currentTarget;
  47355. };
  47356. /** @hidden */
  47357. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47358. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47359. };
  47360. /** @hidden */
  47361. TargetCamera.prototype._updatePosition = function () {
  47362. if (this.parent) {
  47363. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47364. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47365. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47366. return;
  47367. }
  47368. this.position.addInPlace(this.cameraDirection);
  47369. };
  47370. /** @hidden */
  47371. TargetCamera.prototype._checkInputs = function () {
  47372. var needToMove = this._decideIfNeedsToMove();
  47373. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47374. // Move
  47375. if (needToMove) {
  47376. this._updatePosition();
  47377. }
  47378. // Rotate
  47379. if (needToRotate) {
  47380. this.rotation.x += this.cameraRotation.x;
  47381. this.rotation.y += this.cameraRotation.y;
  47382. //rotate, if quaternion is set and rotation was used
  47383. if (this.rotationQuaternion) {
  47384. var len = this.rotation.lengthSquared();
  47385. if (len) {
  47386. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47387. }
  47388. }
  47389. if (!this.noRotationConstraint) {
  47390. var limit = (Math.PI / 2) * 0.95;
  47391. if (this.rotation.x > limit)
  47392. this.rotation.x = limit;
  47393. if (this.rotation.x < -limit)
  47394. this.rotation.x = -limit;
  47395. }
  47396. }
  47397. // Inertia
  47398. if (needToMove) {
  47399. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47400. this.cameraDirection.x = 0;
  47401. }
  47402. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47403. this.cameraDirection.y = 0;
  47404. }
  47405. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47406. this.cameraDirection.z = 0;
  47407. }
  47408. this.cameraDirection.scaleInPlace(this.inertia);
  47409. }
  47410. if (needToRotate) {
  47411. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47412. this.cameraRotation.x = 0;
  47413. }
  47414. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47415. this.cameraRotation.y = 0;
  47416. }
  47417. this.cameraRotation.scaleInPlace(this.inertia);
  47418. }
  47419. _super.prototype._checkInputs.call(this);
  47420. };
  47421. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47422. if (this.rotationQuaternion) {
  47423. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47424. }
  47425. else {
  47426. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47427. }
  47428. };
  47429. /**
  47430. * 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)
  47431. * @returns the current camera
  47432. */
  47433. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  47434. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  47435. return this;
  47436. };
  47437. /** @hidden */
  47438. TargetCamera.prototype._getViewMatrix = function () {
  47439. if (this.lockedTarget) {
  47440. this.setTarget(this._getLockedTargetPosition());
  47441. }
  47442. // Compute
  47443. this._updateCameraRotationMatrix();
  47444. // Apply the changed rotation to the upVector.
  47445. if (this._cachedRotationZ != this.rotation.z) {
  47446. this._rotateUpVectorWithCameraRotationMatrix();
  47447. this._cachedRotationZ = this.rotation.z;
  47448. }
  47449. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47450. // Computing target and final matrix
  47451. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47452. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  47453. return this._viewMatrix;
  47454. };
  47455. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47456. if (this.parent) {
  47457. var parentWorldMatrix = this.parent.getWorldMatrix();
  47458. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  47459. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47460. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47461. this._markSyncedWithParent();
  47462. }
  47463. else {
  47464. this._globalPosition.copyFrom(position);
  47465. this._globalCurrentTarget.copyFrom(target);
  47466. this._globalCurrentUpVector.copyFrom(up);
  47467. }
  47468. if (this.getScene().useRightHandedSystem) {
  47469. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47470. }
  47471. else {
  47472. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47473. }
  47474. };
  47475. /**
  47476. * @hidden
  47477. */
  47478. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47479. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47480. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47481. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47482. if (!this.rotationQuaternion) {
  47483. this.rotationQuaternion = new BABYLON.Quaternion();
  47484. }
  47485. rigCamera._cameraRigParams = {};
  47486. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47487. }
  47488. return rigCamera;
  47489. }
  47490. return null;
  47491. };
  47492. /**
  47493. * @hidden
  47494. */
  47495. TargetCamera.prototype._updateRigCameras = function () {
  47496. var camLeft = this._rigCameras[0];
  47497. var camRight = this._rigCameras[1];
  47498. switch (this.cameraRigMode) {
  47499. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47500. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47501. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47503. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47504. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47505. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47506. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47507. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47508. camLeft.setTarget(this.getTarget());
  47509. camRight.setTarget(this.getTarget());
  47510. break;
  47511. case BABYLON.Camera.RIG_MODE_VR:
  47512. if (camLeft.rotationQuaternion) {
  47513. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47514. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47515. }
  47516. else {
  47517. camLeft.rotation.copyFrom(this.rotation);
  47518. camRight.rotation.copyFrom(this.rotation);
  47519. }
  47520. camLeft.position.copyFrom(this.position);
  47521. camRight.position.copyFrom(this.position);
  47522. break;
  47523. }
  47524. _super.prototype._updateRigCameras.call(this);
  47525. };
  47526. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47527. if (!this._rigCamTransformMatrix) {
  47528. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47529. }
  47530. var target = this.getTarget();
  47531. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47532. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47533. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47534. };
  47535. /**
  47536. * Gets the current object class name.
  47537. * @return the class name
  47538. */
  47539. TargetCamera.prototype.getClassName = function () {
  47540. return "TargetCamera";
  47541. };
  47542. __decorate([
  47543. BABYLON.serializeAsVector3()
  47544. ], TargetCamera.prototype, "rotation", void 0);
  47545. __decorate([
  47546. BABYLON.serialize()
  47547. ], TargetCamera.prototype, "speed", void 0);
  47548. __decorate([
  47549. BABYLON.serializeAsMeshReference("lockedTargetId")
  47550. ], TargetCamera.prototype, "lockedTarget", void 0);
  47551. return TargetCamera;
  47552. }(BABYLON.Camera));
  47553. BABYLON.TargetCamera = TargetCamera;
  47554. })(BABYLON || (BABYLON = {}));
  47555. //# sourceMappingURL=babylon.targetCamera.js.map
  47556. var BABYLON;
  47557. (function (BABYLON) {
  47558. /**
  47559. * Manage the mouse inputs to control the movement of a free camera.
  47560. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47561. */
  47562. var FreeCameraMouseInput = /** @class */ (function () {
  47563. /**
  47564. * Manage the mouse inputs to control the movement of a free camera.
  47565. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47566. * @param touchEnabled Defines if touch is enabled or not
  47567. */
  47568. function FreeCameraMouseInput(
  47569. /**
  47570. * Define if touch is enabled in the mouse input
  47571. */
  47572. touchEnabled) {
  47573. if (touchEnabled === void 0) { touchEnabled = true; }
  47574. this.touchEnabled = touchEnabled;
  47575. /**
  47576. * Defines the buttons associated with the input to handle camera move.
  47577. */
  47578. this.buttons = [0, 1, 2];
  47579. /**
  47580. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47581. */
  47582. this.angularSensibility = 2000.0;
  47583. this.previousPosition = null;
  47584. }
  47585. /**
  47586. * Attach the input controls to a specific dom element to get the input from.
  47587. * @param element Defines the element the controls should be listened from
  47588. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47589. */
  47590. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47591. var _this = this;
  47592. var engine = this.camera.getEngine();
  47593. if (!this._pointerInput) {
  47594. this._pointerInput = function (p, s) {
  47595. var evt = p.event;
  47596. if (engine.isInVRExclusivePointerMode) {
  47597. return;
  47598. }
  47599. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47600. return;
  47601. }
  47602. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47603. return;
  47604. }
  47605. var srcElement = (evt.srcElement || evt.target);
  47606. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47607. try {
  47608. srcElement.setPointerCapture(evt.pointerId);
  47609. }
  47610. catch (e) {
  47611. //Nothing to do with the error. Execution will continue.
  47612. }
  47613. _this.previousPosition = {
  47614. x: evt.clientX,
  47615. y: evt.clientY
  47616. };
  47617. if (!noPreventDefault) {
  47618. evt.preventDefault();
  47619. element.focus();
  47620. }
  47621. }
  47622. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47623. try {
  47624. srcElement.releasePointerCapture(evt.pointerId);
  47625. }
  47626. catch (e) {
  47627. //Nothing to do with the error.
  47628. }
  47629. _this.previousPosition = null;
  47630. if (!noPreventDefault) {
  47631. evt.preventDefault();
  47632. }
  47633. }
  47634. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47635. if (!_this.previousPosition || engine.isPointerLock) {
  47636. return;
  47637. }
  47638. var offsetX = evt.clientX - _this.previousPosition.x;
  47639. if (_this.camera.getScene().useRightHandedSystem)
  47640. offsetX *= -1;
  47641. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47642. offsetX *= -1;
  47643. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47644. var offsetY = evt.clientY - _this.previousPosition.y;
  47645. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47646. _this.previousPosition = {
  47647. x: evt.clientX,
  47648. y: evt.clientY
  47649. };
  47650. if (!noPreventDefault) {
  47651. evt.preventDefault();
  47652. }
  47653. }
  47654. };
  47655. }
  47656. this._onMouseMove = function (evt) {
  47657. if (!engine.isPointerLock) {
  47658. return;
  47659. }
  47660. if (engine.isInVRExclusivePointerMode) {
  47661. return;
  47662. }
  47663. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47664. if (_this.camera.getScene().useRightHandedSystem)
  47665. offsetX *= -1;
  47666. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47667. offsetX *= -1;
  47668. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47669. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47670. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47671. _this.previousPosition = null;
  47672. if (!noPreventDefault) {
  47673. evt.preventDefault();
  47674. }
  47675. };
  47676. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47677. element.addEventListener("mousemove", this._onMouseMove, false);
  47678. };
  47679. /**
  47680. * Detach the current controls from the specified dom element.
  47681. * @param element Defines the element to stop listening the inputs from
  47682. */
  47683. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47684. if (this._observer && element) {
  47685. this.camera.getScene().onPointerObservable.remove(this._observer);
  47686. if (this._onMouseMove) {
  47687. element.removeEventListener("mousemove", this._onMouseMove);
  47688. }
  47689. this._observer = null;
  47690. this._onMouseMove = null;
  47691. this.previousPosition = null;
  47692. }
  47693. };
  47694. /**
  47695. * Gets the class name of the current intput.
  47696. * @returns the class name
  47697. */
  47698. FreeCameraMouseInput.prototype.getClassName = function () {
  47699. return "FreeCameraMouseInput";
  47700. };
  47701. /**
  47702. * Get the friendly name associated with the input class.
  47703. * @returns the input friendly name
  47704. */
  47705. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47706. return "mouse";
  47707. };
  47708. __decorate([
  47709. BABYLON.serialize()
  47710. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47711. __decorate([
  47712. BABYLON.serialize()
  47713. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47714. return FreeCameraMouseInput;
  47715. }());
  47716. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47717. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47718. })(BABYLON || (BABYLON = {}));
  47719. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47720. var BABYLON;
  47721. (function (BABYLON) {
  47722. /**
  47723. * Manage the keyboard inputs to control the movement of a free camera.
  47724. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47725. */
  47726. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47727. function FreeCameraKeyboardMoveInput() {
  47728. /**
  47729. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47730. */
  47731. this.keysUp = [38];
  47732. /**
  47733. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47734. */
  47735. this.keysDown = [40];
  47736. /**
  47737. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47738. */
  47739. this.keysLeft = [37];
  47740. /**
  47741. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47742. */
  47743. this.keysRight = [39];
  47744. this._keys = new Array();
  47745. }
  47746. /**
  47747. * Attach the input controls to a specific dom element to get the input from.
  47748. * @param element Defines the element the controls should be listened from
  47749. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47750. */
  47751. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47752. var _this = this;
  47753. if (this._onCanvasBlurObserver) {
  47754. return;
  47755. }
  47756. this._scene = this.camera.getScene();
  47757. this._engine = this._scene.getEngine();
  47758. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47759. _this._keys = [];
  47760. });
  47761. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47762. var evt = info.event;
  47763. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47764. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47765. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47766. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47767. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47768. var index = _this._keys.indexOf(evt.keyCode);
  47769. if (index === -1) {
  47770. _this._keys.push(evt.keyCode);
  47771. }
  47772. if (!noPreventDefault) {
  47773. evt.preventDefault();
  47774. }
  47775. }
  47776. }
  47777. else {
  47778. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47779. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47780. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47781. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47782. var index = _this._keys.indexOf(evt.keyCode);
  47783. if (index >= 0) {
  47784. _this._keys.splice(index, 1);
  47785. }
  47786. if (!noPreventDefault) {
  47787. evt.preventDefault();
  47788. }
  47789. }
  47790. }
  47791. });
  47792. };
  47793. /**
  47794. * Detach the current controls from the specified dom element.
  47795. * @param element Defines the element to stop listening the inputs from
  47796. */
  47797. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47798. if (this._scene) {
  47799. if (this._onKeyboardObserver) {
  47800. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47801. }
  47802. if (this._onCanvasBlurObserver) {
  47803. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47804. }
  47805. this._onKeyboardObserver = null;
  47806. this._onCanvasBlurObserver = null;
  47807. }
  47808. this._keys = [];
  47809. };
  47810. /**
  47811. * Update the current camera state depending on the inputs that have been used this frame.
  47812. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47813. */
  47814. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47815. if (this._onKeyboardObserver) {
  47816. var camera = this.camera;
  47817. // Keyboard
  47818. for (var index = 0; index < this._keys.length; index++) {
  47819. var keyCode = this._keys[index];
  47820. var speed = camera._computeLocalCameraSpeed();
  47821. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47822. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47823. }
  47824. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47825. camera._localDirection.copyFromFloats(0, 0, speed);
  47826. }
  47827. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47828. camera._localDirection.copyFromFloats(speed, 0, 0);
  47829. }
  47830. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47831. camera._localDirection.copyFromFloats(0, 0, -speed);
  47832. }
  47833. if (camera.getScene().useRightHandedSystem) {
  47834. camera._localDirection.z *= -1;
  47835. }
  47836. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47837. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47838. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47839. }
  47840. }
  47841. };
  47842. /**
  47843. * Gets the class name of the current intput.
  47844. * @returns the class name
  47845. */
  47846. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47847. return "FreeCameraKeyboardMoveInput";
  47848. };
  47849. /** @hidden */
  47850. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47851. this._keys = [];
  47852. };
  47853. /**
  47854. * Get the friendly name associated with the input class.
  47855. * @returns the input friendly name
  47856. */
  47857. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47858. return "keyboard";
  47859. };
  47860. __decorate([
  47861. BABYLON.serialize()
  47862. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47863. __decorate([
  47864. BABYLON.serialize()
  47865. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47866. __decorate([
  47867. BABYLON.serialize()
  47868. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47869. __decorate([
  47870. BABYLON.serialize()
  47871. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47872. return FreeCameraKeyboardMoveInput;
  47873. }());
  47874. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47875. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47876. })(BABYLON || (BABYLON = {}));
  47877. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47878. var BABYLON;
  47879. (function (BABYLON) {
  47880. /**
  47881. * Default Inputs manager for the FreeCamera.
  47882. * It groups all the default supported inputs for ease of use.
  47883. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47884. */
  47885. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47886. __extends(FreeCameraInputsManager, _super);
  47887. /**
  47888. * Instantiates a new FreeCameraInputsManager.
  47889. * @param camera Defines the camera the inputs belong to
  47890. */
  47891. function FreeCameraInputsManager(camera) {
  47892. return _super.call(this, camera) || this;
  47893. }
  47894. /**
  47895. * Add keyboard input support to the input manager.
  47896. * @returns the current input manager
  47897. */
  47898. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47899. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47900. return this;
  47901. };
  47902. /**
  47903. * Add mouse input support to the input manager.
  47904. * @returns the current input manager
  47905. */
  47906. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47907. if (touchEnabled === void 0) { touchEnabled = true; }
  47908. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47909. return this;
  47910. };
  47911. /**
  47912. * Add orientation input support to the input manager.
  47913. * @returns the current input manager
  47914. */
  47915. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47916. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47917. return this;
  47918. };
  47919. /**
  47920. * Add touch input support to the input manager.
  47921. * @returns the current input manager
  47922. */
  47923. FreeCameraInputsManager.prototype.addTouch = function () {
  47924. this.add(new BABYLON.FreeCameraTouchInput());
  47925. return this;
  47926. };
  47927. /**
  47928. * Add virtual joystick input support to the input manager.
  47929. * @returns the current input manager
  47930. */
  47931. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47932. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47933. return this;
  47934. };
  47935. return FreeCameraInputsManager;
  47936. }(BABYLON.CameraInputsManager));
  47937. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47938. })(BABYLON || (BABYLON = {}));
  47939. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47940. var BABYLON;
  47941. (function (BABYLON) {
  47942. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47943. // Forcing to use the Universal camera
  47944. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47945. });
  47946. /**
  47947. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47948. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47949. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47950. */
  47951. var FreeCamera = /** @class */ (function (_super) {
  47952. __extends(FreeCamera, _super);
  47953. /**
  47954. * Instantiates a Free Camera.
  47955. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47956. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47957. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47958. * @param name Define the name of the camera in the scene
  47959. * @param position Define the start position of the camera in the scene
  47960. * @param scene Define the scene the camera belongs to
  47961. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47962. */
  47963. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47964. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47965. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47966. /**
  47967. * Define the collision ellipsoid of the camera.
  47968. * This is helpful to simulate a camera body like the player body around the camera
  47969. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47970. */
  47971. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47972. /**
  47973. * Define an offset for the position of the ellipsoid around the camera.
  47974. * This can be helpful to determine the center of the body near the gravity center of the body
  47975. * instead of its head.
  47976. */
  47977. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47978. /**
  47979. * Enable or disable collisions of the camera with the rest of the scene objects.
  47980. */
  47981. _this.checkCollisions = false;
  47982. /**
  47983. * Enable or disable gravity on the camera.
  47984. */
  47985. _this.applyGravity = false;
  47986. _this._needMoveForGravity = false;
  47987. _this._oldPosition = BABYLON.Vector3.Zero();
  47988. _this._diffPosition = BABYLON.Vector3.Zero();
  47989. _this._newPosition = BABYLON.Vector3.Zero();
  47990. // Collisions
  47991. _this._collisionMask = -1;
  47992. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47993. if (collidedMesh === void 0) { collidedMesh = null; }
  47994. //TODO move this to the collision coordinator!
  47995. if (_this.getScene().workerCollisions)
  47996. newPosition.multiplyInPlace(_this._collider._radius);
  47997. var updatePosition = function (newPos) {
  47998. _this._newPosition.copyFrom(newPos);
  47999. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48000. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48001. _this.position.addInPlace(_this._diffPosition);
  48002. if (_this.onCollide && collidedMesh) {
  48003. _this.onCollide(collidedMesh);
  48004. }
  48005. }
  48006. };
  48007. updatePosition(newPosition);
  48008. };
  48009. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48010. _this.inputs.addKeyboard().addMouse();
  48011. return _this;
  48012. }
  48013. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48014. /**
  48015. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48016. * Higher values reduce sensitivity.
  48017. */
  48018. get: function () {
  48019. var mouse = this.inputs.attached["mouse"];
  48020. if (mouse)
  48021. return mouse.angularSensibility;
  48022. return 0;
  48023. },
  48024. /**
  48025. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48026. * Higher values reduce sensitivity.
  48027. */
  48028. set: function (value) {
  48029. var mouse = this.inputs.attached["mouse"];
  48030. if (mouse)
  48031. mouse.angularSensibility = value;
  48032. },
  48033. enumerable: true,
  48034. configurable: true
  48035. });
  48036. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48037. /**
  48038. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48039. */
  48040. get: function () {
  48041. var keyboard = this.inputs.attached["keyboard"];
  48042. if (keyboard)
  48043. return keyboard.keysUp;
  48044. return [];
  48045. },
  48046. set: function (value) {
  48047. var keyboard = this.inputs.attached["keyboard"];
  48048. if (keyboard)
  48049. keyboard.keysUp = value;
  48050. },
  48051. enumerable: true,
  48052. configurable: true
  48053. });
  48054. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48055. /**
  48056. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48057. */
  48058. get: function () {
  48059. var keyboard = this.inputs.attached["keyboard"];
  48060. if (keyboard)
  48061. return keyboard.keysDown;
  48062. return [];
  48063. },
  48064. set: function (value) {
  48065. var keyboard = this.inputs.attached["keyboard"];
  48066. if (keyboard)
  48067. keyboard.keysDown = value;
  48068. },
  48069. enumerable: true,
  48070. configurable: true
  48071. });
  48072. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48073. /**
  48074. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48075. */
  48076. get: function () {
  48077. var keyboard = this.inputs.attached["keyboard"];
  48078. if (keyboard)
  48079. return keyboard.keysLeft;
  48080. return [];
  48081. },
  48082. set: function (value) {
  48083. var keyboard = this.inputs.attached["keyboard"];
  48084. if (keyboard)
  48085. keyboard.keysLeft = value;
  48086. },
  48087. enumerable: true,
  48088. configurable: true
  48089. });
  48090. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48091. /**
  48092. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48093. */
  48094. get: function () {
  48095. var keyboard = this.inputs.attached["keyboard"];
  48096. if (keyboard)
  48097. return keyboard.keysRight;
  48098. return [];
  48099. },
  48100. set: function (value) {
  48101. var keyboard = this.inputs.attached["keyboard"];
  48102. if (keyboard)
  48103. keyboard.keysRight = value;
  48104. },
  48105. enumerable: true,
  48106. configurable: true
  48107. });
  48108. /**
  48109. * Attached controls to the current camera.
  48110. * @param element Defines the element the controls should be listened from
  48111. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48112. */
  48113. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48114. this.inputs.attachElement(element, noPreventDefault);
  48115. };
  48116. /**
  48117. * Detach the current controls from the camera.
  48118. * The camera will stop reacting to inputs.
  48119. * @param element Defines the element to stop listening the inputs from
  48120. */
  48121. FreeCamera.prototype.detachControl = function (element) {
  48122. this.inputs.detachElement(element);
  48123. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48124. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48125. };
  48126. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48127. /**
  48128. * Define a collision mask to limit the list of object the camera can collide with
  48129. */
  48130. get: function () {
  48131. return this._collisionMask;
  48132. },
  48133. set: function (mask) {
  48134. this._collisionMask = !isNaN(mask) ? mask : -1;
  48135. },
  48136. enumerable: true,
  48137. configurable: true
  48138. });
  48139. /** @hidden */
  48140. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48141. var globalPosition;
  48142. if (this.parent) {
  48143. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48144. }
  48145. else {
  48146. globalPosition = this.position;
  48147. }
  48148. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48149. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48150. if (!this._collider) {
  48151. this._collider = new BABYLON.Collider();
  48152. }
  48153. this._collider._radius = this.ellipsoid;
  48154. this._collider.collisionMask = this._collisionMask;
  48155. //no need for clone, as long as gravity is not on.
  48156. var actualDisplacement = displacement;
  48157. //add gravity to the direction to prevent the dual-collision checking
  48158. if (this.applyGravity) {
  48159. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48160. actualDisplacement = displacement.add(this.getScene().gravity);
  48161. }
  48162. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48163. };
  48164. /** @hidden */
  48165. FreeCamera.prototype._checkInputs = function () {
  48166. if (!this._localDirection) {
  48167. this._localDirection = BABYLON.Vector3.Zero();
  48168. this._transformedDirection = BABYLON.Vector3.Zero();
  48169. }
  48170. this.inputs.checkInputs();
  48171. _super.prototype._checkInputs.call(this);
  48172. };
  48173. /** @hidden */
  48174. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48175. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48176. };
  48177. /** @hidden */
  48178. FreeCamera.prototype._updatePosition = function () {
  48179. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48180. this._collideWithWorld(this.cameraDirection);
  48181. }
  48182. else {
  48183. _super.prototype._updatePosition.call(this);
  48184. }
  48185. };
  48186. /**
  48187. * Destroy the camera and release the current resources hold by it.
  48188. */
  48189. FreeCamera.prototype.dispose = function () {
  48190. this.inputs.clear();
  48191. _super.prototype.dispose.call(this);
  48192. };
  48193. /**
  48194. * Gets the current object class name.
  48195. * @return the class name
  48196. */
  48197. FreeCamera.prototype.getClassName = function () {
  48198. return "FreeCamera";
  48199. };
  48200. __decorate([
  48201. BABYLON.serializeAsVector3()
  48202. ], FreeCamera.prototype, "ellipsoid", void 0);
  48203. __decorate([
  48204. BABYLON.serializeAsVector3()
  48205. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], FreeCamera.prototype, "checkCollisions", void 0);
  48209. __decorate([
  48210. BABYLON.serialize()
  48211. ], FreeCamera.prototype, "applyGravity", void 0);
  48212. return FreeCamera;
  48213. }(BABYLON.TargetCamera));
  48214. BABYLON.FreeCamera = FreeCamera;
  48215. })(BABYLON || (BABYLON = {}));
  48216. //# sourceMappingURL=babylon.freeCamera.js.map
  48217. var BABYLON;
  48218. (function (BABYLON) {
  48219. /**
  48220. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48221. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48222. */
  48223. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48224. function ArcRotateCameraKeyboardMoveInput() {
  48225. /**
  48226. * Defines the list of key codes associated with the up action (increase alpha)
  48227. */
  48228. this.keysUp = [38];
  48229. /**
  48230. * Defines the list of key codes associated with the down action (decrease alpha)
  48231. */
  48232. this.keysDown = [40];
  48233. /**
  48234. * Defines the list of key codes associated with the left action (increase beta)
  48235. */
  48236. this.keysLeft = [37];
  48237. /**
  48238. * Defines the list of key codes associated with the right action (decrease beta)
  48239. */
  48240. this.keysRight = [39];
  48241. /**
  48242. * Defines the list of key codes associated with the reset action.
  48243. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48244. */
  48245. this.keysReset = [220];
  48246. /**
  48247. * Defines the panning sensibility of the inputs.
  48248. * (How fast is the camera paning)
  48249. */
  48250. this.panningSensibility = 50.0;
  48251. /**
  48252. * Defines the zooming sensibility of the inputs.
  48253. * (How fast is the camera zooming)
  48254. */
  48255. this.zoomingSensibility = 25.0;
  48256. /**
  48257. * Defines wether maintaining the alt key down switch the movement mode from
  48258. * orientation to zoom.
  48259. */
  48260. this.useAltToZoom = true;
  48261. this._keys = new Array();
  48262. }
  48263. /**
  48264. * Attach the input controls to a specific dom element to get the input from.
  48265. * @param element Defines the element the controls should be listened from
  48266. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48267. */
  48268. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48269. var _this = this;
  48270. if (this._onCanvasBlurObserver) {
  48271. return;
  48272. }
  48273. this._scene = this.camera.getScene();
  48274. this._engine = this._scene.getEngine();
  48275. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48276. _this._keys = [];
  48277. });
  48278. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48279. var evt = info.event;
  48280. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48281. _this._ctrlPressed = evt.ctrlKey;
  48282. _this._altPressed = evt.altKey;
  48283. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48284. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48285. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48286. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48287. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48288. var index = _this._keys.indexOf(evt.keyCode);
  48289. if (index === -1) {
  48290. _this._keys.push(evt.keyCode);
  48291. }
  48292. if (evt.preventDefault) {
  48293. if (!noPreventDefault) {
  48294. evt.preventDefault();
  48295. }
  48296. }
  48297. }
  48298. }
  48299. else {
  48300. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48301. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48302. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48303. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48304. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48305. var index = _this._keys.indexOf(evt.keyCode);
  48306. if (index >= 0) {
  48307. _this._keys.splice(index, 1);
  48308. }
  48309. if (evt.preventDefault) {
  48310. if (!noPreventDefault) {
  48311. evt.preventDefault();
  48312. }
  48313. }
  48314. }
  48315. }
  48316. });
  48317. };
  48318. /**
  48319. * Detach the current controls from the specified dom element.
  48320. * @param element Defines the element to stop listening the inputs from
  48321. */
  48322. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48323. if (this._scene) {
  48324. if (this._onKeyboardObserver) {
  48325. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48326. }
  48327. if (this._onCanvasBlurObserver) {
  48328. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48329. }
  48330. this._onKeyboardObserver = null;
  48331. this._onCanvasBlurObserver = null;
  48332. }
  48333. this._keys = [];
  48334. };
  48335. /**
  48336. * Update the current camera state depending on the inputs that have been used this frame.
  48337. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48338. */
  48339. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48340. if (this._onKeyboardObserver) {
  48341. var camera = this.camera;
  48342. for (var index = 0; index < this._keys.length; index++) {
  48343. var keyCode = this._keys[index];
  48344. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48345. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48346. camera.inertialPanningX -= 1 / this.panningSensibility;
  48347. }
  48348. else {
  48349. camera.inertialAlphaOffset -= 0.01;
  48350. }
  48351. }
  48352. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48353. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48354. camera.inertialPanningY += 1 / this.panningSensibility;
  48355. }
  48356. else if (this._altPressed && this.useAltToZoom) {
  48357. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48358. }
  48359. else {
  48360. camera.inertialBetaOffset -= 0.01;
  48361. }
  48362. }
  48363. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48364. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48365. camera.inertialPanningX += 1 / this.panningSensibility;
  48366. }
  48367. else {
  48368. camera.inertialAlphaOffset += 0.01;
  48369. }
  48370. }
  48371. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48372. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48373. camera.inertialPanningY -= 1 / this.panningSensibility;
  48374. }
  48375. else if (this._altPressed && this.useAltToZoom) {
  48376. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48377. }
  48378. else {
  48379. camera.inertialBetaOffset += 0.01;
  48380. }
  48381. }
  48382. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48383. if (camera.useInputToRestoreState) {
  48384. camera.restoreState();
  48385. }
  48386. }
  48387. }
  48388. }
  48389. };
  48390. /**
  48391. * Gets the class name of the current intput.
  48392. * @returns the class name
  48393. */
  48394. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48395. return "ArcRotateCameraKeyboardMoveInput";
  48396. };
  48397. /**
  48398. * Get the friendly name associated with the input class.
  48399. * @returns the input friendly name
  48400. */
  48401. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48402. return "keyboard";
  48403. };
  48404. __decorate([
  48405. BABYLON.serialize()
  48406. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48407. __decorate([
  48408. BABYLON.serialize()
  48409. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48410. __decorate([
  48411. BABYLON.serialize()
  48412. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48413. __decorate([
  48414. BABYLON.serialize()
  48415. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48416. __decorate([
  48417. BABYLON.serialize()
  48418. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48419. __decorate([
  48420. BABYLON.serialize()
  48421. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48422. __decorate([
  48423. BABYLON.serialize()
  48424. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48425. __decorate([
  48426. BABYLON.serialize()
  48427. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48428. return ArcRotateCameraKeyboardMoveInput;
  48429. }());
  48430. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48431. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48432. })(BABYLON || (BABYLON = {}));
  48433. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48434. var BABYLON;
  48435. (function (BABYLON) {
  48436. /**
  48437. * Manage the mouse wheel inputs to control an arc rotate camera.
  48438. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48439. */
  48440. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48441. function ArcRotateCameraMouseWheelInput() {
  48442. /**
  48443. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48444. */
  48445. this.wheelPrecision = 3.0;
  48446. /**
  48447. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48448. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48449. */
  48450. this.wheelDeltaPercentage = 0;
  48451. }
  48452. /**
  48453. * Attach the input controls to a specific dom element to get the input from.
  48454. * @param element Defines the element the controls should be listened from
  48455. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48456. */
  48457. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48458. var _this = this;
  48459. this._wheel = function (p, s) {
  48460. //sanity check - this should be a PointerWheel event.
  48461. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48462. return;
  48463. var event = p.event;
  48464. var delta = 0;
  48465. if (event.wheelDelta) {
  48466. if (_this.wheelDeltaPercentage) {
  48467. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48468. if (event.wheelDelta > 0) {
  48469. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48470. }
  48471. else {
  48472. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48473. }
  48474. }
  48475. else {
  48476. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48477. }
  48478. }
  48479. else if (event.detail) {
  48480. delta = -event.detail / _this.wheelPrecision;
  48481. }
  48482. if (delta)
  48483. _this.camera.inertialRadiusOffset += delta;
  48484. if (event.preventDefault) {
  48485. if (!noPreventDefault) {
  48486. event.preventDefault();
  48487. }
  48488. }
  48489. };
  48490. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48491. };
  48492. /**
  48493. * Detach the current controls from the specified dom element.
  48494. * @param element Defines the element to stop listening the inputs from
  48495. */
  48496. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48497. if (this._observer && element) {
  48498. this.camera.getScene().onPointerObservable.remove(this._observer);
  48499. this._observer = null;
  48500. this._wheel = null;
  48501. }
  48502. };
  48503. /**
  48504. * Gets the class name of the current intput.
  48505. * @returns the class name
  48506. */
  48507. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48508. return "ArcRotateCameraMouseWheelInput";
  48509. };
  48510. /**
  48511. * Get the friendly name associated with the input class.
  48512. * @returns the input friendly name
  48513. */
  48514. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48515. return "mousewheel";
  48516. };
  48517. __decorate([
  48518. BABYLON.serialize()
  48519. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48520. __decorate([
  48521. BABYLON.serialize()
  48522. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48523. return ArcRotateCameraMouseWheelInput;
  48524. }());
  48525. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48526. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48527. })(BABYLON || (BABYLON = {}));
  48528. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48529. var BABYLON;
  48530. (function (BABYLON) {
  48531. /**
  48532. * Manage the pointers inputs to control an arc rotate camera.
  48533. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48534. */
  48535. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48536. function ArcRotateCameraPointersInput() {
  48537. /**
  48538. * Defines the buttons associated with the input to handle camera move.
  48539. */
  48540. this.buttons = [0, 1, 2];
  48541. /**
  48542. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48543. */
  48544. this.angularSensibilityX = 1000.0;
  48545. /**
  48546. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48547. */
  48548. this.angularSensibilityY = 1000.0;
  48549. /**
  48550. * Defines the pointer pinch precision or how fast is the camera zooming.
  48551. */
  48552. this.pinchPrecision = 12.0;
  48553. /**
  48554. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48555. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48556. */
  48557. this.pinchDeltaPercentage = 0;
  48558. /**
  48559. * Defines the pointer panning sensibility or how fast is the camera moving.
  48560. */
  48561. this.panningSensibility = 1000.0;
  48562. /**
  48563. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48564. */
  48565. this.multiTouchPanning = true;
  48566. /**
  48567. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48568. */
  48569. this.multiTouchPanAndZoom = true;
  48570. /**
  48571. * Revers pinch action direction.
  48572. */
  48573. this.pinchInwards = true;
  48574. this._isPanClick = false;
  48575. }
  48576. /**
  48577. * Attach the input controls to a specific dom element to get the input from.
  48578. * @param element Defines the element the controls should be listened from
  48579. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48580. */
  48581. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48582. var _this = this;
  48583. var engine = this.camera.getEngine();
  48584. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48585. var pointA = null;
  48586. var pointB = null;
  48587. var previousPinchSquaredDistance = 0;
  48588. var initialDistance = 0;
  48589. var twoFingerActivityCount = 0;
  48590. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48591. this._pointerInput = function (p, s) {
  48592. var evt = p.event;
  48593. var isTouch = p.event.pointerType === "touch";
  48594. if (engine.isInVRExclusivePointerMode) {
  48595. return;
  48596. }
  48597. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48598. return;
  48599. }
  48600. var srcElement = (evt.srcElement || evt.target);
  48601. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48602. try {
  48603. srcElement.setPointerCapture(evt.pointerId);
  48604. }
  48605. catch (e) {
  48606. //Nothing to do with the error. Execution will continue.
  48607. }
  48608. // Manage panning with pan button click
  48609. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48610. // manage pointers
  48611. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48612. if (pointA === null) {
  48613. pointA = cacheSoloPointer;
  48614. }
  48615. else if (pointB === null) {
  48616. pointB = cacheSoloPointer;
  48617. }
  48618. if (!noPreventDefault) {
  48619. evt.preventDefault();
  48620. element.focus();
  48621. }
  48622. }
  48623. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48624. if (_this.camera.useInputToRestoreState) {
  48625. _this.camera.restoreState();
  48626. }
  48627. }
  48628. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48629. try {
  48630. srcElement.releasePointerCapture(evt.pointerId);
  48631. }
  48632. catch (e) {
  48633. //Nothing to do with the error.
  48634. }
  48635. cacheSoloPointer = null;
  48636. previousPinchSquaredDistance = 0;
  48637. previousMultiTouchPanPosition.isPaning = false;
  48638. previousMultiTouchPanPosition.isPinching = false;
  48639. twoFingerActivityCount = 0;
  48640. initialDistance = 0;
  48641. if (!isTouch) {
  48642. pointB = null; // Mouse and pen are mono pointer
  48643. }
  48644. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48645. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48646. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48647. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48648. if (engine._badOS) {
  48649. pointA = pointB = null;
  48650. }
  48651. else {
  48652. //only remove the impacted pointer in case of multitouch allowing on most
  48653. //platforms switching from rotate to zoom and pan seamlessly.
  48654. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48655. pointA = pointB;
  48656. pointB = null;
  48657. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48658. }
  48659. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48660. pointB = null;
  48661. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48662. }
  48663. else {
  48664. pointA = pointB = null;
  48665. }
  48666. }
  48667. if (!noPreventDefault) {
  48668. evt.preventDefault();
  48669. }
  48670. }
  48671. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48672. if (!noPreventDefault) {
  48673. evt.preventDefault();
  48674. }
  48675. // One button down
  48676. if (pointA && pointB === null && cacheSoloPointer) {
  48677. if (_this.panningSensibility !== 0 &&
  48678. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48679. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48680. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48681. }
  48682. else {
  48683. var offsetX = evt.clientX - cacheSoloPointer.x;
  48684. var offsetY = evt.clientY - cacheSoloPointer.y;
  48685. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48686. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48687. }
  48688. cacheSoloPointer.x = evt.clientX;
  48689. cacheSoloPointer.y = evt.clientY;
  48690. }
  48691. // Two buttons down: pinch/pan
  48692. else if (pointA && pointB) {
  48693. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48694. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48695. ed.x = evt.clientX;
  48696. ed.y = evt.clientY;
  48697. var direction = _this.pinchInwards ? 1 : -1;
  48698. var distX = pointA.x - pointB.x;
  48699. var distY = pointA.y - pointB.y;
  48700. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48701. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48702. if (previousPinchSquaredDistance === 0) {
  48703. initialDistance = pinchDistance;
  48704. previousPinchSquaredDistance = pinchSquaredDistance;
  48705. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48706. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48707. return;
  48708. }
  48709. if (_this.multiTouchPanAndZoom) {
  48710. if (_this.pinchDeltaPercentage) {
  48711. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48712. }
  48713. else {
  48714. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48715. (_this.pinchPrecision *
  48716. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48717. direction);
  48718. }
  48719. if (_this.panningSensibility !== 0) {
  48720. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48721. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48722. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48723. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48724. previousMultiTouchPanPosition.x = pointersCenterX;
  48725. previousMultiTouchPanPosition.y = pointersCenterY;
  48726. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48727. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48728. }
  48729. }
  48730. else {
  48731. twoFingerActivityCount++;
  48732. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48733. if (_this.pinchDeltaPercentage) {
  48734. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48735. }
  48736. else {
  48737. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48738. (_this.pinchPrecision *
  48739. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48740. direction);
  48741. }
  48742. previousMultiTouchPanPosition.isPaning = false;
  48743. previousMultiTouchPanPosition.isPinching = true;
  48744. }
  48745. else {
  48746. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48747. if (!previousMultiTouchPanPosition.isPaning) {
  48748. previousMultiTouchPanPosition.isPaning = true;
  48749. previousMultiTouchPanPosition.isPinching = false;
  48750. previousMultiTouchPanPosition.x = ed.x;
  48751. previousMultiTouchPanPosition.y = ed.y;
  48752. return;
  48753. }
  48754. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48755. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48756. }
  48757. }
  48758. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48759. previousMultiTouchPanPosition.x = ed.x;
  48760. previousMultiTouchPanPosition.y = ed.y;
  48761. }
  48762. }
  48763. previousPinchSquaredDistance = pinchSquaredDistance;
  48764. }
  48765. }
  48766. };
  48767. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48768. this._onContextMenu = function (evt) {
  48769. evt.preventDefault();
  48770. };
  48771. if (!this.camera._useCtrlForPanning) {
  48772. element.addEventListener("contextmenu", this._onContextMenu, false);
  48773. }
  48774. this._onLostFocus = function () {
  48775. //this._keys = [];
  48776. pointA = pointB = null;
  48777. previousPinchSquaredDistance = 0;
  48778. previousMultiTouchPanPosition.isPaning = false;
  48779. previousMultiTouchPanPosition.isPinching = false;
  48780. twoFingerActivityCount = 0;
  48781. cacheSoloPointer = null;
  48782. initialDistance = 0;
  48783. };
  48784. this._onMouseMove = function (evt) {
  48785. if (!engine.isPointerLock) {
  48786. return;
  48787. }
  48788. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48789. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48790. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48791. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48792. if (!noPreventDefault) {
  48793. evt.preventDefault();
  48794. }
  48795. };
  48796. this._onGestureStart = function (e) {
  48797. if (window.MSGesture === undefined) {
  48798. return;
  48799. }
  48800. if (!_this._MSGestureHandler) {
  48801. _this._MSGestureHandler = new MSGesture();
  48802. _this._MSGestureHandler.target = element;
  48803. }
  48804. _this._MSGestureHandler.addPointer(e.pointerId);
  48805. };
  48806. this._onGesture = function (e) {
  48807. _this.camera.radius *= e.scale;
  48808. if (e.preventDefault) {
  48809. if (!noPreventDefault) {
  48810. e.stopPropagation();
  48811. e.preventDefault();
  48812. }
  48813. }
  48814. };
  48815. element.addEventListener("mousemove", this._onMouseMove, false);
  48816. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48817. element.addEventListener("MSGestureChange", this._onGesture, false);
  48818. BABYLON.Tools.RegisterTopRootEvents([
  48819. { name: "blur", handler: this._onLostFocus }
  48820. ]);
  48821. };
  48822. /**
  48823. * Detach the current controls from the specified dom element.
  48824. * @param element Defines the element to stop listening the inputs from
  48825. */
  48826. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48827. if (this._onLostFocus) {
  48828. BABYLON.Tools.UnregisterTopRootEvents([
  48829. { name: "blur", handler: this._onLostFocus }
  48830. ]);
  48831. }
  48832. if (element && this._observer) {
  48833. this.camera.getScene().onPointerObservable.remove(this._observer);
  48834. this._observer = null;
  48835. if (this._onContextMenu) {
  48836. element.removeEventListener("contextmenu", this._onContextMenu);
  48837. }
  48838. if (this._onMouseMove) {
  48839. element.removeEventListener("mousemove", this._onMouseMove);
  48840. }
  48841. if (this._onGestureStart) {
  48842. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48843. }
  48844. if (this._onGesture) {
  48845. element.removeEventListener("MSGestureChange", this._onGesture);
  48846. }
  48847. this._isPanClick = false;
  48848. this.pinchInwards = true;
  48849. this._onMouseMove = null;
  48850. this._onGestureStart = null;
  48851. this._onGesture = null;
  48852. this._MSGestureHandler = null;
  48853. this._onLostFocus = null;
  48854. this._onContextMenu = null;
  48855. }
  48856. };
  48857. /**
  48858. * Gets the class name of the current intput.
  48859. * @returns the class name
  48860. */
  48861. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48862. return "ArcRotateCameraPointersInput";
  48863. };
  48864. /**
  48865. * Get the friendly name associated with the input class.
  48866. * @returns the input friendly name
  48867. */
  48868. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48869. return "pointers";
  48870. };
  48871. __decorate([
  48872. BABYLON.serialize()
  48873. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48874. __decorate([
  48875. BABYLON.serialize()
  48876. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48877. __decorate([
  48878. BABYLON.serialize()
  48879. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48880. __decorate([
  48881. BABYLON.serialize()
  48882. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48883. __decorate([
  48884. BABYLON.serialize()
  48885. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48886. __decorate([
  48887. BABYLON.serialize()
  48888. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48889. __decorate([
  48890. BABYLON.serialize()
  48891. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48892. __decorate([
  48893. BABYLON.serialize()
  48894. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48895. return ArcRotateCameraPointersInput;
  48896. }());
  48897. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48898. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48899. })(BABYLON || (BABYLON = {}));
  48900. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48901. var BABYLON;
  48902. (function (BABYLON) {
  48903. /**
  48904. * Default Inputs manager for the ArcRotateCamera.
  48905. * It groups all the default supported inputs for ease of use.
  48906. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48907. */
  48908. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48909. __extends(ArcRotateCameraInputsManager, _super);
  48910. /**
  48911. * Instantiates a new ArcRotateCameraInputsManager.
  48912. * @param camera Defines the camera the inputs belong to
  48913. */
  48914. function ArcRotateCameraInputsManager(camera) {
  48915. return _super.call(this, camera) || this;
  48916. }
  48917. /**
  48918. * Add mouse wheel input support to the input manager.
  48919. * @returns the current input manager
  48920. */
  48921. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48922. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48923. return this;
  48924. };
  48925. /**
  48926. * Add pointers input support to the input manager.
  48927. * @returns the current input manager
  48928. */
  48929. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48930. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48931. return this;
  48932. };
  48933. /**
  48934. * Add keyboard input support to the input manager.
  48935. * @returns the current input manager
  48936. */
  48937. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48938. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48939. return this;
  48940. };
  48941. /**
  48942. * Add orientation input support to the input manager.
  48943. * @returns the current input manager
  48944. */
  48945. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48946. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48947. return this;
  48948. };
  48949. return ArcRotateCameraInputsManager;
  48950. }(BABYLON.CameraInputsManager));
  48951. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48952. })(BABYLON || (BABYLON = {}));
  48953. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48954. var BABYLON;
  48955. (function (BABYLON) {
  48956. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48957. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48958. });
  48959. /**
  48960. * This represents an orbital type of camera.
  48961. *
  48962. * 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.
  48963. * 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.
  48964. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48965. */
  48966. var ArcRotateCamera = /** @class */ (function (_super) {
  48967. __extends(ArcRotateCamera, _super);
  48968. /**
  48969. * Instantiates a new ArcRotateCamera in a given scene
  48970. * @param name Defines the name of the camera
  48971. * @param alpha Defines the camera rotation along the logitudinal axis
  48972. * @param beta Defines the camera rotation along the latitudinal axis
  48973. * @param radius Defines the camera distance from its target
  48974. * @param target Defines the camera target
  48975. * @param scene Defines the scene the camera belongs to
  48976. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48977. */
  48978. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48979. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48980. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48981. /**
  48982. * Current inertia value on the longitudinal axis.
  48983. * The bigger this number the longer it will take for the camera to stop.
  48984. */
  48985. _this.inertialAlphaOffset = 0;
  48986. /**
  48987. * Current inertia value on the latitudinal axis.
  48988. * The bigger this number the longer it will take for the camera to stop.
  48989. */
  48990. _this.inertialBetaOffset = 0;
  48991. /**
  48992. * Current inertia value on the radius axis.
  48993. * The bigger this number the longer it will take for the camera to stop.
  48994. */
  48995. _this.inertialRadiusOffset = 0;
  48996. /**
  48997. * Minimum allowed angle on the longitudinal axis.
  48998. * This can help limiting how the Camera is able to move in the scene.
  48999. */
  49000. _this.lowerAlphaLimit = null;
  49001. /**
  49002. * Maximum allowed angle on the longitudinal axis.
  49003. * This can help limiting how the Camera is able to move in the scene.
  49004. */
  49005. _this.upperAlphaLimit = null;
  49006. /**
  49007. * Minimum allowed angle on the latitudinal axis.
  49008. * This can help limiting how the Camera is able to move in the scene.
  49009. */
  49010. _this.lowerBetaLimit = 0.01;
  49011. /**
  49012. * Maximum allowed angle on the latitudinal axis.
  49013. * This can help limiting how the Camera is able to move in the scene.
  49014. */
  49015. _this.upperBetaLimit = Math.PI;
  49016. /**
  49017. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49018. * This can help limiting how the Camera is able to move in the scene.
  49019. */
  49020. _this.lowerRadiusLimit = null;
  49021. /**
  49022. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49023. * This can help limiting how the Camera is able to move in the scene.
  49024. */
  49025. _this.upperRadiusLimit = null;
  49026. /**
  49027. * Defines the current inertia value used during panning of the camera along the X axis.
  49028. */
  49029. _this.inertialPanningX = 0;
  49030. /**
  49031. * Defines the current inertia value used during panning of the camera along the Y axis.
  49032. */
  49033. _this.inertialPanningY = 0;
  49034. /**
  49035. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49036. * Basically if your fingers moves away from more than this distance you will be considered
  49037. * in pinch mode.
  49038. */
  49039. _this.pinchToPanMaxDistance = 20;
  49040. /**
  49041. * Defines the maximum distance the camera can pan.
  49042. * This could help keeping the cammera always in your scene.
  49043. */
  49044. _this.panningDistanceLimit = null;
  49045. /**
  49046. * Defines the target of the camera before paning.
  49047. */
  49048. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49049. /**
  49050. * Defines the value of the inertia used during panning.
  49051. * 0 would mean stop inertia and one would mean no decelleration at all.
  49052. */
  49053. _this.panningInertia = 0.9;
  49054. //-- end properties for backward compatibility for inputs
  49055. /**
  49056. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49057. */
  49058. _this.zoomOnFactor = 1;
  49059. /**
  49060. * Defines a screen offset for the camera position.
  49061. */
  49062. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49063. /**
  49064. * Allows the camera to be completely reversed.
  49065. * If false the camera can not arrive upside down.
  49066. */
  49067. _this.allowUpsideDown = true;
  49068. /**
  49069. * Define if double tap/click is used to restore the previously saved state of the camera.
  49070. */
  49071. _this.useInputToRestoreState = true;
  49072. /** @hidden */
  49073. _this._viewMatrix = new BABYLON.Matrix();
  49074. /**
  49075. * Defines the allowed panning axis.
  49076. */
  49077. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49078. /**
  49079. * Observable triggered when the mesh target has been changed on the camera.
  49080. */
  49081. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49082. /**
  49083. * Defines whether the camera should check collision with the objects oh the scene.
  49084. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49085. */
  49086. _this.checkCollisions = false;
  49087. /**
  49088. * Defines the collision radius of the camera.
  49089. * This simulates a sphere around the camera.
  49090. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49091. */
  49092. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49093. _this._previousPosition = BABYLON.Vector3.Zero();
  49094. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49095. _this._newPosition = BABYLON.Vector3.Zero();
  49096. _this._computationVector = BABYLON.Vector3.Zero();
  49097. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49098. if (collidedMesh === void 0) { collidedMesh = null; }
  49099. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49100. newPosition.multiplyInPlace(_this._collider._radius);
  49101. }
  49102. if (!collidedMesh) {
  49103. _this._previousPosition.copyFrom(_this.position);
  49104. }
  49105. else {
  49106. _this.setPosition(newPosition);
  49107. if (_this.onCollide) {
  49108. _this.onCollide(collidedMesh);
  49109. }
  49110. }
  49111. // Recompute because of constraints
  49112. var cosa = Math.cos(_this.alpha);
  49113. var sina = Math.sin(_this.alpha);
  49114. var cosb = Math.cos(_this.beta);
  49115. var sinb = Math.sin(_this.beta);
  49116. if (sinb === 0) {
  49117. sinb = 0.0001;
  49118. }
  49119. var target = _this._getTargetPosition();
  49120. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49121. target.addToRef(_this._computationVector, _this._newPosition);
  49122. _this.position.copyFrom(_this._newPosition);
  49123. var up = _this.upVector;
  49124. if (_this.allowUpsideDown && _this.beta < 0) {
  49125. up = up.clone();
  49126. up = up.negate();
  49127. }
  49128. _this._computeViewMatrix(_this.position, target, up);
  49129. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49130. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49131. _this._collisionTriggered = false;
  49132. };
  49133. _this._target = BABYLON.Vector3.Zero();
  49134. if (target) {
  49135. _this.setTarget(target);
  49136. }
  49137. _this.alpha = alpha;
  49138. _this.beta = beta;
  49139. _this.radius = radius;
  49140. _this.getViewMatrix();
  49141. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49142. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49143. return _this;
  49144. }
  49145. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49146. /**
  49147. * Defines the target point of the camera.
  49148. * The camera looks towards it form the radius distance.
  49149. */
  49150. get: function () {
  49151. return this._target;
  49152. },
  49153. set: function (value) {
  49154. this.setTarget(value);
  49155. },
  49156. enumerable: true,
  49157. configurable: true
  49158. });
  49159. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49160. //-- begin properties for backward compatibility for inputs
  49161. /**
  49162. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49163. */
  49164. get: function () {
  49165. var pointers = this.inputs.attached["pointers"];
  49166. if (pointers)
  49167. return pointers.angularSensibilityX;
  49168. return 0;
  49169. },
  49170. set: function (value) {
  49171. var pointers = this.inputs.attached["pointers"];
  49172. if (pointers) {
  49173. pointers.angularSensibilityX = value;
  49174. }
  49175. },
  49176. enumerable: true,
  49177. configurable: true
  49178. });
  49179. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49180. /**
  49181. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49182. */
  49183. get: function () {
  49184. var pointers = this.inputs.attached["pointers"];
  49185. if (pointers)
  49186. return pointers.angularSensibilityY;
  49187. return 0;
  49188. },
  49189. set: function (value) {
  49190. var pointers = this.inputs.attached["pointers"];
  49191. if (pointers) {
  49192. pointers.angularSensibilityY = value;
  49193. }
  49194. },
  49195. enumerable: true,
  49196. configurable: true
  49197. });
  49198. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49199. /**
  49200. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49201. */
  49202. get: function () {
  49203. var pointers = this.inputs.attached["pointers"];
  49204. if (pointers)
  49205. return pointers.pinchPrecision;
  49206. return 0;
  49207. },
  49208. set: function (value) {
  49209. var pointers = this.inputs.attached["pointers"];
  49210. if (pointers) {
  49211. pointers.pinchPrecision = value;
  49212. }
  49213. },
  49214. enumerable: true,
  49215. configurable: true
  49216. });
  49217. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49218. /**
  49219. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49220. * It will be used instead of pinchDeltaPrecision if different from 0.
  49221. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49222. */
  49223. get: function () {
  49224. var pointers = this.inputs.attached["pointers"];
  49225. if (pointers)
  49226. return pointers.pinchDeltaPercentage;
  49227. return 0;
  49228. },
  49229. set: function (value) {
  49230. var pointers = this.inputs.attached["pointers"];
  49231. if (pointers) {
  49232. pointers.pinchDeltaPercentage = value;
  49233. }
  49234. },
  49235. enumerable: true,
  49236. configurable: true
  49237. });
  49238. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49239. /**
  49240. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49241. */
  49242. get: function () {
  49243. var pointers = this.inputs.attached["pointers"];
  49244. if (pointers)
  49245. return pointers.panningSensibility;
  49246. return 0;
  49247. },
  49248. set: function (value) {
  49249. var pointers = this.inputs.attached["pointers"];
  49250. if (pointers) {
  49251. pointers.panningSensibility = value;
  49252. }
  49253. },
  49254. enumerable: true,
  49255. configurable: true
  49256. });
  49257. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49258. /**
  49259. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49260. */
  49261. get: function () {
  49262. var keyboard = this.inputs.attached["keyboard"];
  49263. if (keyboard)
  49264. return keyboard.keysUp;
  49265. return [];
  49266. },
  49267. set: function (value) {
  49268. var keyboard = this.inputs.attached["keyboard"];
  49269. if (keyboard)
  49270. keyboard.keysUp = value;
  49271. },
  49272. enumerable: true,
  49273. configurable: true
  49274. });
  49275. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49276. /**
  49277. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49278. */
  49279. get: function () {
  49280. var keyboard = this.inputs.attached["keyboard"];
  49281. if (keyboard)
  49282. return keyboard.keysDown;
  49283. return [];
  49284. },
  49285. set: function (value) {
  49286. var keyboard = this.inputs.attached["keyboard"];
  49287. if (keyboard)
  49288. keyboard.keysDown = value;
  49289. },
  49290. enumerable: true,
  49291. configurable: true
  49292. });
  49293. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49294. /**
  49295. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49296. */
  49297. get: function () {
  49298. var keyboard = this.inputs.attached["keyboard"];
  49299. if (keyboard)
  49300. return keyboard.keysLeft;
  49301. return [];
  49302. },
  49303. set: function (value) {
  49304. var keyboard = this.inputs.attached["keyboard"];
  49305. if (keyboard)
  49306. keyboard.keysLeft = value;
  49307. },
  49308. enumerable: true,
  49309. configurable: true
  49310. });
  49311. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49312. /**
  49313. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49314. */
  49315. get: function () {
  49316. var keyboard = this.inputs.attached["keyboard"];
  49317. if (keyboard)
  49318. return keyboard.keysRight;
  49319. return [];
  49320. },
  49321. set: function (value) {
  49322. var keyboard = this.inputs.attached["keyboard"];
  49323. if (keyboard)
  49324. keyboard.keysRight = value;
  49325. },
  49326. enumerable: true,
  49327. configurable: true
  49328. });
  49329. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49330. /**
  49331. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49332. */
  49333. get: function () {
  49334. var mousewheel = this.inputs.attached["mousewheel"];
  49335. if (mousewheel)
  49336. return mousewheel.wheelPrecision;
  49337. return 0;
  49338. },
  49339. set: function (value) {
  49340. var mousewheel = this.inputs.attached["mousewheel"];
  49341. if (mousewheel)
  49342. mousewheel.wheelPrecision = value;
  49343. },
  49344. enumerable: true,
  49345. configurable: true
  49346. });
  49347. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49348. /**
  49349. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  49350. * It will be used instead of pinchDeltaPrecision if different from 0.
  49351. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49352. */
  49353. get: function () {
  49354. var mousewheel = this.inputs.attached["mousewheel"];
  49355. if (mousewheel)
  49356. return mousewheel.wheelDeltaPercentage;
  49357. return 0;
  49358. },
  49359. set: function (value) {
  49360. var mousewheel = this.inputs.attached["mousewheel"];
  49361. if (mousewheel)
  49362. mousewheel.wheelDeltaPercentage = value;
  49363. },
  49364. enumerable: true,
  49365. configurable: true
  49366. });
  49367. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49368. /**
  49369. * Gets the bouncing behavior of the camera if it has been enabled.
  49370. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49371. */
  49372. get: function () {
  49373. return this._bouncingBehavior;
  49374. },
  49375. enumerable: true,
  49376. configurable: true
  49377. });
  49378. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49379. /**
  49380. * Defines if the bouncing behavior of the camera is enabled on the camera.
  49381. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49382. */
  49383. get: function () {
  49384. return this._bouncingBehavior != null;
  49385. },
  49386. set: function (value) {
  49387. if (value === this.useBouncingBehavior) {
  49388. return;
  49389. }
  49390. if (value) {
  49391. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49392. this.addBehavior(this._bouncingBehavior);
  49393. }
  49394. else if (this._bouncingBehavior) {
  49395. this.removeBehavior(this._bouncingBehavior);
  49396. this._bouncingBehavior = null;
  49397. }
  49398. },
  49399. enumerable: true,
  49400. configurable: true
  49401. });
  49402. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49403. /**
  49404. * Gets the framing behavior of the camera if it has been enabled.
  49405. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49406. */
  49407. get: function () {
  49408. return this._framingBehavior;
  49409. },
  49410. enumerable: true,
  49411. configurable: true
  49412. });
  49413. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49414. /**
  49415. * Defines if the framing behavior of the camera is enabled on the camera.
  49416. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49417. */
  49418. get: function () {
  49419. return this._framingBehavior != null;
  49420. },
  49421. set: function (value) {
  49422. if (value === this.useFramingBehavior) {
  49423. return;
  49424. }
  49425. if (value) {
  49426. this._framingBehavior = new BABYLON.FramingBehavior();
  49427. this.addBehavior(this._framingBehavior);
  49428. }
  49429. else if (this._framingBehavior) {
  49430. this.removeBehavior(this._framingBehavior);
  49431. this._framingBehavior = null;
  49432. }
  49433. },
  49434. enumerable: true,
  49435. configurable: true
  49436. });
  49437. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49438. /**
  49439. * Gets the auto rotation behavior of the camera if it has been enabled.
  49440. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49441. */
  49442. get: function () {
  49443. return this._autoRotationBehavior;
  49444. },
  49445. enumerable: true,
  49446. configurable: true
  49447. });
  49448. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49449. /**
  49450. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  49451. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49452. */
  49453. get: function () {
  49454. return this._autoRotationBehavior != null;
  49455. },
  49456. set: function (value) {
  49457. if (value === this.useAutoRotationBehavior) {
  49458. return;
  49459. }
  49460. if (value) {
  49461. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49462. this.addBehavior(this._autoRotationBehavior);
  49463. }
  49464. else if (this._autoRotationBehavior) {
  49465. this.removeBehavior(this._autoRotationBehavior);
  49466. this._autoRotationBehavior = null;
  49467. }
  49468. },
  49469. enumerable: true,
  49470. configurable: true
  49471. });
  49472. // Cache
  49473. /** @hidden */
  49474. ArcRotateCamera.prototype._initCache = function () {
  49475. _super.prototype._initCache.call(this);
  49476. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49477. this._cache.alpha = undefined;
  49478. this._cache.beta = undefined;
  49479. this._cache.radius = undefined;
  49480. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49481. };
  49482. /** @hidden */
  49483. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49484. if (!ignoreParentClass) {
  49485. _super.prototype._updateCache.call(this);
  49486. }
  49487. this._cache._target.copyFrom(this._getTargetPosition());
  49488. this._cache.alpha = this.alpha;
  49489. this._cache.beta = this.beta;
  49490. this._cache.radius = this.radius;
  49491. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49492. };
  49493. ArcRotateCamera.prototype._getTargetPosition = function () {
  49494. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49495. var pos = this._targetHost.getAbsolutePosition();
  49496. if (this._targetBoundingCenter) {
  49497. pos.addToRef(this._targetBoundingCenter, this._target);
  49498. }
  49499. else {
  49500. this._target.copyFrom(pos);
  49501. }
  49502. }
  49503. var lockedTargetPosition = this._getLockedTargetPosition();
  49504. if (lockedTargetPosition) {
  49505. return lockedTargetPosition;
  49506. }
  49507. return this._target;
  49508. };
  49509. /**
  49510. * Stores the current state of the camera (alpha, beta, radius and target)
  49511. * @returns the camera itself
  49512. */
  49513. ArcRotateCamera.prototype.storeState = function () {
  49514. this._storedAlpha = this.alpha;
  49515. this._storedBeta = this.beta;
  49516. this._storedRadius = this.radius;
  49517. this._storedTarget = this._getTargetPosition().clone();
  49518. return _super.prototype.storeState.call(this);
  49519. };
  49520. /**
  49521. * @hidden
  49522. * Restored camera state. You must call storeState() first
  49523. */
  49524. ArcRotateCamera.prototype._restoreStateValues = function () {
  49525. if (!_super.prototype._restoreStateValues.call(this)) {
  49526. return false;
  49527. }
  49528. this.alpha = this._storedAlpha;
  49529. this.beta = this._storedBeta;
  49530. this.radius = this._storedRadius;
  49531. this.setTarget(this._storedTarget.clone());
  49532. this.inertialAlphaOffset = 0;
  49533. this.inertialBetaOffset = 0;
  49534. this.inertialRadiusOffset = 0;
  49535. this.inertialPanningX = 0;
  49536. this.inertialPanningY = 0;
  49537. return true;
  49538. };
  49539. // Synchronized
  49540. /** @hidden */
  49541. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49542. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49543. return false;
  49544. return this._cache._target.equals(this._getTargetPosition())
  49545. && this._cache.alpha === this.alpha
  49546. && this._cache.beta === this.beta
  49547. && this._cache.radius === this.radius
  49548. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49549. };
  49550. /**
  49551. * Attached controls to the current camera.
  49552. * @param element Defines the element the controls should be listened from
  49553. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49554. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49555. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49556. */
  49557. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49558. var _this = this;
  49559. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49560. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49561. this._useCtrlForPanning = useCtrlForPanning;
  49562. this._panningMouseButton = panningMouseButton;
  49563. this.inputs.attachElement(element, noPreventDefault);
  49564. this._reset = function () {
  49565. _this.inertialAlphaOffset = 0;
  49566. _this.inertialBetaOffset = 0;
  49567. _this.inertialRadiusOffset = 0;
  49568. _this.inertialPanningX = 0;
  49569. _this.inertialPanningY = 0;
  49570. };
  49571. };
  49572. /**
  49573. * Detach the current controls from the camera.
  49574. * The camera will stop reacting to inputs.
  49575. * @param element Defines the element to stop listening the inputs from
  49576. */
  49577. ArcRotateCamera.prototype.detachControl = function (element) {
  49578. this.inputs.detachElement(element);
  49579. if (this._reset) {
  49580. this._reset();
  49581. }
  49582. };
  49583. /** @hidden */
  49584. ArcRotateCamera.prototype._checkInputs = function () {
  49585. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49586. if (this._collisionTriggered) {
  49587. return;
  49588. }
  49589. this.inputs.checkInputs();
  49590. // Inertia
  49591. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49592. var inertialAlphaOffset = this.inertialAlphaOffset;
  49593. if (this.beta <= 0)
  49594. inertialAlphaOffset *= -1;
  49595. if (this.getScene().useRightHandedSystem)
  49596. inertialAlphaOffset *= -1;
  49597. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49598. inertialAlphaOffset *= -1;
  49599. this.alpha += inertialAlphaOffset;
  49600. this.beta += this.inertialBetaOffset;
  49601. this.radius -= this.inertialRadiusOffset;
  49602. this.inertialAlphaOffset *= this.inertia;
  49603. this.inertialBetaOffset *= this.inertia;
  49604. this.inertialRadiusOffset *= this.inertia;
  49605. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49606. this.inertialAlphaOffset = 0;
  49607. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49608. this.inertialBetaOffset = 0;
  49609. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49610. this.inertialRadiusOffset = 0;
  49611. }
  49612. // Panning inertia
  49613. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49614. if (!this._localDirection) {
  49615. this._localDirection = BABYLON.Vector3.Zero();
  49616. this._transformedDirection = BABYLON.Vector3.Zero();
  49617. }
  49618. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49619. this._localDirection.multiplyInPlace(this.panningAxis);
  49620. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49621. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49622. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49623. if (!this.panningAxis.y) {
  49624. this._transformedDirection.y = 0;
  49625. }
  49626. if (!this._targetHost) {
  49627. if (this.panningDistanceLimit) {
  49628. this._transformedDirection.addInPlace(this._target);
  49629. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49630. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49631. this._target.copyFrom(this._transformedDirection);
  49632. }
  49633. }
  49634. else {
  49635. this._target.addInPlace(this._transformedDirection);
  49636. }
  49637. }
  49638. this.inertialPanningX *= this.panningInertia;
  49639. this.inertialPanningY *= this.panningInertia;
  49640. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49641. this.inertialPanningX = 0;
  49642. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49643. this.inertialPanningY = 0;
  49644. }
  49645. // Limits
  49646. this._checkLimits();
  49647. _super.prototype._checkInputs.call(this);
  49648. };
  49649. ArcRotateCamera.prototype._checkLimits = function () {
  49650. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49651. if (this.allowUpsideDown && this.beta > Math.PI) {
  49652. this.beta = this.beta - (2 * Math.PI);
  49653. }
  49654. }
  49655. else {
  49656. if (this.beta < this.lowerBetaLimit) {
  49657. this.beta = this.lowerBetaLimit;
  49658. }
  49659. }
  49660. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49661. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49662. this.beta = this.beta + (2 * Math.PI);
  49663. }
  49664. }
  49665. else {
  49666. if (this.beta > this.upperBetaLimit) {
  49667. this.beta = this.upperBetaLimit;
  49668. }
  49669. }
  49670. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49671. this.alpha = this.lowerAlphaLimit;
  49672. }
  49673. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49674. this.alpha = this.upperAlphaLimit;
  49675. }
  49676. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49677. this.radius = this.lowerRadiusLimit;
  49678. }
  49679. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49680. this.radius = this.upperRadiusLimit;
  49681. }
  49682. };
  49683. /**
  49684. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49685. */
  49686. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49687. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49688. this.radius = this._computationVector.length();
  49689. if (this.radius === 0) {
  49690. this.radius = 0.0001; // Just to avoid division by zero
  49691. }
  49692. // Alpha
  49693. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49694. if (this._computationVector.z < 0) {
  49695. this.alpha = 2 * Math.PI - this.alpha;
  49696. }
  49697. // Beta
  49698. this.beta = Math.acos(this._computationVector.y / this.radius);
  49699. this._checkLimits();
  49700. };
  49701. /**
  49702. * Use a position to define the current camera related information like aplha, beta and radius
  49703. * @param position Defines the position to set the camera at
  49704. */
  49705. ArcRotateCamera.prototype.setPosition = function (position) {
  49706. if (this.position.equals(position)) {
  49707. return;
  49708. }
  49709. this.position.copyFrom(position);
  49710. this.rebuildAnglesAndRadius();
  49711. };
  49712. /**
  49713. * Defines the target the camera should look at.
  49714. * This will automatically adapt alpha beta and radius to fit within the new target.
  49715. * @param target Defines the new target as a Vector or a mesh
  49716. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  49717. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  49718. */
  49719. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49720. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49721. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49722. if (target.getBoundingInfo) {
  49723. if (toBoundingCenter) {
  49724. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49725. }
  49726. else {
  49727. this._targetBoundingCenter = null;
  49728. }
  49729. this._targetHost = target;
  49730. this._target = this._getTargetPosition();
  49731. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49732. }
  49733. else {
  49734. var newTarget = target;
  49735. var currentTarget = this._getTargetPosition();
  49736. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49737. return;
  49738. }
  49739. this._targetHost = null;
  49740. this._target = newTarget;
  49741. this._targetBoundingCenter = null;
  49742. this.onMeshTargetChangedObservable.notifyObservers(null);
  49743. }
  49744. this.rebuildAnglesAndRadius();
  49745. };
  49746. /** @hidden */
  49747. ArcRotateCamera.prototype._getViewMatrix = function () {
  49748. // Compute
  49749. var cosa = Math.cos(this.alpha);
  49750. var sina = Math.sin(this.alpha);
  49751. var cosb = Math.cos(this.beta);
  49752. var sinb = Math.sin(this.beta);
  49753. if (sinb === 0) {
  49754. sinb = 0.0001;
  49755. }
  49756. var target = this._getTargetPosition();
  49757. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49758. target.addToRef(this._computationVector, this._newPosition);
  49759. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49760. if (!this._collider) {
  49761. this._collider = new BABYLON.Collider();
  49762. }
  49763. this._collider._radius = this.collisionRadius;
  49764. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49765. this._collisionTriggered = true;
  49766. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49767. }
  49768. else {
  49769. this.position.copyFrom(this._newPosition);
  49770. var up = this.upVector;
  49771. if (this.allowUpsideDown && sinb < 0) {
  49772. up = up.clone();
  49773. up = up.negate();
  49774. }
  49775. this._computeViewMatrix(this.position, target, up);
  49776. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49777. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49778. }
  49779. this._currentTarget = target;
  49780. return this._viewMatrix;
  49781. };
  49782. /**
  49783. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49784. * @param meshes Defines the mesh to zoom on
  49785. * @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)
  49786. */
  49787. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49788. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49789. meshes = meshes || this.getScene().meshes;
  49790. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49791. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49792. this.radius = distance * this.zoomOnFactor;
  49793. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49794. };
  49795. /**
  49796. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49797. * The target will be changed but the radius
  49798. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49799. * @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)
  49800. */
  49801. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49802. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49803. var meshesOrMinMaxVector;
  49804. var distance;
  49805. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49806. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49807. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49808. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49809. }
  49810. else { //minMaxVector and distance
  49811. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49812. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49813. distance = minMaxVectorAndDistance.distance;
  49814. }
  49815. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49816. if (!doNotUpdateMaxZ) {
  49817. this.maxZ = distance * 2;
  49818. }
  49819. };
  49820. /**
  49821. * @override
  49822. * Override Camera.createRigCamera
  49823. */
  49824. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49825. var alphaShift = 0;
  49826. switch (this.cameraRigMode) {
  49827. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49828. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49829. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49830. case BABYLON.Camera.RIG_MODE_VR:
  49831. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49832. break;
  49833. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49834. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49835. break;
  49836. }
  49837. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49838. rigCam._cameraRigParams = {};
  49839. return rigCam;
  49840. };
  49841. /**
  49842. * @hidden
  49843. * @override
  49844. * Override Camera._updateRigCameras
  49845. */
  49846. ArcRotateCamera.prototype._updateRigCameras = function () {
  49847. var camLeft = this._rigCameras[0];
  49848. var camRight = this._rigCameras[1];
  49849. camLeft.beta = camRight.beta = this.beta;
  49850. camLeft.radius = camRight.radius = this.radius;
  49851. switch (this.cameraRigMode) {
  49852. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49853. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49854. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49855. case BABYLON.Camera.RIG_MODE_VR:
  49856. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49857. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49858. break;
  49859. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49860. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49861. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49862. break;
  49863. }
  49864. _super.prototype._updateRigCameras.call(this);
  49865. };
  49866. /**
  49867. * Destroy the camera and release the current resources hold by it.
  49868. */
  49869. ArcRotateCamera.prototype.dispose = function () {
  49870. this.inputs.clear();
  49871. _super.prototype.dispose.call(this);
  49872. };
  49873. /**
  49874. * Gets the current object class name.
  49875. * @return the class name
  49876. */
  49877. ArcRotateCamera.prototype.getClassName = function () {
  49878. return "ArcRotateCamera";
  49879. };
  49880. __decorate([
  49881. BABYLON.serialize()
  49882. ], ArcRotateCamera.prototype, "alpha", void 0);
  49883. __decorate([
  49884. BABYLON.serialize()
  49885. ], ArcRotateCamera.prototype, "beta", void 0);
  49886. __decorate([
  49887. BABYLON.serialize()
  49888. ], ArcRotateCamera.prototype, "radius", void 0);
  49889. __decorate([
  49890. BABYLON.serializeAsVector3("target")
  49891. ], ArcRotateCamera.prototype, "_target", void 0);
  49892. __decorate([
  49893. BABYLON.serialize()
  49894. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49895. __decorate([
  49896. BABYLON.serialize()
  49897. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49898. __decorate([
  49899. BABYLON.serialize()
  49900. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49901. __decorate([
  49902. BABYLON.serialize()
  49903. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49904. __decorate([
  49905. BABYLON.serialize()
  49906. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49907. __decorate([
  49908. BABYLON.serialize()
  49909. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49910. __decorate([
  49911. BABYLON.serialize()
  49912. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49913. __decorate([
  49914. BABYLON.serialize()
  49915. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49916. __decorate([
  49917. BABYLON.serialize()
  49918. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49919. __decorate([
  49920. BABYLON.serialize()
  49921. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49922. __decorate([
  49923. BABYLON.serialize()
  49924. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49925. __decorate([
  49926. BABYLON.serialize()
  49927. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49928. __decorate([
  49929. BABYLON.serialize()
  49930. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49931. __decorate([
  49932. BABYLON.serializeAsVector3()
  49933. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49934. __decorate([
  49935. BABYLON.serialize()
  49936. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49937. __decorate([
  49938. BABYLON.serialize()
  49939. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49940. __decorate([
  49941. BABYLON.serialize()
  49942. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49943. __decorate([
  49944. BABYLON.serialize()
  49945. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49946. __decorate([
  49947. BABYLON.serialize()
  49948. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49949. return ArcRotateCamera;
  49950. }(BABYLON.TargetCamera));
  49951. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49952. })(BABYLON || (BABYLON = {}));
  49953. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49954. var BABYLON;
  49955. (function (BABYLON) {
  49956. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49957. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49958. });
  49959. /**
  49960. * The HemisphericLight simulates the ambient environment light,
  49961. * so the passed direction is the light reflection direction, not the incoming direction.
  49962. */
  49963. var HemisphericLight = /** @class */ (function (_super) {
  49964. __extends(HemisphericLight, _super);
  49965. /**
  49966. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49967. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49968. * The HemisphericLight can't cast shadows.
  49969. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49970. * @param name The friendly name of the light
  49971. * @param direction The direction of the light reflection
  49972. * @param scene The scene the light belongs to
  49973. */
  49974. function HemisphericLight(name, direction, scene) {
  49975. var _this = _super.call(this, name, scene) || this;
  49976. /**
  49977. * The groundColor is the light in the opposite direction to the one specified during creation.
  49978. * 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.
  49979. */
  49980. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49981. _this.direction = direction || BABYLON.Vector3.Up();
  49982. return _this;
  49983. }
  49984. HemisphericLight.prototype._buildUniformLayout = function () {
  49985. this._uniformBuffer.addUniform("vLightData", 4);
  49986. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49987. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49988. this._uniformBuffer.addUniform("vLightGround", 3);
  49989. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49990. this._uniformBuffer.addUniform("depthValues", 2);
  49991. this._uniformBuffer.create();
  49992. };
  49993. /**
  49994. * Returns the string "HemisphericLight".
  49995. * @return The class name
  49996. */
  49997. HemisphericLight.prototype.getClassName = function () {
  49998. return "HemisphericLight";
  49999. };
  50000. /**
  50001. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50002. * Returns the updated direction.
  50003. * @param target The target the direction should point to
  50004. * @return The computed direction
  50005. */
  50006. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50007. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50008. return this.direction;
  50009. };
  50010. /**
  50011. * Returns the shadow generator associated to the light.
  50012. * @returns Always null for hemispheric lights because it does not support shadows.
  50013. */
  50014. HemisphericLight.prototype.getShadowGenerator = function () {
  50015. return null;
  50016. };
  50017. /**
  50018. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50019. * @param effect The effect to update
  50020. * @param lightIndex The index of the light in the effect to update
  50021. * @returns The hemispheric light
  50022. */
  50023. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50024. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50025. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50026. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50027. return this;
  50028. };
  50029. /**
  50030. * Computes the world matrix of the node
  50031. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50032. * @param useWasUpdatedFlag defines a reserved property
  50033. * @returns the world matrix
  50034. */
  50035. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50036. if (!this._worldMatrix) {
  50037. this._worldMatrix = BABYLON.Matrix.Identity();
  50038. }
  50039. return this._worldMatrix;
  50040. };
  50041. /**
  50042. * Returns the integer 3.
  50043. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50044. */
  50045. HemisphericLight.prototype.getTypeID = function () {
  50046. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50047. };
  50048. /**
  50049. * Prepares the list of defines specific to the light type.
  50050. * @param defines the list of defines
  50051. * @param lightIndex defines the index of the light for the effect
  50052. */
  50053. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50054. defines["HEMILIGHT" + lightIndex] = true;
  50055. };
  50056. __decorate([
  50057. BABYLON.serializeAsColor3()
  50058. ], HemisphericLight.prototype, "groundColor", void 0);
  50059. __decorate([
  50060. BABYLON.serializeAsVector3()
  50061. ], HemisphericLight.prototype, "direction", void 0);
  50062. return HemisphericLight;
  50063. }(BABYLON.Light));
  50064. BABYLON.HemisphericLight = HemisphericLight;
  50065. })(BABYLON || (BABYLON = {}));
  50066. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50067. var BABYLON;
  50068. (function (BABYLON) {
  50069. /**
  50070. * Base implementation IShadowLight
  50071. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50072. */
  50073. var ShadowLight = /** @class */ (function (_super) {
  50074. __extends(ShadowLight, _super);
  50075. function ShadowLight() {
  50076. var _this = _super !== null && _super.apply(this, arguments) || this;
  50077. _this._needProjectionMatrixCompute = true;
  50078. return _this;
  50079. }
  50080. ShadowLight.prototype._setPosition = function (value) {
  50081. this._position = value;
  50082. };
  50083. Object.defineProperty(ShadowLight.prototype, "position", {
  50084. /**
  50085. * Sets the position the shadow will be casted from. Also use as the light position for both
  50086. * point and spot lights.
  50087. */
  50088. get: function () {
  50089. return this._position;
  50090. },
  50091. /**
  50092. * Sets the position the shadow will be casted from. Also use as the light position for both
  50093. * point and spot lights.
  50094. */
  50095. set: function (value) {
  50096. this._setPosition(value);
  50097. },
  50098. enumerable: true,
  50099. configurable: true
  50100. });
  50101. ShadowLight.prototype._setDirection = function (value) {
  50102. this._direction = value;
  50103. };
  50104. Object.defineProperty(ShadowLight.prototype, "direction", {
  50105. /**
  50106. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50107. * Also use as the light direction on spot and directional lights.
  50108. */
  50109. get: function () {
  50110. return this._direction;
  50111. },
  50112. /**
  50113. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50114. * Also use as the light direction on spot and directional lights.
  50115. */
  50116. set: function (value) {
  50117. this._setDirection(value);
  50118. },
  50119. enumerable: true,
  50120. configurable: true
  50121. });
  50122. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50123. /**
  50124. * Gets the shadow projection clipping minimum z value.
  50125. */
  50126. get: function () {
  50127. return this._shadowMinZ;
  50128. },
  50129. /**
  50130. * Sets the shadow projection clipping minimum z value.
  50131. */
  50132. set: function (value) {
  50133. this._shadowMinZ = value;
  50134. this.forceProjectionMatrixCompute();
  50135. },
  50136. enumerable: true,
  50137. configurable: true
  50138. });
  50139. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50140. /**
  50141. * Sets the shadow projection clipping maximum z value.
  50142. */
  50143. get: function () {
  50144. return this._shadowMaxZ;
  50145. },
  50146. /**
  50147. * Gets the shadow projection clipping maximum z value.
  50148. */
  50149. set: function (value) {
  50150. this._shadowMaxZ = value;
  50151. this.forceProjectionMatrixCompute();
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. /**
  50157. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50158. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50159. */
  50160. ShadowLight.prototype.computeTransformedInformation = function () {
  50161. if (this.parent && this.parent.getWorldMatrix) {
  50162. if (!this.transformedPosition) {
  50163. this.transformedPosition = BABYLON.Vector3.Zero();
  50164. }
  50165. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50166. // In case the direction is present.
  50167. if (this.direction) {
  50168. if (!this.transformedDirection) {
  50169. this.transformedDirection = BABYLON.Vector3.Zero();
  50170. }
  50171. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50172. }
  50173. return true;
  50174. }
  50175. return false;
  50176. };
  50177. /**
  50178. * Return the depth scale used for the shadow map.
  50179. * @returns the depth scale.
  50180. */
  50181. ShadowLight.prototype.getDepthScale = function () {
  50182. return 50.0;
  50183. };
  50184. /**
  50185. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50186. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50187. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50188. */
  50189. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50190. return this.transformedDirection ? this.transformedDirection : this.direction;
  50191. };
  50192. /**
  50193. * Returns the ShadowLight absolute position in the World.
  50194. * @returns the position vector in world space
  50195. */
  50196. ShadowLight.prototype.getAbsolutePosition = function () {
  50197. return this.transformedPosition ? this.transformedPosition : this.position;
  50198. };
  50199. /**
  50200. * Sets the ShadowLight direction toward the passed target.
  50201. * @param target The point tot target in local space
  50202. * @returns the updated ShadowLight direction
  50203. */
  50204. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50205. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50206. return this.direction;
  50207. };
  50208. /**
  50209. * Returns the light rotation in euler definition.
  50210. * @returns the x y z rotation in local space.
  50211. */
  50212. ShadowLight.prototype.getRotation = function () {
  50213. this.direction.normalize();
  50214. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50215. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50216. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50217. };
  50218. /**
  50219. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50220. * @returns true if a cube texture needs to be use
  50221. */
  50222. ShadowLight.prototype.needCube = function () {
  50223. return false;
  50224. };
  50225. /**
  50226. * Detects if the projection matrix requires to be recomputed this frame.
  50227. * @returns true if it requires to be recomputed otherwise, false.
  50228. */
  50229. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50230. return this._needProjectionMatrixCompute;
  50231. };
  50232. /**
  50233. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50234. */
  50235. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50236. this._needProjectionMatrixCompute = true;
  50237. };
  50238. /** @hidden */
  50239. ShadowLight.prototype._initCache = function () {
  50240. _super.prototype._initCache.call(this);
  50241. this._cache.position = BABYLON.Vector3.Zero();
  50242. };
  50243. /** @hidden */
  50244. ShadowLight.prototype._isSynchronized = function () {
  50245. if (!this._cache.position.equals(this.position))
  50246. return false;
  50247. return true;
  50248. };
  50249. /**
  50250. * Computes the world matrix of the node
  50251. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50252. * @returns the world matrix
  50253. */
  50254. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50255. if (!force && this.isSynchronized()) {
  50256. this._currentRenderId = this.getScene().getRenderId();
  50257. return this._worldMatrix;
  50258. }
  50259. this._updateCache();
  50260. this._cache.position.copyFrom(this.position);
  50261. if (!this._worldMatrix) {
  50262. this._worldMatrix = BABYLON.Matrix.Identity();
  50263. }
  50264. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50265. if (this.parent && this.parent.getWorldMatrix) {
  50266. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50267. this._markSyncedWithParent();
  50268. }
  50269. // Cache the determinant
  50270. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50271. return this._worldMatrix;
  50272. };
  50273. /**
  50274. * Gets the minZ used for shadow according to both the scene and the light.
  50275. * @param activeCamera The camera we are returning the min for
  50276. * @returns the depth min z
  50277. */
  50278. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50279. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50280. };
  50281. /**
  50282. * Gets the maxZ used for shadow according to both the scene and the light.
  50283. * @param activeCamera The camera we are returning the max for
  50284. * @returns the depth max z
  50285. */
  50286. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50287. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50288. };
  50289. /**
  50290. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50291. * @param matrix The materix to updated with the projection information
  50292. * @param viewMatrix The transform matrix of the light
  50293. * @param renderList The list of mesh to render in the map
  50294. * @returns The current light
  50295. */
  50296. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50297. if (this.customProjectionMatrixBuilder) {
  50298. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50299. }
  50300. else {
  50301. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50302. }
  50303. return this;
  50304. };
  50305. __decorate([
  50306. BABYLON.serializeAsVector3()
  50307. ], ShadowLight.prototype, "position", null);
  50308. __decorate([
  50309. BABYLON.serializeAsVector3()
  50310. ], ShadowLight.prototype, "direction", null);
  50311. __decorate([
  50312. BABYLON.serialize()
  50313. ], ShadowLight.prototype, "shadowMinZ", null);
  50314. __decorate([
  50315. BABYLON.serialize()
  50316. ], ShadowLight.prototype, "shadowMaxZ", null);
  50317. return ShadowLight;
  50318. }(BABYLON.Light));
  50319. BABYLON.ShadowLight = ShadowLight;
  50320. })(BABYLON || (BABYLON = {}));
  50321. //# sourceMappingURL=babylon.shadowLight.js.map
  50322. var BABYLON;
  50323. (function (BABYLON) {
  50324. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  50325. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  50326. });
  50327. /**
  50328. * A point light is a light defined by an unique point in world space.
  50329. * The light is emitted in every direction from this point.
  50330. * A good example of a point light is a standard light bulb.
  50331. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50332. */
  50333. var PointLight = /** @class */ (function (_super) {
  50334. __extends(PointLight, _super);
  50335. /**
  50336. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50337. * A PointLight emits the light in every direction.
  50338. * It can cast shadows.
  50339. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50340. * ```javascript
  50341. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50342. * ```
  50343. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50344. * @param name The light friendly name
  50345. * @param position The position of the point light in the scene
  50346. * @param scene The scene the lights belongs to
  50347. */
  50348. function PointLight(name, position, scene) {
  50349. var _this = _super.call(this, name, scene) || this;
  50350. _this._shadowAngle = Math.PI / 2;
  50351. _this.position = position;
  50352. return _this;
  50353. }
  50354. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  50355. /**
  50356. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50357. * This specifies what angle the shadow will use to be created.
  50358. *
  50359. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50360. */
  50361. get: function () {
  50362. return this._shadowAngle;
  50363. },
  50364. /**
  50365. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50366. * This specifies what angle the shadow will use to be created.
  50367. *
  50368. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50369. */
  50370. set: function (value) {
  50371. this._shadowAngle = value;
  50372. this.forceProjectionMatrixCompute();
  50373. },
  50374. enumerable: true,
  50375. configurable: true
  50376. });
  50377. Object.defineProperty(PointLight.prototype, "direction", {
  50378. /**
  50379. * Gets the direction if it has been set.
  50380. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50381. */
  50382. get: function () {
  50383. return this._direction;
  50384. },
  50385. /**
  50386. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50387. */
  50388. set: function (value) {
  50389. var previousNeedCube = this.needCube();
  50390. this._direction = value;
  50391. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  50392. this._shadowGenerator.recreateShadowMap();
  50393. }
  50394. },
  50395. enumerable: true,
  50396. configurable: true
  50397. });
  50398. /**
  50399. * Returns the string "PointLight"
  50400. * @returns the class name
  50401. */
  50402. PointLight.prototype.getClassName = function () {
  50403. return "PointLight";
  50404. };
  50405. /**
  50406. * Returns the integer 0.
  50407. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50408. */
  50409. PointLight.prototype.getTypeID = function () {
  50410. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50411. };
  50412. /**
  50413. * Specifies wether or not the shadowmap should be a cube texture.
  50414. * @returns true if the shadowmap needs to be a cube texture.
  50415. */
  50416. PointLight.prototype.needCube = function () {
  50417. return !this.direction;
  50418. };
  50419. /**
  50420. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50421. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50422. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50423. */
  50424. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50425. if (this.direction) {
  50426. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50427. }
  50428. else {
  50429. switch (faceIndex) {
  50430. case 0:
  50431. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50432. case 1:
  50433. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50434. case 2:
  50435. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50436. case 3:
  50437. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50438. case 4:
  50439. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50440. case 5:
  50441. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50442. }
  50443. }
  50444. return BABYLON.Vector3.Zero();
  50445. };
  50446. /**
  50447. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50448. * - fov = PI / 2
  50449. * - aspect ratio : 1.0
  50450. * - z-near and far equal to the active camera minZ and maxZ.
  50451. * Returns the PointLight.
  50452. */
  50453. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50454. var activeCamera = this.getScene().activeCamera;
  50455. if (!activeCamera) {
  50456. return;
  50457. }
  50458. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50459. };
  50460. PointLight.prototype._buildUniformLayout = function () {
  50461. this._uniformBuffer.addUniform("vLightData", 4);
  50462. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50463. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50464. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50465. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50466. this._uniformBuffer.addUniform("depthValues", 2);
  50467. this._uniformBuffer.create();
  50468. };
  50469. /**
  50470. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50471. * @param effect The effect to update
  50472. * @param lightIndex The index of the light in the effect to update
  50473. * @returns The point light
  50474. */
  50475. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50476. if (this.computeTransformedInformation()) {
  50477. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50478. }
  50479. else {
  50480. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50481. }
  50482. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  50483. return this;
  50484. };
  50485. /**
  50486. * Prepares the list of defines specific to the light type.
  50487. * @param defines the list of defines
  50488. * @param lightIndex defines the index of the light for the effect
  50489. */
  50490. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50491. defines["POINTLIGHT" + lightIndex] = true;
  50492. };
  50493. __decorate([
  50494. BABYLON.serialize()
  50495. ], PointLight.prototype, "shadowAngle", null);
  50496. return PointLight;
  50497. }(BABYLON.ShadowLight));
  50498. BABYLON.PointLight = PointLight;
  50499. })(BABYLON || (BABYLON = {}));
  50500. //# sourceMappingURL=babylon.pointLight.js.map
  50501. var BABYLON;
  50502. (function (BABYLON) {
  50503. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50504. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50505. });
  50506. /**
  50507. * A directional light is defined by a direction (what a surprise!).
  50508. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50509. * 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.
  50510. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50511. */
  50512. var DirectionalLight = /** @class */ (function (_super) {
  50513. __extends(DirectionalLight, _super);
  50514. /**
  50515. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50516. * The directional light is emitted from everywhere in the given direction.
  50517. * It can cast shadows.
  50518. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50519. * @param name The friendly name of the light
  50520. * @param direction The direction of the light
  50521. * @param scene The scene the light belongs to
  50522. */
  50523. function DirectionalLight(name, direction, scene) {
  50524. var _this = _super.call(this, name, scene) || this;
  50525. _this._shadowFrustumSize = 0;
  50526. _this._shadowOrthoScale = 0.1;
  50527. /**
  50528. * Automatically compute the projection matrix to best fit (including all the casters)
  50529. * on each frame.
  50530. */
  50531. _this.autoUpdateExtends = true;
  50532. // Cache
  50533. _this._orthoLeft = Number.MAX_VALUE;
  50534. _this._orthoRight = Number.MIN_VALUE;
  50535. _this._orthoTop = Number.MIN_VALUE;
  50536. _this._orthoBottom = Number.MAX_VALUE;
  50537. _this.position = direction.scale(-1.0);
  50538. _this.direction = direction;
  50539. return _this;
  50540. }
  50541. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50542. /**
  50543. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50544. */
  50545. get: function () {
  50546. return this._shadowFrustumSize;
  50547. },
  50548. /**
  50549. * Specifies a fix frustum size for the shadow generation.
  50550. */
  50551. set: function (value) {
  50552. this._shadowFrustumSize = value;
  50553. this.forceProjectionMatrixCompute();
  50554. },
  50555. enumerable: true,
  50556. configurable: true
  50557. });
  50558. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50559. /**
  50560. * Gets the shadow projection scale against the optimal computed one.
  50561. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50562. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50563. */
  50564. get: function () {
  50565. return this._shadowOrthoScale;
  50566. },
  50567. /**
  50568. * Sets the shadow projection scale against the optimal computed one.
  50569. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50570. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50571. */
  50572. set: function (value) {
  50573. this._shadowOrthoScale = value;
  50574. this.forceProjectionMatrixCompute();
  50575. },
  50576. enumerable: true,
  50577. configurable: true
  50578. });
  50579. /**
  50580. * Returns the string "DirectionalLight".
  50581. * @return The class name
  50582. */
  50583. DirectionalLight.prototype.getClassName = function () {
  50584. return "DirectionalLight";
  50585. };
  50586. /**
  50587. * Returns the integer 1.
  50588. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50589. */
  50590. DirectionalLight.prototype.getTypeID = function () {
  50591. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50592. };
  50593. /**
  50594. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50595. * Returns the DirectionalLight Shadow projection matrix.
  50596. */
  50597. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50598. if (this.shadowFrustumSize > 0) {
  50599. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50600. }
  50601. else {
  50602. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50603. }
  50604. };
  50605. /**
  50606. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50607. * Returns the DirectionalLight Shadow projection matrix.
  50608. */
  50609. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50610. var activeCamera = this.getScene().activeCamera;
  50611. if (!activeCamera) {
  50612. return;
  50613. }
  50614. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50615. };
  50616. /**
  50617. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50618. * Returns the DirectionalLight Shadow projection matrix.
  50619. */
  50620. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50621. var activeCamera = this.getScene().activeCamera;
  50622. if (!activeCamera) {
  50623. return;
  50624. }
  50625. // Check extends
  50626. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50627. var tempVector3 = BABYLON.Vector3.Zero();
  50628. this._orthoLeft = Number.MAX_VALUE;
  50629. this._orthoRight = Number.MIN_VALUE;
  50630. this._orthoTop = Number.MIN_VALUE;
  50631. this._orthoBottom = Number.MAX_VALUE;
  50632. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50633. var mesh = renderList[meshIndex];
  50634. if (!mesh) {
  50635. continue;
  50636. }
  50637. var boundingInfo = mesh.getBoundingInfo();
  50638. var boundingBox = boundingInfo.boundingBox;
  50639. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50640. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50641. if (tempVector3.x < this._orthoLeft)
  50642. this._orthoLeft = tempVector3.x;
  50643. if (tempVector3.y < this._orthoBottom)
  50644. this._orthoBottom = tempVector3.y;
  50645. if (tempVector3.x > this._orthoRight)
  50646. this._orthoRight = tempVector3.x;
  50647. if (tempVector3.y > this._orthoTop)
  50648. this._orthoTop = tempVector3.y;
  50649. }
  50650. }
  50651. }
  50652. var xOffset = this._orthoRight - this._orthoLeft;
  50653. var yOffset = this._orthoTop - this._orthoBottom;
  50654. 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);
  50655. };
  50656. DirectionalLight.prototype._buildUniformLayout = function () {
  50657. this._uniformBuffer.addUniform("vLightData", 4);
  50658. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50659. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50660. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50661. this._uniformBuffer.addUniform("depthValues", 2);
  50662. this._uniformBuffer.create();
  50663. };
  50664. /**
  50665. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50666. * @param effect The effect to update
  50667. * @param lightIndex The index of the light in the effect to update
  50668. * @returns The directional light
  50669. */
  50670. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50671. if (this.computeTransformedInformation()) {
  50672. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50673. return this;
  50674. }
  50675. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50676. return this;
  50677. };
  50678. /**
  50679. * Gets the minZ used for shadow according to both the scene and the light.
  50680. *
  50681. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50682. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50683. * @param activeCamera The camera we are returning the min for
  50684. * @returns the depth min z
  50685. */
  50686. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50687. return 1;
  50688. };
  50689. /**
  50690. * Gets the maxZ used for shadow according to both the scene and the light.
  50691. *
  50692. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50693. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50694. * @param activeCamera The camera we are returning the max for
  50695. * @returns the depth max z
  50696. */
  50697. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50698. return 1;
  50699. };
  50700. /**
  50701. * Prepares the list of defines specific to the light type.
  50702. * @param defines the list of defines
  50703. * @param lightIndex defines the index of the light for the effect
  50704. */
  50705. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50706. defines["DIRLIGHT" + lightIndex] = true;
  50707. };
  50708. __decorate([
  50709. BABYLON.serialize()
  50710. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50711. __decorate([
  50712. BABYLON.serialize()
  50713. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50714. __decorate([
  50715. BABYLON.serialize()
  50716. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50717. return DirectionalLight;
  50718. }(BABYLON.ShadowLight));
  50719. BABYLON.DirectionalLight = DirectionalLight;
  50720. })(BABYLON || (BABYLON = {}));
  50721. //# sourceMappingURL=babylon.directionalLight.js.map
  50722. var BABYLON;
  50723. (function (BABYLON) {
  50724. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50725. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50726. });
  50727. /**
  50728. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50729. * These values define a cone of light starting from the position, emitting toward the direction.
  50730. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50731. * and the exponent defines the speed of the decay of the light with distance (reach).
  50732. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50733. */
  50734. var SpotLight = /** @class */ (function (_super) {
  50735. __extends(SpotLight, _super);
  50736. /**
  50737. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50738. * It can cast shadows.
  50739. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50740. * @param name The light friendly name
  50741. * @param position The position of the spot light in the scene
  50742. * @param direction The direction of the light in the scene
  50743. * @param angle The cone angle of the light in Radians
  50744. * @param exponent The light decay speed with the distance from the emission spot
  50745. * @param scene The scene the lights belongs to
  50746. */
  50747. function SpotLight(name, position, direction, angle, exponent, scene) {
  50748. var _this = _super.call(this, name, scene) || this;
  50749. _this._innerAngle = 0;
  50750. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50751. _this._projectionTextureLightNear = 1e-6;
  50752. _this._projectionTextureLightFar = 1000.0;
  50753. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50754. _this._projectionTextureViewLightDirty = true;
  50755. _this._projectionTextureProjectionLightDirty = true;
  50756. _this._projectionTextureDirty = true;
  50757. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50758. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50759. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50760. _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);
  50761. _this.position = position;
  50762. _this.direction = direction;
  50763. _this.angle = angle;
  50764. _this.exponent = exponent;
  50765. return _this;
  50766. }
  50767. Object.defineProperty(SpotLight.prototype, "angle", {
  50768. /**
  50769. * Gets the cone angle of the spot light in Radians.
  50770. */
  50771. get: function () {
  50772. return this._angle;
  50773. },
  50774. /**
  50775. * Sets the cone angle of the spot light in Radians.
  50776. */
  50777. set: function (value) {
  50778. this._angle = value;
  50779. this._cosHalfAngle = Math.cos(value * 0.5);
  50780. this._projectionTextureProjectionLightDirty = true;
  50781. this.forceProjectionMatrixCompute();
  50782. this._computeAngleValues();
  50783. },
  50784. enumerable: true,
  50785. configurable: true
  50786. });
  50787. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50788. /**
  50789. * Only used in gltf falloff mode, this defines the angle where
  50790. * the directional falloff will start before cutting at angle which could be seen
  50791. * as outer angle.
  50792. */
  50793. get: function () {
  50794. return this._innerAngle;
  50795. },
  50796. /**
  50797. * Only used in gltf falloff mode, this defines the angle where
  50798. * the directional falloff will start before cutting at angle which could be seen
  50799. * as outer angle.
  50800. */
  50801. set: function (value) {
  50802. this._innerAngle = value;
  50803. this._computeAngleValues();
  50804. },
  50805. enumerable: true,
  50806. configurable: true
  50807. });
  50808. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50809. /**
  50810. * Allows scaling the angle of the light for shadow generation only.
  50811. */
  50812. get: function () {
  50813. return this._shadowAngleScale;
  50814. },
  50815. /**
  50816. * Allows scaling the angle of the light for shadow generation only.
  50817. */
  50818. set: function (value) {
  50819. this._shadowAngleScale = value;
  50820. this.forceProjectionMatrixCompute();
  50821. },
  50822. enumerable: true,
  50823. configurable: true
  50824. });
  50825. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50826. /**
  50827. * Allows reading the projecton texture
  50828. */
  50829. get: function () {
  50830. return this._projectionTextureMatrix;
  50831. },
  50832. enumerable: true,
  50833. configurable: true
  50834. });
  50835. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50836. /**
  50837. * Gets the near clip of the Spotlight for texture projection.
  50838. */
  50839. get: function () {
  50840. return this._projectionTextureLightNear;
  50841. },
  50842. /**
  50843. * Sets the near clip of the Spotlight for texture projection.
  50844. */
  50845. set: function (value) {
  50846. this._projectionTextureLightNear = value;
  50847. this._projectionTextureProjectionLightDirty = true;
  50848. },
  50849. enumerable: true,
  50850. configurable: true
  50851. });
  50852. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50853. /**
  50854. * Gets the far clip of the Spotlight for texture projection.
  50855. */
  50856. get: function () {
  50857. return this._projectionTextureLightFar;
  50858. },
  50859. /**
  50860. * Sets the far clip of the Spotlight for texture projection.
  50861. */
  50862. set: function (value) {
  50863. this._projectionTextureLightFar = value;
  50864. this._projectionTextureProjectionLightDirty = true;
  50865. },
  50866. enumerable: true,
  50867. configurable: true
  50868. });
  50869. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50870. /**
  50871. * Gets the Up vector of the Spotlight for texture projection.
  50872. */
  50873. get: function () {
  50874. return this._projectionTextureUpDirection;
  50875. },
  50876. /**
  50877. * Sets the Up vector of the Spotlight for texture projection.
  50878. */
  50879. set: function (value) {
  50880. this._projectionTextureUpDirection = value;
  50881. this._projectionTextureProjectionLightDirty = true;
  50882. },
  50883. enumerable: true,
  50884. configurable: true
  50885. });
  50886. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50887. /**
  50888. * Gets the projection texture of the light.
  50889. */
  50890. get: function () {
  50891. return this._projectionTexture;
  50892. },
  50893. /**
  50894. * Sets the projection texture of the light.
  50895. */
  50896. set: function (value) {
  50897. this._projectionTexture = value;
  50898. this._projectionTextureDirty = true;
  50899. },
  50900. enumerable: true,
  50901. configurable: true
  50902. });
  50903. /**
  50904. * Returns the string "SpotLight".
  50905. * @returns the class name
  50906. */
  50907. SpotLight.prototype.getClassName = function () {
  50908. return "SpotLight";
  50909. };
  50910. /**
  50911. * Returns the integer 2.
  50912. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50913. */
  50914. SpotLight.prototype.getTypeID = function () {
  50915. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50916. };
  50917. /**
  50918. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50919. */
  50920. SpotLight.prototype._setDirection = function (value) {
  50921. _super.prototype._setDirection.call(this, value);
  50922. this._projectionTextureViewLightDirty = true;
  50923. };
  50924. /**
  50925. * Overrides the position setter to recompute the projection texture view light Matrix.
  50926. */
  50927. SpotLight.prototype._setPosition = function (value) {
  50928. _super.prototype._setPosition.call(this, value);
  50929. this._projectionTextureViewLightDirty = true;
  50930. };
  50931. /**
  50932. * 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.
  50933. * Returns the SpotLight.
  50934. */
  50935. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50936. var activeCamera = this.getScene().activeCamera;
  50937. if (!activeCamera) {
  50938. return;
  50939. }
  50940. this._shadowAngleScale = this._shadowAngleScale || 1;
  50941. var angle = this._shadowAngleScale * this._angle;
  50942. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50943. };
  50944. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50945. this._projectionTextureViewLightDirty = false;
  50946. this._projectionTextureDirty = true;
  50947. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50948. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50949. };
  50950. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50951. this._projectionTextureProjectionLightDirty = false;
  50952. this._projectionTextureDirty = true;
  50953. var light_far = this.projectionTextureLightFar;
  50954. var light_near = this.projectionTextureLightNear;
  50955. var P = light_far / (light_far - light_near);
  50956. var Q = -P * light_near;
  50957. var S = 1.0 / Math.tan(this._angle / 2.0);
  50958. var A = 1.0;
  50959. 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);
  50960. };
  50961. /**
  50962. * Main function for light texture projection matrix computing.
  50963. */
  50964. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50965. this._projectionTextureDirty = false;
  50966. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50967. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50968. };
  50969. SpotLight.prototype._buildUniformLayout = function () {
  50970. this._uniformBuffer.addUniform("vLightData", 4);
  50971. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50972. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50973. this._uniformBuffer.addUniform("vLightDirection", 3);
  50974. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50975. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50976. this._uniformBuffer.addUniform("depthValues", 2);
  50977. this._uniformBuffer.create();
  50978. };
  50979. SpotLight.prototype._computeAngleValues = function () {
  50980. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50981. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50982. };
  50983. /**
  50984. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50985. * @param effect The effect to update
  50986. * @param lightIndex The index of the light in the effect to update
  50987. * @returns The spot light
  50988. */
  50989. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50990. var normalizeDirection;
  50991. if (this.computeTransformedInformation()) {
  50992. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50993. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50994. }
  50995. else {
  50996. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50997. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50998. }
  50999. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51000. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51001. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51002. if (this._projectionTextureViewLightDirty) {
  51003. this._computeProjectionTextureViewLightMatrix();
  51004. }
  51005. if (this._projectionTextureProjectionLightDirty) {
  51006. this._computeProjectionTextureProjectionLightMatrix();
  51007. }
  51008. if (this._projectionTextureDirty) {
  51009. this._computeProjectionTextureMatrix();
  51010. }
  51011. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51012. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51013. }
  51014. return this;
  51015. };
  51016. /**
  51017. * Disposes the light and the associated resources.
  51018. */
  51019. SpotLight.prototype.dispose = function () {
  51020. _super.prototype.dispose.call(this);
  51021. if (this._projectionTexture) {
  51022. this._projectionTexture.dispose();
  51023. }
  51024. };
  51025. /**
  51026. * Prepares the list of defines specific to the light type.
  51027. * @param defines the list of defines
  51028. * @param lightIndex defines the index of the light for the effect
  51029. */
  51030. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51031. defines["SPOTLIGHT" + lightIndex] = true;
  51032. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51033. };
  51034. __decorate([
  51035. BABYLON.serialize()
  51036. ], SpotLight.prototype, "angle", null);
  51037. __decorate([
  51038. BABYLON.serialize()
  51039. ], SpotLight.prototype, "innerAngle", null);
  51040. __decorate([
  51041. BABYLON.serialize()
  51042. ], SpotLight.prototype, "shadowAngleScale", null);
  51043. __decorate([
  51044. BABYLON.serialize()
  51045. ], SpotLight.prototype, "exponent", void 0);
  51046. __decorate([
  51047. BABYLON.serialize()
  51048. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51049. __decorate([
  51050. BABYLON.serialize()
  51051. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51052. __decorate([
  51053. BABYLON.serialize()
  51054. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51055. __decorate([
  51056. BABYLON.serializeAsTexture("projectedLightTexture")
  51057. ], SpotLight.prototype, "_projectionTexture", void 0);
  51058. return SpotLight;
  51059. }(BABYLON.ShadowLight));
  51060. BABYLON.SpotLight = SpotLight;
  51061. })(BABYLON || (BABYLON = {}));
  51062. //# sourceMappingURL=babylon.spotLight.js.map
  51063. var BABYLON;
  51064. (function (BABYLON) {
  51065. /**
  51066. * Class used to override all child animations of a given target
  51067. */
  51068. var AnimationPropertiesOverride = /** @class */ (function () {
  51069. function AnimationPropertiesOverride() {
  51070. /**
  51071. * Gets or sets a value indicating if animation blending must be used
  51072. */
  51073. this.enableBlending = false;
  51074. /**
  51075. * Gets or sets the blending speed to use when enableBlending is true
  51076. */
  51077. this.blendingSpeed = 0.01;
  51078. /**
  51079. * Gets or sets the default loop mode to use
  51080. */
  51081. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51082. }
  51083. return AnimationPropertiesOverride;
  51084. }());
  51085. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51086. })(BABYLON || (BABYLON = {}));
  51087. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51088. var BABYLON;
  51089. (function (BABYLON) {
  51090. /**
  51091. * Represents the range of an animation
  51092. */
  51093. var AnimationRange = /** @class */ (function () {
  51094. /**
  51095. * Initializes the range of an animation
  51096. * @param name The name of the animation range
  51097. * @param from The starting frame of the animation
  51098. * @param to The ending frame of the animation
  51099. */
  51100. function AnimationRange(
  51101. /**The name of the animation range**/
  51102. name,
  51103. /**The starting frame of the animation */
  51104. from,
  51105. /**The ending frame of the animation*/
  51106. to) {
  51107. this.name = name;
  51108. this.from = from;
  51109. this.to = to;
  51110. }
  51111. /**
  51112. * Makes a copy of the animation range
  51113. * @returns A copy of the animation range
  51114. */
  51115. AnimationRange.prototype.clone = function () {
  51116. return new AnimationRange(this.name, this.from, this.to);
  51117. };
  51118. return AnimationRange;
  51119. }());
  51120. BABYLON.AnimationRange = AnimationRange;
  51121. /**
  51122. * Composed of a frame, and an action function
  51123. */
  51124. var AnimationEvent = /** @class */ (function () {
  51125. /**
  51126. * Initializes the animation event
  51127. * @param frame The frame for which the event is triggered
  51128. * @param action The event to perform when triggered
  51129. * @param onlyOnce Specifies if the event should be triggered only once
  51130. */
  51131. function AnimationEvent(
  51132. /** The frame for which the event is triggered **/
  51133. frame,
  51134. /** The event to perform when triggered **/
  51135. action,
  51136. /** Specifies if the event should be triggered only once**/
  51137. onlyOnce) {
  51138. this.frame = frame;
  51139. this.action = action;
  51140. this.onlyOnce = onlyOnce;
  51141. /**
  51142. * Specifies if the animation event is done
  51143. */
  51144. this.isDone = false;
  51145. }
  51146. /** @hidden */
  51147. AnimationEvent.prototype._clone = function () {
  51148. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51149. };
  51150. return AnimationEvent;
  51151. }());
  51152. BABYLON.AnimationEvent = AnimationEvent;
  51153. /**
  51154. * A cursor which tracks a point on a path
  51155. */
  51156. var PathCursor = /** @class */ (function () {
  51157. /**
  51158. * Initializes the path cursor
  51159. * @param path The path to track
  51160. */
  51161. function PathCursor(path) {
  51162. this.path = path;
  51163. /**
  51164. * Stores path cursor callbacks for when an onchange event is triggered
  51165. */
  51166. this._onchange = new Array();
  51167. /**
  51168. * The value of the path cursor
  51169. */
  51170. this.value = 0;
  51171. /**
  51172. * The animation array of the path cursor
  51173. */
  51174. this.animations = new Array();
  51175. }
  51176. /**
  51177. * Gets the cursor point on the path
  51178. * @returns A point on the path cursor at the cursor location
  51179. */
  51180. PathCursor.prototype.getPoint = function () {
  51181. var point = this.path.getPointAtLengthPosition(this.value);
  51182. return new BABYLON.Vector3(point.x, 0, point.y);
  51183. };
  51184. /**
  51185. * Moves the cursor ahead by the step amount
  51186. * @param step The amount to move the cursor forward
  51187. * @returns This path cursor
  51188. */
  51189. PathCursor.prototype.moveAhead = function (step) {
  51190. if (step === void 0) { step = 0.002; }
  51191. this.move(step);
  51192. return this;
  51193. };
  51194. /**
  51195. * Moves the cursor behind by the step amount
  51196. * @param step The amount to move the cursor back
  51197. * @returns This path cursor
  51198. */
  51199. PathCursor.prototype.moveBack = function (step) {
  51200. if (step === void 0) { step = 0.002; }
  51201. this.move(-step);
  51202. return this;
  51203. };
  51204. /**
  51205. * Moves the cursor by the step amount
  51206. * If the step amount is greater than one, an exception is thrown
  51207. * @param step The amount to move the cursor
  51208. * @returns This path cursor
  51209. */
  51210. PathCursor.prototype.move = function (step) {
  51211. if (Math.abs(step) > 1) {
  51212. throw "step size should be less than 1.";
  51213. }
  51214. this.value += step;
  51215. this.ensureLimits();
  51216. this.raiseOnChange();
  51217. return this;
  51218. };
  51219. /**
  51220. * Ensures that the value is limited between zero and one
  51221. * @returns This path cursor
  51222. */
  51223. PathCursor.prototype.ensureLimits = function () {
  51224. while (this.value > 1) {
  51225. this.value -= 1;
  51226. }
  51227. while (this.value < 0) {
  51228. this.value += 1;
  51229. }
  51230. return this;
  51231. };
  51232. /**
  51233. * Runs onchange callbacks on change (used by the animation engine)
  51234. * @returns This path cursor
  51235. */
  51236. PathCursor.prototype.raiseOnChange = function () {
  51237. var _this = this;
  51238. this._onchange.forEach(function (f) { return f(_this); });
  51239. return this;
  51240. };
  51241. /**
  51242. * Executes a function on change
  51243. * @param f A path cursor onchange callback
  51244. * @returns This path cursor
  51245. */
  51246. PathCursor.prototype.onchange = function (f) {
  51247. this._onchange.push(f);
  51248. return this;
  51249. };
  51250. return PathCursor;
  51251. }());
  51252. BABYLON.PathCursor = PathCursor;
  51253. /**
  51254. * Enum for the animation key frame interpolation type
  51255. */
  51256. var AnimationKeyInterpolation;
  51257. (function (AnimationKeyInterpolation) {
  51258. /**
  51259. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51260. */
  51261. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51262. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51263. /**
  51264. * Class used to store any kind of animation
  51265. */
  51266. var Animation = /** @class */ (function () {
  51267. /**
  51268. * Initializes the animation
  51269. * @param name Name of the animation
  51270. * @param targetProperty Property to animate
  51271. * @param framePerSecond The frames per second of the animation
  51272. * @param dataType The data type of the animation
  51273. * @param loopMode The loop mode of the animation
  51274. * @param enableBlendings Specifies if blending should be enabled
  51275. */
  51276. function Animation(
  51277. /**Name of the animation */
  51278. name,
  51279. /**Property to animate */
  51280. targetProperty,
  51281. /**The frames per second of the animation */
  51282. framePerSecond,
  51283. /**The data type of the animation */
  51284. dataType,
  51285. /**The loop mode of the animation */
  51286. loopMode,
  51287. /**Specifies if blending should be enabled */
  51288. enableBlending) {
  51289. this.name = name;
  51290. this.targetProperty = targetProperty;
  51291. this.framePerSecond = framePerSecond;
  51292. this.dataType = dataType;
  51293. this.loopMode = loopMode;
  51294. this.enableBlending = enableBlending;
  51295. /**
  51296. * @hidden Internal use only
  51297. */
  51298. this._runtimeAnimations = new Array();
  51299. /**
  51300. * The set of event that will be linked to this animation
  51301. */
  51302. this._events = new Array();
  51303. /**
  51304. * Stores the blending speed of the animation
  51305. */
  51306. this.blendingSpeed = 0.01;
  51307. /**
  51308. * Stores the animation ranges for the animation
  51309. */
  51310. this._ranges = {};
  51311. this.targetPropertyPath = targetProperty.split(".");
  51312. this.dataType = dataType;
  51313. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51314. }
  51315. /**
  51316. * @hidden Internal use
  51317. */
  51318. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51319. var dataType = undefined;
  51320. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51321. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51322. }
  51323. else if (from instanceof BABYLON.Quaternion) {
  51324. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  51325. }
  51326. else if (from instanceof BABYLON.Vector3) {
  51327. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  51328. }
  51329. else if (from instanceof BABYLON.Vector2) {
  51330. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  51331. }
  51332. else if (from instanceof BABYLON.Color3) {
  51333. dataType = Animation.ANIMATIONTYPE_COLOR3;
  51334. }
  51335. else if (from instanceof BABYLON.Size) {
  51336. dataType = Animation.ANIMATIONTYPE_SIZE;
  51337. }
  51338. if (dataType == undefined) {
  51339. return null;
  51340. }
  51341. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  51342. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  51343. animation.setKeys(keys);
  51344. if (easingFunction !== undefined) {
  51345. animation.setEasingFunction(easingFunction);
  51346. }
  51347. return animation;
  51348. };
  51349. /**
  51350. * Sets up an animation
  51351. * @param property The property to animate
  51352. * @param animationType The animation type to apply
  51353. * @param framePerSecond The frames per second of the animation
  51354. * @param easingFunction The easing function used in the animation
  51355. * @returns The created animation
  51356. */
  51357. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  51358. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  51359. animation.setEasingFunction(easingFunction);
  51360. return animation;
  51361. };
  51362. /**
  51363. * Create and start an animation on a node
  51364. * @param name defines the name of the global animation that will be run on all nodes
  51365. * @param node defines the root node where the animation will take place
  51366. * @param targetProperty defines property to animate
  51367. * @param framePerSecond defines the number of frame per second yo use
  51368. * @param totalFrame defines the number of frames in total
  51369. * @param from defines the initial value
  51370. * @param to defines the final value
  51371. * @param loopMode defines which loop mode you want to use (off by default)
  51372. * @param easingFunction defines the easing function to use (linear by default)
  51373. * @param onAnimationEnd defines the callback to call when animation end
  51374. * @returns the animatable created for this animation
  51375. */
  51376. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51377. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51378. if (!animation) {
  51379. return null;
  51380. }
  51381. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51382. };
  51383. /**
  51384. * Create and start an animation on a node and its descendants
  51385. * @param name defines the name of the global animation that will be run on all nodes
  51386. * @param node defines the root node where the animation will take place
  51387. * @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
  51388. * @param targetProperty defines property to animate
  51389. * @param framePerSecond defines the number of frame per second to use
  51390. * @param totalFrame defines the number of frames in total
  51391. * @param from defines the initial value
  51392. * @param to defines the final value
  51393. * @param loopMode defines which loop mode you want to use (off by default)
  51394. * @param easingFunction defines the easing function to use (linear by default)
  51395. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  51396. * @returns the list of animatables created for all nodes
  51397. * @example https://www.babylonjs-playground.com/#MH0VLI
  51398. */
  51399. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51400. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51401. if (!animation) {
  51402. return null;
  51403. }
  51404. var scene = node.getScene();
  51405. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51406. };
  51407. /**
  51408. * Creates a new animation, merges it with the existing animations and starts it
  51409. * @param name Name of the animation
  51410. * @param node Node which contains the scene that begins the animations
  51411. * @param targetProperty Specifies which property to animate
  51412. * @param framePerSecond The frames per second of the animation
  51413. * @param totalFrame The total number of frames
  51414. * @param from The frame at the beginning of the animation
  51415. * @param to The frame at the end of the animation
  51416. * @param loopMode Specifies the loop mode of the animation
  51417. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  51418. * @param onAnimationEnd Callback to run once the animation is complete
  51419. * @returns Nullable animation
  51420. */
  51421. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51422. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51423. if (!animation) {
  51424. return null;
  51425. }
  51426. node.animations.push(animation);
  51427. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51428. };
  51429. /**
  51430. * Transition property of an host to the target Value
  51431. * @param property The property to transition
  51432. * @param targetValue The target Value of the property
  51433. * @param host The object where the property to animate belongs
  51434. * @param scene Scene used to run the animation
  51435. * @param frameRate Framerate (in frame/s) to use
  51436. * @param transition The transition type we want to use
  51437. * @param duration The duration of the animation, in milliseconds
  51438. * @param onAnimationEnd Callback trigger at the end of the animation
  51439. * @returns Nullable animation
  51440. */
  51441. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  51442. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  51443. if (duration <= 0) {
  51444. host[property] = targetValue;
  51445. if (onAnimationEnd) {
  51446. onAnimationEnd();
  51447. }
  51448. return null;
  51449. }
  51450. var endFrame = frameRate * (duration / 1000);
  51451. transition.setKeys([{
  51452. frame: 0,
  51453. value: host[property].clone ? host[property].clone() : host[property]
  51454. },
  51455. {
  51456. frame: endFrame,
  51457. value: targetValue
  51458. }]);
  51459. if (!host.animations) {
  51460. host.animations = [];
  51461. }
  51462. host.animations.push(transition);
  51463. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51464. animation.onAnimationEnd = onAnimationEnd;
  51465. return animation;
  51466. };
  51467. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51468. /**
  51469. * Return the array of runtime animations currently using this animation
  51470. */
  51471. get: function () {
  51472. return this._runtimeAnimations;
  51473. },
  51474. enumerable: true,
  51475. configurable: true
  51476. });
  51477. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51478. /**
  51479. * Specifies if any of the runtime animations are currently running
  51480. */
  51481. get: function () {
  51482. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51483. var runtimeAnimation = _a[_i];
  51484. if (!runtimeAnimation.isStopped) {
  51485. return true;
  51486. }
  51487. }
  51488. return false;
  51489. },
  51490. enumerable: true,
  51491. configurable: true
  51492. });
  51493. // Methods
  51494. /**
  51495. * Converts the animation to a string
  51496. * @param fullDetails support for multiple levels of logging within scene loading
  51497. * @returns String form of the animation
  51498. */
  51499. Animation.prototype.toString = function (fullDetails) {
  51500. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51501. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51502. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51503. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51504. if (fullDetails) {
  51505. ret += ", Ranges: {";
  51506. var first = true;
  51507. for (var name in this._ranges) {
  51508. if (first) {
  51509. ret += ", ";
  51510. first = false;
  51511. }
  51512. ret += name;
  51513. }
  51514. ret += "}";
  51515. }
  51516. return ret;
  51517. };
  51518. /**
  51519. * Add an event to this animation
  51520. * @param event Event to add
  51521. */
  51522. Animation.prototype.addEvent = function (event) {
  51523. this._events.push(event);
  51524. };
  51525. /**
  51526. * Remove all events found at the given frame
  51527. * @param frame The frame to remove events from
  51528. */
  51529. Animation.prototype.removeEvents = function (frame) {
  51530. for (var index = 0; index < this._events.length; index++) {
  51531. if (this._events[index].frame === frame) {
  51532. this._events.splice(index, 1);
  51533. index--;
  51534. }
  51535. }
  51536. };
  51537. /**
  51538. * Retrieves all the events from the animation
  51539. * @returns Events from the animation
  51540. */
  51541. Animation.prototype.getEvents = function () {
  51542. return this._events;
  51543. };
  51544. /**
  51545. * Creates an animation range
  51546. * @param name Name of the animation range
  51547. * @param from Starting frame of the animation range
  51548. * @param to Ending frame of the animation
  51549. */
  51550. Animation.prototype.createRange = function (name, from, to) {
  51551. // check name not already in use; could happen for bones after serialized
  51552. if (!this._ranges[name]) {
  51553. this._ranges[name] = new AnimationRange(name, from, to);
  51554. }
  51555. };
  51556. /**
  51557. * Deletes an animation range by name
  51558. * @param name Name of the animation range to delete
  51559. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51560. */
  51561. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51562. if (deleteFrames === void 0) { deleteFrames = true; }
  51563. var range = this._ranges[name];
  51564. if (!range) {
  51565. return;
  51566. }
  51567. if (deleteFrames) {
  51568. var from = range.from;
  51569. var to = range.to;
  51570. // this loop MUST go high to low for multiple splices to work
  51571. for (var key = this._keys.length - 1; key >= 0; key--) {
  51572. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51573. this._keys.splice(key, 1);
  51574. }
  51575. }
  51576. }
  51577. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51578. };
  51579. /**
  51580. * Gets the animation range by name, or null if not defined
  51581. * @param name Name of the animation range
  51582. * @returns Nullable animation range
  51583. */
  51584. Animation.prototype.getRange = function (name) {
  51585. return this._ranges[name];
  51586. };
  51587. /**
  51588. * Gets the key frames from the animation
  51589. * @returns The key frames of the animation
  51590. */
  51591. Animation.prototype.getKeys = function () {
  51592. return this._keys;
  51593. };
  51594. /**
  51595. * Gets the highest frame rate of the animation
  51596. * @returns Highest frame rate of the animation
  51597. */
  51598. Animation.prototype.getHighestFrame = function () {
  51599. var ret = 0;
  51600. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51601. if (ret < this._keys[key].frame) {
  51602. ret = this._keys[key].frame;
  51603. }
  51604. }
  51605. return ret;
  51606. };
  51607. /**
  51608. * Gets the easing function of the animation
  51609. * @returns Easing function of the animation
  51610. */
  51611. Animation.prototype.getEasingFunction = function () {
  51612. return this._easingFunction;
  51613. };
  51614. /**
  51615. * Sets the easing function of the animation
  51616. * @param easingFunction A custom mathematical formula for animation
  51617. */
  51618. Animation.prototype.setEasingFunction = function (easingFunction) {
  51619. this._easingFunction = easingFunction;
  51620. };
  51621. /**
  51622. * Interpolates a scalar linearly
  51623. * @param startValue Start value of the animation curve
  51624. * @param endValue End value of the animation curve
  51625. * @param gradient Scalar amount to interpolate
  51626. * @returns Interpolated scalar value
  51627. */
  51628. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51629. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51630. };
  51631. /**
  51632. * Interpolates a scalar cubically
  51633. * @param startValue Start value of the animation curve
  51634. * @param outTangent End tangent of the animation
  51635. * @param endValue End value of the animation curve
  51636. * @param inTangent Start tangent of the animation curve
  51637. * @param gradient Scalar amount to interpolate
  51638. * @returns Interpolated scalar value
  51639. */
  51640. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51641. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51642. };
  51643. /**
  51644. * Interpolates a quaternion using a spherical linear interpolation
  51645. * @param startValue Start value of the animation curve
  51646. * @param endValue End value of the animation curve
  51647. * @param gradient Scalar amount to interpolate
  51648. * @returns Interpolated quaternion value
  51649. */
  51650. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51651. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51652. };
  51653. /**
  51654. * Interpolates a quaternion cubically
  51655. * @param startValue Start value of the animation curve
  51656. * @param outTangent End tangent of the animation curve
  51657. * @param endValue End value of the animation curve
  51658. * @param inTangent Start tangent of the animation curve
  51659. * @param gradient Scalar amount to interpolate
  51660. * @returns Interpolated quaternion value
  51661. */
  51662. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51663. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51664. };
  51665. /**
  51666. * Interpolates a Vector3 linearl
  51667. * @param startValue Start value of the animation curve
  51668. * @param endValue End value of the animation curve
  51669. * @param gradient Scalar amount to interpolate
  51670. * @returns Interpolated scalar value
  51671. */
  51672. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51673. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51674. };
  51675. /**
  51676. * Interpolates a Vector3 cubically
  51677. * @param startValue Start value of the animation curve
  51678. * @param outTangent End tangent of the animation
  51679. * @param endValue End value of the animation curve
  51680. * @param inTangent Start tangent of the animation curve
  51681. * @param gradient Scalar amount to interpolate
  51682. * @returns InterpolatedVector3 value
  51683. */
  51684. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51685. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51686. };
  51687. /**
  51688. * Interpolates a Vector2 linearly
  51689. * @param startValue Start value of the animation curve
  51690. * @param endValue End value of the animation curve
  51691. * @param gradient Scalar amount to interpolate
  51692. * @returns Interpolated Vector2 value
  51693. */
  51694. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51695. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51696. };
  51697. /**
  51698. * Interpolates a Vector2 cubically
  51699. * @param startValue Start value of the animation curve
  51700. * @param outTangent End tangent of the animation
  51701. * @param endValue End value of the animation curve
  51702. * @param inTangent Start tangent of the animation curve
  51703. * @param gradient Scalar amount to interpolate
  51704. * @returns Interpolated Vector2 value
  51705. */
  51706. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51707. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51708. };
  51709. /**
  51710. * Interpolates a size linearly
  51711. * @param startValue Start value of the animation curve
  51712. * @param endValue End value of the animation curve
  51713. * @param gradient Scalar amount to interpolate
  51714. * @returns Interpolated Size value
  51715. */
  51716. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51717. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51718. };
  51719. /**
  51720. * Interpolates a Color3 linearly
  51721. * @param startValue Start value of the animation curve
  51722. * @param endValue End value of the animation curve
  51723. * @param gradient Scalar amount to interpolate
  51724. * @returns Interpolated Color3 value
  51725. */
  51726. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51727. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51728. };
  51729. /**
  51730. * @hidden Internal use only
  51731. */
  51732. Animation.prototype._getKeyValue = function (value) {
  51733. if (typeof value === "function") {
  51734. return value();
  51735. }
  51736. return value;
  51737. };
  51738. /**
  51739. * @hidden Internal use only
  51740. */
  51741. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51742. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51743. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51744. }
  51745. var keys = this.getKeys();
  51746. // Try to get a hash to find the right key
  51747. 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));
  51748. if (keys[startKeyIndex].frame >= currentFrame) {
  51749. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51750. startKeyIndex--;
  51751. }
  51752. }
  51753. for (var key = startKeyIndex; key < keys.length; key++) {
  51754. var endKey = keys[key + 1];
  51755. if (endKey.frame >= currentFrame) {
  51756. var startKey = keys[key];
  51757. var startValue = this._getKeyValue(startKey.value);
  51758. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51759. return startValue;
  51760. }
  51761. var endValue = this._getKeyValue(endKey.value);
  51762. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51763. var frameDelta = endKey.frame - startKey.frame;
  51764. // gradient : percent of currentFrame between the frame inf and the frame sup
  51765. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51766. // check for easingFunction and correction of gradient
  51767. var easingFunction = this.getEasingFunction();
  51768. if (easingFunction != null) {
  51769. gradient = easingFunction.ease(gradient);
  51770. }
  51771. switch (this.dataType) {
  51772. // Float
  51773. case Animation.ANIMATIONTYPE_FLOAT:
  51774. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51775. switch (loopMode) {
  51776. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51777. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51778. return floatValue;
  51779. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51780. return offsetValue * repeatCount + floatValue;
  51781. }
  51782. break;
  51783. // Quaternion
  51784. case Animation.ANIMATIONTYPE_QUATERNION:
  51785. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51786. switch (loopMode) {
  51787. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51788. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51789. return quatValue;
  51790. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51791. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51792. }
  51793. return quatValue;
  51794. // Vector3
  51795. case Animation.ANIMATIONTYPE_VECTOR3:
  51796. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51797. switch (loopMode) {
  51798. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51799. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51800. return vec3Value;
  51801. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51802. return vec3Value.add(offsetValue.scale(repeatCount));
  51803. }
  51804. // Vector2
  51805. case Animation.ANIMATIONTYPE_VECTOR2:
  51806. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51807. switch (loopMode) {
  51808. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51809. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51810. return vec2Value;
  51811. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51812. return vec2Value.add(offsetValue.scale(repeatCount));
  51813. }
  51814. // Size
  51815. case Animation.ANIMATIONTYPE_SIZE:
  51816. switch (loopMode) {
  51817. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51818. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51819. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51820. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51821. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51822. }
  51823. // Color3
  51824. case Animation.ANIMATIONTYPE_COLOR3:
  51825. switch (loopMode) {
  51826. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51827. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51828. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51829. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51830. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51831. }
  51832. // Matrix
  51833. case Animation.ANIMATIONTYPE_MATRIX:
  51834. switch (loopMode) {
  51835. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51836. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51837. if (Animation.AllowMatricesInterpolation) {
  51838. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51839. }
  51840. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51841. return startValue;
  51842. }
  51843. default:
  51844. break;
  51845. }
  51846. break;
  51847. }
  51848. }
  51849. return this._getKeyValue(keys[keys.length - 1].value);
  51850. };
  51851. /**
  51852. * Defines the function to use to interpolate matrices
  51853. * @param startValue defines the start matrix
  51854. * @param endValue defines the end matrix
  51855. * @param gradient defines the gradient between both matrices
  51856. * @param result defines an optional target matrix where to store the interpolation
  51857. * @returns the interpolated matrix
  51858. */
  51859. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51860. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51861. if (result) {
  51862. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51863. return result;
  51864. }
  51865. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51866. }
  51867. if (result) {
  51868. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51869. return result;
  51870. }
  51871. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51872. };
  51873. /**
  51874. * Makes a copy of the animation
  51875. * @returns Cloned animation
  51876. */
  51877. Animation.prototype.clone = function () {
  51878. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51879. clone.enableBlending = this.enableBlending;
  51880. clone.blendingSpeed = this.blendingSpeed;
  51881. if (this._keys) {
  51882. clone.setKeys(this._keys);
  51883. }
  51884. if (this._ranges) {
  51885. clone._ranges = {};
  51886. for (var name in this._ranges) {
  51887. var range = this._ranges[name];
  51888. if (!range) {
  51889. continue;
  51890. }
  51891. clone._ranges[name] = range.clone();
  51892. }
  51893. }
  51894. return clone;
  51895. };
  51896. /**
  51897. * Sets the key frames of the animation
  51898. * @param values The animation key frames to set
  51899. */
  51900. Animation.prototype.setKeys = function (values) {
  51901. this._keys = values.slice(0);
  51902. };
  51903. /**
  51904. * Serializes the animation to an object
  51905. * @returns Serialized object
  51906. */
  51907. Animation.prototype.serialize = function () {
  51908. var serializationObject = {};
  51909. serializationObject.name = this.name;
  51910. serializationObject.property = this.targetProperty;
  51911. serializationObject.framePerSecond = this.framePerSecond;
  51912. serializationObject.dataType = this.dataType;
  51913. serializationObject.loopBehavior = this.loopMode;
  51914. serializationObject.enableBlending = this.enableBlending;
  51915. serializationObject.blendingSpeed = this.blendingSpeed;
  51916. var dataType = this.dataType;
  51917. serializationObject.keys = [];
  51918. var keys = this.getKeys();
  51919. for (var index = 0; index < keys.length; index++) {
  51920. var animationKey = keys[index];
  51921. var key = {};
  51922. key.frame = animationKey.frame;
  51923. switch (dataType) {
  51924. case Animation.ANIMATIONTYPE_FLOAT:
  51925. key.values = [animationKey.value];
  51926. break;
  51927. case Animation.ANIMATIONTYPE_QUATERNION:
  51928. case Animation.ANIMATIONTYPE_MATRIX:
  51929. case Animation.ANIMATIONTYPE_VECTOR3:
  51930. case Animation.ANIMATIONTYPE_COLOR3:
  51931. key.values = animationKey.value.asArray();
  51932. break;
  51933. }
  51934. serializationObject.keys.push(key);
  51935. }
  51936. serializationObject.ranges = [];
  51937. for (var name in this._ranges) {
  51938. var source = this._ranges[name];
  51939. if (!source) {
  51940. continue;
  51941. }
  51942. var range = {};
  51943. range.name = name;
  51944. range.from = source.from;
  51945. range.to = source.to;
  51946. serializationObject.ranges.push(range);
  51947. }
  51948. return serializationObject;
  51949. };
  51950. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51951. /**
  51952. * Get the float animation type
  51953. */
  51954. get: function () {
  51955. return Animation._ANIMATIONTYPE_FLOAT;
  51956. },
  51957. enumerable: true,
  51958. configurable: true
  51959. });
  51960. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51961. /**
  51962. * Get the Vector3 animation type
  51963. */
  51964. get: function () {
  51965. return Animation._ANIMATIONTYPE_VECTOR3;
  51966. },
  51967. enumerable: true,
  51968. configurable: true
  51969. });
  51970. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51971. /**
  51972. * Get the Vector2 animation type
  51973. */
  51974. get: function () {
  51975. return Animation._ANIMATIONTYPE_VECTOR2;
  51976. },
  51977. enumerable: true,
  51978. configurable: true
  51979. });
  51980. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51981. /**
  51982. * Get the Size animation type
  51983. */
  51984. get: function () {
  51985. return Animation._ANIMATIONTYPE_SIZE;
  51986. },
  51987. enumerable: true,
  51988. configurable: true
  51989. });
  51990. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51991. /**
  51992. * Get the Quaternion animation type
  51993. */
  51994. get: function () {
  51995. return Animation._ANIMATIONTYPE_QUATERNION;
  51996. },
  51997. enumerable: true,
  51998. configurable: true
  51999. });
  52000. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52001. /**
  52002. * Get the Matrix animation type
  52003. */
  52004. get: function () {
  52005. return Animation._ANIMATIONTYPE_MATRIX;
  52006. },
  52007. enumerable: true,
  52008. configurable: true
  52009. });
  52010. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52011. /**
  52012. * Get the Color3 animation type
  52013. */
  52014. get: function () {
  52015. return Animation._ANIMATIONTYPE_COLOR3;
  52016. },
  52017. enumerable: true,
  52018. configurable: true
  52019. });
  52020. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52021. /**
  52022. * Get the Relative Loop Mode
  52023. */
  52024. get: function () {
  52025. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52026. },
  52027. enumerable: true,
  52028. configurable: true
  52029. });
  52030. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52031. /**
  52032. * Get the Cycle Loop Mode
  52033. */
  52034. get: function () {
  52035. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52036. },
  52037. enumerable: true,
  52038. configurable: true
  52039. });
  52040. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52041. /**
  52042. * Get the Constant Loop Mode
  52043. */
  52044. get: function () {
  52045. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52046. },
  52047. enumerable: true,
  52048. configurable: true
  52049. });
  52050. /** @hidden */
  52051. Animation._UniversalLerp = function (left, right, amount) {
  52052. var constructor = left.constructor;
  52053. if (constructor.Lerp) { // Lerp supported
  52054. return constructor.Lerp(left, right, amount);
  52055. }
  52056. else if (constructor.Slerp) { // Slerp supported
  52057. return constructor.Slerp(left, right, amount);
  52058. }
  52059. else if (left.toFixed) { // Number
  52060. return left * (1.0 - amount) + amount * right;
  52061. }
  52062. else { // Blending not supported
  52063. return right;
  52064. }
  52065. };
  52066. /**
  52067. * Parses an animation object and creates an animation
  52068. * @param parsedAnimation Parsed animation object
  52069. * @returns Animation object
  52070. */
  52071. Animation.Parse = function (parsedAnimation) {
  52072. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52073. var dataType = parsedAnimation.dataType;
  52074. var keys = [];
  52075. var data;
  52076. var index;
  52077. if (parsedAnimation.enableBlending) {
  52078. animation.enableBlending = parsedAnimation.enableBlending;
  52079. }
  52080. if (parsedAnimation.blendingSpeed) {
  52081. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52082. }
  52083. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52084. var key = parsedAnimation.keys[index];
  52085. var inTangent;
  52086. var outTangent;
  52087. switch (dataType) {
  52088. case Animation.ANIMATIONTYPE_FLOAT:
  52089. data = key.values[0];
  52090. if (key.values.length >= 1) {
  52091. inTangent = key.values[1];
  52092. }
  52093. if (key.values.length >= 2) {
  52094. outTangent = key.values[2];
  52095. }
  52096. break;
  52097. case Animation.ANIMATIONTYPE_QUATERNION:
  52098. data = BABYLON.Quaternion.FromArray(key.values);
  52099. if (key.values.length >= 8) {
  52100. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52101. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52102. inTangent = _inTangent;
  52103. }
  52104. }
  52105. if (key.values.length >= 12) {
  52106. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52107. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52108. outTangent = _outTangent;
  52109. }
  52110. }
  52111. break;
  52112. case Animation.ANIMATIONTYPE_MATRIX:
  52113. data = BABYLON.Matrix.FromArray(key.values);
  52114. break;
  52115. case Animation.ANIMATIONTYPE_COLOR3:
  52116. data = BABYLON.Color3.FromArray(key.values);
  52117. break;
  52118. case Animation.ANIMATIONTYPE_VECTOR3:
  52119. default:
  52120. data = BABYLON.Vector3.FromArray(key.values);
  52121. break;
  52122. }
  52123. var keyData = {};
  52124. keyData.frame = key.frame;
  52125. keyData.value = data;
  52126. if (inTangent != undefined) {
  52127. keyData.inTangent = inTangent;
  52128. }
  52129. if (outTangent != undefined) {
  52130. keyData.outTangent = outTangent;
  52131. }
  52132. keys.push(keyData);
  52133. }
  52134. animation.setKeys(keys);
  52135. if (parsedAnimation.ranges) {
  52136. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52137. data = parsedAnimation.ranges[index];
  52138. animation.createRange(data.name, data.from, data.to);
  52139. }
  52140. }
  52141. return animation;
  52142. };
  52143. /**
  52144. * Appends the serialized animations from the source animations
  52145. * @param source Source containing the animations
  52146. * @param destination Target to store the animations
  52147. */
  52148. Animation.AppendSerializedAnimations = function (source, destination) {
  52149. if (source.animations) {
  52150. destination.animations = [];
  52151. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52152. var animation = source.animations[animationIndex];
  52153. destination.animations.push(animation.serialize());
  52154. }
  52155. }
  52156. };
  52157. /**
  52158. * Use matrix interpolation instead of using direct key value when animating matrices
  52159. */
  52160. Animation.AllowMatricesInterpolation = false;
  52161. /**
  52162. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52163. */
  52164. Animation.AllowMatrixDecomposeForInterpolation = true;
  52165. // Statics
  52166. /**
  52167. * Float animation type
  52168. */
  52169. Animation._ANIMATIONTYPE_FLOAT = 0;
  52170. /**
  52171. * Vector3 animation type
  52172. */
  52173. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52174. /**
  52175. * Quaternion animation type
  52176. */
  52177. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52178. /**
  52179. * Matrix animation type
  52180. */
  52181. Animation._ANIMATIONTYPE_MATRIX = 3;
  52182. /**
  52183. * Color3 animation type
  52184. */
  52185. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52186. /**
  52187. * Vector2 animation type
  52188. */
  52189. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52190. /**
  52191. * Size animation type
  52192. */
  52193. Animation._ANIMATIONTYPE_SIZE = 6;
  52194. /**
  52195. * Relative Loop Mode
  52196. */
  52197. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52198. /**
  52199. * Cycle Loop Mode
  52200. */
  52201. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52202. /**
  52203. * Constant Loop Mode
  52204. */
  52205. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52206. return Animation;
  52207. }());
  52208. BABYLON.Animation = Animation;
  52209. })(BABYLON || (BABYLON = {}));
  52210. //# sourceMappingURL=babylon.animation.js.map
  52211. var BABYLON;
  52212. (function (BABYLON) {
  52213. /**
  52214. * This class defines the direct association between an animation and a target
  52215. */
  52216. var TargetedAnimation = /** @class */ (function () {
  52217. function TargetedAnimation() {
  52218. }
  52219. return TargetedAnimation;
  52220. }());
  52221. BABYLON.TargetedAnimation = TargetedAnimation;
  52222. /**
  52223. * Use this class to create coordinated animations on multiple targets
  52224. */
  52225. var AnimationGroup = /** @class */ (function () {
  52226. /**
  52227. * Instantiates a new Animation Group.
  52228. * This helps managing several animations at once.
  52229. * @see http://doc.babylonjs.com/how_to/group
  52230. * @param name Defines the name of the group
  52231. * @param scene Defines the scene the group belongs to
  52232. */
  52233. function AnimationGroup(
  52234. /** The name of the animation group */
  52235. name, scene) {
  52236. if (scene === void 0) { scene = null; }
  52237. this.name = name;
  52238. this._targetedAnimations = new Array();
  52239. this._animatables = new Array();
  52240. this._from = Number.MAX_VALUE;
  52241. this._to = -Number.MAX_VALUE;
  52242. this._speedRatio = 1;
  52243. /**
  52244. * This observable will notify when one animation have ended.
  52245. */
  52246. this.onAnimationEndObservable = new BABYLON.Observable();
  52247. /**
  52248. * This observable will notify when all animations have ended.
  52249. */
  52250. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52251. /**
  52252. * This observable will notify when all animations have paused.
  52253. */
  52254. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52255. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52256. this._scene.animationGroups.push(this);
  52257. }
  52258. Object.defineProperty(AnimationGroup.prototype, "from", {
  52259. /**
  52260. * Gets the first frame
  52261. */
  52262. get: function () {
  52263. return this._from;
  52264. },
  52265. enumerable: true,
  52266. configurable: true
  52267. });
  52268. Object.defineProperty(AnimationGroup.prototype, "to", {
  52269. /**
  52270. * Gets the last frame
  52271. */
  52272. get: function () {
  52273. return this._to;
  52274. },
  52275. enumerable: true,
  52276. configurable: true
  52277. });
  52278. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52279. /**
  52280. * Define if the animations are started
  52281. */
  52282. get: function () {
  52283. return this._isStarted;
  52284. },
  52285. enumerable: true,
  52286. configurable: true
  52287. });
  52288. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52289. /**
  52290. * Gets or sets the speed ratio to use for all animations
  52291. */
  52292. get: function () {
  52293. return this._speedRatio;
  52294. },
  52295. /**
  52296. * Gets or sets the speed ratio to use for all animations
  52297. */
  52298. set: function (value) {
  52299. if (this._speedRatio === value) {
  52300. return;
  52301. }
  52302. this._speedRatio = value;
  52303. for (var index = 0; index < this._animatables.length; index++) {
  52304. var animatable = this._animatables[index];
  52305. animatable.speedRatio = this._speedRatio;
  52306. }
  52307. },
  52308. enumerable: true,
  52309. configurable: true
  52310. });
  52311. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52312. /**
  52313. * Gets the targeted animations for this animation group
  52314. */
  52315. get: function () {
  52316. return this._targetedAnimations;
  52317. },
  52318. enumerable: true,
  52319. configurable: true
  52320. });
  52321. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52322. /**
  52323. * returning the list of animatables controlled by this animation group.
  52324. */
  52325. get: function () {
  52326. return this._animatables;
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. /**
  52332. * Add an animation (with its target) in the group
  52333. * @param animation defines the animation we want to add
  52334. * @param target defines the target of the animation
  52335. * @returns the {BABYLON.TargetedAnimation} object
  52336. */
  52337. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  52338. var targetedAnimation = {
  52339. animation: animation,
  52340. target: target
  52341. };
  52342. var keys = animation.getKeys();
  52343. if (this._from > keys[0].frame) {
  52344. this._from = keys[0].frame;
  52345. }
  52346. if (this._to < keys[keys.length - 1].frame) {
  52347. this._to = keys[keys.length - 1].frame;
  52348. }
  52349. this._targetedAnimations.push(targetedAnimation);
  52350. return targetedAnimation;
  52351. };
  52352. /**
  52353. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  52354. * It can add constant keys at begin or end
  52355. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  52356. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  52357. * @returns the animation group
  52358. */
  52359. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  52360. if (beginFrame === void 0) { beginFrame = null; }
  52361. if (endFrame === void 0) { endFrame = null; }
  52362. if (beginFrame == null)
  52363. beginFrame = this._from;
  52364. if (endFrame == null)
  52365. endFrame = this._to;
  52366. for (var index = 0; index < this._targetedAnimations.length; index++) {
  52367. var targetedAnimation = this._targetedAnimations[index];
  52368. var keys = targetedAnimation.animation.getKeys();
  52369. var startKey = keys[0];
  52370. var endKey = keys[keys.length - 1];
  52371. if (startKey.frame > beginFrame) {
  52372. var newKey = {
  52373. frame: beginFrame,
  52374. value: startKey.value,
  52375. inTangent: startKey.inTangent,
  52376. outTangent: startKey.outTangent,
  52377. interpolation: startKey.interpolation
  52378. };
  52379. keys.splice(0, 0, newKey);
  52380. }
  52381. if (endKey.frame < endFrame) {
  52382. var newKey = {
  52383. frame: endFrame,
  52384. value: endKey.value,
  52385. inTangent: endKey.outTangent,
  52386. outTangent: endKey.outTangent,
  52387. interpolation: endKey.interpolation
  52388. };
  52389. keys.push(newKey);
  52390. }
  52391. }
  52392. this._from = beginFrame;
  52393. this._to = endFrame;
  52394. return this;
  52395. };
  52396. /**
  52397. * Start all animations on given targets
  52398. * @param loop defines if animations must loop
  52399. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  52400. * @param from defines the from key (optional)
  52401. * @param to defines the to key (optional)
  52402. * @returns the current animation group
  52403. */
  52404. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  52405. var _this = this;
  52406. if (loop === void 0) { loop = false; }
  52407. if (speedRatio === void 0) { speedRatio = 1; }
  52408. if (this._isStarted || this._targetedAnimations.length === 0) {
  52409. return this;
  52410. }
  52411. var _loop_1 = function (targetedAnimation) {
  52412. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  52413. animatable.onAnimationEnd = function () {
  52414. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  52415. _this._checkAnimationGroupEnded(animatable);
  52416. };
  52417. this_1._animatables.push(animatable);
  52418. };
  52419. var this_1 = this;
  52420. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  52421. var targetedAnimation = _a[_i];
  52422. _loop_1(targetedAnimation);
  52423. }
  52424. this._speedRatio = speedRatio;
  52425. this._isStarted = true;
  52426. return this;
  52427. };
  52428. /**
  52429. * Pause all animations
  52430. * @returns the animation group
  52431. */
  52432. AnimationGroup.prototype.pause = function () {
  52433. if (!this._isStarted) {
  52434. return this;
  52435. }
  52436. for (var index = 0; index < this._animatables.length; index++) {
  52437. var animatable = this._animatables[index];
  52438. animatable.pause();
  52439. }
  52440. this.onAnimationGroupPauseObservable.notifyObservers(this);
  52441. return this;
  52442. };
  52443. /**
  52444. * Play all animations to initial state
  52445. * This function will start() the animations if they were not started or will restart() them if they were paused
  52446. * @param loop defines if animations must loop
  52447. * @returns the animation group
  52448. */
  52449. AnimationGroup.prototype.play = function (loop) {
  52450. // only if all animatables are ready and exist
  52451. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  52452. if (loop !== undefined) {
  52453. for (var index = 0; index < this._animatables.length; index++) {
  52454. var animatable = this._animatables[index];
  52455. animatable.loopAnimation = loop;
  52456. }
  52457. }
  52458. this.restart();
  52459. }
  52460. else {
  52461. this.stop();
  52462. this.start(loop, this._speedRatio);
  52463. }
  52464. return this;
  52465. };
  52466. /**
  52467. * Reset all animations to initial state
  52468. * @returns the animation group
  52469. */
  52470. AnimationGroup.prototype.reset = function () {
  52471. if (!this._isStarted) {
  52472. return this;
  52473. }
  52474. for (var index = 0; index < this._animatables.length; index++) {
  52475. var animatable = this._animatables[index];
  52476. animatable.reset();
  52477. }
  52478. return this;
  52479. };
  52480. /**
  52481. * Restart animations from key 0
  52482. * @returns the animation group
  52483. */
  52484. AnimationGroup.prototype.restart = function () {
  52485. if (!this._isStarted) {
  52486. return this;
  52487. }
  52488. for (var index = 0; index < this._animatables.length; index++) {
  52489. var animatable = this._animatables[index];
  52490. animatable.restart();
  52491. }
  52492. return this;
  52493. };
  52494. /**
  52495. * Stop all animations
  52496. * @returns the animation group
  52497. */
  52498. AnimationGroup.prototype.stop = function () {
  52499. if (!this._isStarted) {
  52500. return this;
  52501. }
  52502. var list = this._animatables.slice();
  52503. for (var index = 0; index < list.length; index++) {
  52504. list[index].stop();
  52505. }
  52506. this._isStarted = false;
  52507. return this;
  52508. };
  52509. /**
  52510. * Set animation weight for all animatables
  52511. * @param weight defines the weight to use
  52512. * @return the animationGroup
  52513. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52514. */
  52515. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52516. for (var index = 0; index < this._animatables.length; index++) {
  52517. var animatable = this._animatables[index];
  52518. animatable.weight = weight;
  52519. }
  52520. return this;
  52521. };
  52522. /**
  52523. * Synchronize and normalize all animatables with a source animatable
  52524. * @param root defines the root animatable to synchronize with
  52525. * @return the animationGroup
  52526. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52527. */
  52528. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52529. for (var index = 0; index < this._animatables.length; index++) {
  52530. var animatable = this._animatables[index];
  52531. animatable.syncWith(root);
  52532. }
  52533. return this;
  52534. };
  52535. /**
  52536. * Goes to a specific frame in this animation group
  52537. * @param frame the frame number to go to
  52538. * @return the animationGroup
  52539. */
  52540. AnimationGroup.prototype.goToFrame = function (frame) {
  52541. if (!this._isStarted) {
  52542. return this;
  52543. }
  52544. for (var index = 0; index < this._animatables.length; index++) {
  52545. var animatable = this._animatables[index];
  52546. animatable.goToFrame(frame);
  52547. }
  52548. return this;
  52549. };
  52550. /**
  52551. * Dispose all associated resources
  52552. */
  52553. AnimationGroup.prototype.dispose = function () {
  52554. this._targetedAnimations = [];
  52555. this._animatables = [];
  52556. var index = this._scene.animationGroups.indexOf(this);
  52557. if (index > -1) {
  52558. this._scene.animationGroups.splice(index, 1);
  52559. }
  52560. };
  52561. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52562. // animatable should be taken out of the array
  52563. var idx = this._animatables.indexOf(animatable);
  52564. if (idx > -1) {
  52565. this._animatables.splice(idx, 1);
  52566. }
  52567. // all animatables were removed? animation group ended!
  52568. if (this._animatables.length === 0) {
  52569. this._isStarted = false;
  52570. this.onAnimationGroupEndObservable.notifyObservers(this);
  52571. }
  52572. };
  52573. // Statics
  52574. /**
  52575. * Returns a new AnimationGroup object parsed from the source provided.
  52576. * @param parsedAnimationGroup defines the source
  52577. * @param scene defines the scene that will receive the animationGroup
  52578. * @returns a new AnimationGroup
  52579. */
  52580. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52581. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52582. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52583. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52584. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52585. var id = targetedAnimation.targetId;
  52586. var targetNode = scene.getNodeByID(id);
  52587. if (targetNode != null)
  52588. animationGroup.addTargetedAnimation(animation, targetNode);
  52589. }
  52590. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52591. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52592. return animationGroup;
  52593. };
  52594. /**
  52595. * Returns the string "AnimationGroup"
  52596. * @returns "AnimationGroup"
  52597. */
  52598. AnimationGroup.prototype.getClassName = function () {
  52599. return "AnimationGroup";
  52600. };
  52601. /**
  52602. * Creates a detailled string about the object
  52603. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52604. * @returns a string representing the object
  52605. */
  52606. AnimationGroup.prototype.toString = function (fullDetails) {
  52607. var ret = "Name: " + this.name;
  52608. ret += ", type: " + this.getClassName();
  52609. if (fullDetails) {
  52610. ret += ", from: " + this._from;
  52611. ret += ", to: " + this._to;
  52612. ret += ", isStarted: " + this._isStarted;
  52613. ret += ", speedRatio: " + this._speedRatio;
  52614. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52615. ret += ", animatables length: " + this._animatables;
  52616. }
  52617. return ret;
  52618. };
  52619. return AnimationGroup;
  52620. }());
  52621. BABYLON.AnimationGroup = AnimationGroup;
  52622. })(BABYLON || (BABYLON = {}));
  52623. //# sourceMappingURL=babylon.animationGroup.js.map
  52624. var BABYLON;
  52625. (function (BABYLON) {
  52626. // Static values to help the garbage collector
  52627. // Quaternion
  52628. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52629. // Vector3
  52630. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52631. // Vector2
  52632. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52633. // Size
  52634. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52635. // Color3
  52636. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52637. /**
  52638. * Defines a runtime animation
  52639. */
  52640. var RuntimeAnimation = /** @class */ (function () {
  52641. /**
  52642. * Create a new RuntimeAnimation object
  52643. * @param target defines the target of the animation
  52644. * @param animation defines the source animation object
  52645. * @param scene defines the hosting scene
  52646. * @param host defines the initiating Animatable
  52647. */
  52648. function RuntimeAnimation(target, animation, scene, host) {
  52649. var _this = this;
  52650. this._events = new Array();
  52651. /**
  52652. * The current frame of the runtime animation
  52653. */
  52654. this._currentFrame = 0;
  52655. /**
  52656. * The original value of the runtime animation
  52657. */
  52658. this._originalValue = new Array();
  52659. /**
  52660. * The offsets cache of the runtime animation
  52661. */
  52662. this._offsetsCache = {};
  52663. /**
  52664. * The high limits cache of the runtime animation
  52665. */
  52666. this._highLimitsCache = {};
  52667. /**
  52668. * Specifies if the runtime animation has been stopped
  52669. */
  52670. this._stopped = false;
  52671. /**
  52672. * The blending factor of the runtime animation
  52673. */
  52674. this._blendingFactor = 0;
  52675. /**
  52676. * The target path of the runtime animation
  52677. */
  52678. this._targetPath = "";
  52679. /**
  52680. * The weight of the runtime animation
  52681. */
  52682. this._weight = 1.0;
  52683. /**
  52684. * The ratio offset of the runtime animation
  52685. */
  52686. this._ratioOffset = 0;
  52687. /**
  52688. * The previous delay of the runtime animation
  52689. */
  52690. this._previousDelay = 0;
  52691. /**
  52692. * The previous ratio of the runtime animation
  52693. */
  52694. this._previousRatio = 0;
  52695. this._animation = animation;
  52696. this._target = target;
  52697. this._scene = scene;
  52698. this._host = host;
  52699. animation._runtimeAnimations.push(this);
  52700. // Cloning events locally
  52701. var events = animation.getEvents();
  52702. if (events && events.length > 0) {
  52703. events.forEach(function (e) {
  52704. _this._events.push(e._clone());
  52705. });
  52706. }
  52707. }
  52708. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52709. /**
  52710. * Gets the current frame of the runtime animation
  52711. */
  52712. get: function () {
  52713. return this._currentFrame;
  52714. },
  52715. enumerable: true,
  52716. configurable: true
  52717. });
  52718. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52719. /**
  52720. * Gets the weight of the runtime animation
  52721. */
  52722. get: function () {
  52723. return this._weight;
  52724. },
  52725. enumerable: true,
  52726. configurable: true
  52727. });
  52728. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52729. /**
  52730. * Gets the current value of the runtime animation
  52731. */
  52732. get: function () {
  52733. return this._currentValue;
  52734. },
  52735. enumerable: true,
  52736. configurable: true
  52737. });
  52738. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52739. /**
  52740. * Gets the target path of the runtime animation
  52741. */
  52742. get: function () {
  52743. return this._targetPath;
  52744. },
  52745. enumerable: true,
  52746. configurable: true
  52747. });
  52748. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52749. /**
  52750. * Gets the actual target of the runtime animation
  52751. */
  52752. get: function () {
  52753. return this._activeTarget;
  52754. },
  52755. enumerable: true,
  52756. configurable: true
  52757. });
  52758. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52759. /**
  52760. * Gets the animation from the runtime animation
  52761. */
  52762. get: function () {
  52763. return this._animation;
  52764. },
  52765. enumerable: true,
  52766. configurable: true
  52767. });
  52768. /**
  52769. * Resets the runtime animation to the beginning
  52770. * @param restoreOriginal defines whether to restore the target property to the original value
  52771. */
  52772. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52773. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52774. if (restoreOriginal) {
  52775. if (this._target instanceof Array) {
  52776. var index = 0;
  52777. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52778. var target = _a[_i];
  52779. if (this._originalValue[index] !== undefined) {
  52780. this._setValue(target, this._originalValue[index], -1);
  52781. }
  52782. index++;
  52783. }
  52784. }
  52785. else {
  52786. if (this._originalValue[0] !== undefined) {
  52787. this._setValue(this._target, this._originalValue[0], -1);
  52788. }
  52789. }
  52790. }
  52791. this._offsetsCache = {};
  52792. this._highLimitsCache = {};
  52793. this._currentFrame = 0;
  52794. this._blendingFactor = 0;
  52795. this._originalValue = new Array();
  52796. // Events
  52797. for (var index = 0; index < this._events.length; index++) {
  52798. this._events[index].isDone = false;
  52799. }
  52800. };
  52801. /**
  52802. * Specifies if the runtime animation is stopped
  52803. * @returns Boolean specifying if the runtime animation is stopped
  52804. */
  52805. RuntimeAnimation.prototype.isStopped = function () {
  52806. return this._stopped;
  52807. };
  52808. /**
  52809. * Disposes of the runtime animation
  52810. */
  52811. RuntimeAnimation.prototype.dispose = function () {
  52812. var index = this._animation.runtimeAnimations.indexOf(this);
  52813. if (index > -1) {
  52814. this._animation.runtimeAnimations.splice(index, 1);
  52815. }
  52816. };
  52817. /**
  52818. * Interpolates the animation from the current frame
  52819. * @param currentFrame The frame to interpolate the animation to
  52820. * @param repeatCount The number of times that the animation should loop
  52821. * @param loopMode The type of looping mode to use
  52822. * @param offsetValue Animation offset value
  52823. * @param highLimitValue The high limit value
  52824. * @returns The interpolated value
  52825. */
  52826. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52827. this._currentFrame = currentFrame;
  52828. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52829. this._workValue = BABYLON.Matrix.Zero();
  52830. }
  52831. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52832. };
  52833. /**
  52834. * Apply the interpolated value to the target
  52835. * @param currentValue defines the value computed by the animation
  52836. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52837. */
  52838. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52839. if (weight === void 0) { weight = 1.0; }
  52840. if (this._target instanceof Array) {
  52841. var index = 0;
  52842. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52843. var target = _a[_i];
  52844. this._setValue(target, currentValue, weight, index);
  52845. index++;
  52846. }
  52847. }
  52848. else {
  52849. this._setValue(this._target, currentValue, weight);
  52850. }
  52851. };
  52852. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52853. if (targetIndex === void 0) { targetIndex = 0; }
  52854. // Set value
  52855. var path;
  52856. var destination;
  52857. var targetPropertyPath = this._animation.targetPropertyPath;
  52858. if (targetPropertyPath.length > 1) {
  52859. var property = target[targetPropertyPath[0]];
  52860. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52861. property = property[targetPropertyPath[index]];
  52862. }
  52863. path = targetPropertyPath[targetPropertyPath.length - 1];
  52864. destination = property;
  52865. }
  52866. else {
  52867. path = targetPropertyPath[0];
  52868. destination = target;
  52869. }
  52870. this._targetPath = path;
  52871. this._activeTarget = destination;
  52872. this._weight = weight;
  52873. if (this._originalValue[targetIndex] === undefined) {
  52874. var originalValue = void 0;
  52875. if (destination.getRestPose && path === "_matrix") { // For bones
  52876. originalValue = destination.getRestPose();
  52877. }
  52878. else {
  52879. originalValue = destination[path];
  52880. }
  52881. if (originalValue && originalValue.clone) {
  52882. this._originalValue[targetIndex] = originalValue.clone();
  52883. }
  52884. else {
  52885. this._originalValue[targetIndex] = originalValue;
  52886. }
  52887. }
  52888. // Blending
  52889. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52890. if (enableBlending && this._blendingFactor <= 1.0) {
  52891. if (!this._originalBlendValue) {
  52892. var originalValue = destination[path];
  52893. if (originalValue.clone) {
  52894. this._originalBlendValue = originalValue.clone();
  52895. }
  52896. else {
  52897. this._originalBlendValue = originalValue;
  52898. }
  52899. }
  52900. if (this._originalBlendValue.m) { // Matrix
  52901. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52902. if (this._currentValue) {
  52903. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52904. }
  52905. else {
  52906. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52907. }
  52908. }
  52909. else {
  52910. if (this._currentValue) {
  52911. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52912. }
  52913. else {
  52914. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52915. }
  52916. }
  52917. }
  52918. else {
  52919. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52920. }
  52921. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52922. this._blendingFactor += blendingSpeed;
  52923. }
  52924. else {
  52925. this._currentValue = currentValue;
  52926. }
  52927. if (weight !== -1.0) {
  52928. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52929. }
  52930. else {
  52931. destination[path] = this._currentValue;
  52932. }
  52933. if (target.markAsDirty) {
  52934. target.markAsDirty(this._animation.targetProperty);
  52935. }
  52936. };
  52937. /**
  52938. * Gets the loop pmode of the runtime animation
  52939. * @returns Loop Mode
  52940. */
  52941. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52942. if (this._target && this._target.animationPropertiesOverride) {
  52943. return this._target.animationPropertiesOverride.loopMode;
  52944. }
  52945. return this._animation.loopMode;
  52946. };
  52947. /**
  52948. * Move the current animation to a given frame
  52949. * @param frame defines the frame to move to
  52950. */
  52951. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52952. var keys = this._animation.getKeys();
  52953. if (frame < keys[0].frame) {
  52954. frame = keys[0].frame;
  52955. }
  52956. else if (frame > keys[keys.length - 1].frame) {
  52957. frame = keys[keys.length - 1].frame;
  52958. }
  52959. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52960. this.setValue(currentValue, -1);
  52961. };
  52962. /**
  52963. * @hidden Internal use only
  52964. */
  52965. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52966. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52967. this._ratioOffset = this._previousRatio - newRatio;
  52968. };
  52969. /**
  52970. * Execute the current animation
  52971. * @param delay defines the delay to add to the current frame
  52972. * @param from defines the lower bound of the animation range
  52973. * @param to defines the upper bound of the animation range
  52974. * @param loop defines if the current animation must loop
  52975. * @param speedRatio defines the current speed ratio
  52976. * @param weight defines the weight of the animation (default is -1 so no weight)
  52977. * @returns a boolean indicating if the animation is running
  52978. */
  52979. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52980. if (weight === void 0) { weight = -1.0; }
  52981. var targetPropertyPath = this._animation.targetPropertyPath;
  52982. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52983. this._stopped = true;
  52984. return false;
  52985. }
  52986. var returnValue = true;
  52987. var keys = this._animation.getKeys();
  52988. // Adding a start key at frame 0 if missing
  52989. if (keys[0].frame !== 0) {
  52990. var newKey = { frame: 0, value: keys[0].value };
  52991. keys.splice(0, 0, newKey);
  52992. }
  52993. // Adding a duplicate key when there is only one key at frame zero
  52994. else if (keys.length === 1) {
  52995. var newKey = { frame: 0.001, value: keys[0].value };
  52996. keys.push(newKey);
  52997. }
  52998. // Check limits
  52999. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53000. from = keys[0].frame;
  53001. }
  53002. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53003. to = keys[keys.length - 1].frame;
  53004. }
  53005. //to and from cannot be the same key
  53006. if (from === to) {
  53007. if (from > keys[0].frame) {
  53008. from--;
  53009. }
  53010. else if (to < keys[keys.length - 1].frame) {
  53011. to++;
  53012. }
  53013. }
  53014. // Compute ratio
  53015. var range = to - from;
  53016. var offsetValue;
  53017. // ratio represents the frame delta between from and to
  53018. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53019. var highLimitValue = 0;
  53020. this._previousDelay = delay;
  53021. this._previousRatio = ratio;
  53022. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53023. returnValue = false;
  53024. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53025. }
  53026. else {
  53027. // Get max value if required
  53028. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53029. var keyOffset = to.toString() + from.toString();
  53030. if (!this._offsetsCache[keyOffset]) {
  53031. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53032. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53033. switch (this._animation.dataType) {
  53034. // Float
  53035. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53036. this._offsetsCache[keyOffset] = toValue - fromValue;
  53037. break;
  53038. // Quaternion
  53039. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53040. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53041. break;
  53042. // Vector3
  53043. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53044. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53045. // Vector2
  53046. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53047. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53048. // Size
  53049. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53050. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53051. // Color3
  53052. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53053. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53054. default:
  53055. break;
  53056. }
  53057. this._highLimitsCache[keyOffset] = toValue;
  53058. }
  53059. highLimitValue = this._highLimitsCache[keyOffset];
  53060. offsetValue = this._offsetsCache[keyOffset];
  53061. }
  53062. }
  53063. if (offsetValue === undefined) {
  53064. switch (this._animation.dataType) {
  53065. // Float
  53066. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53067. offsetValue = 0;
  53068. break;
  53069. // Quaternion
  53070. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53071. offsetValue = _staticOffsetValueQuaternion;
  53072. break;
  53073. // Vector3
  53074. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53075. offsetValue = _staticOffsetValueVector3;
  53076. break;
  53077. // Vector2
  53078. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53079. offsetValue = _staticOffsetValueVector2;
  53080. break;
  53081. // Size
  53082. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53083. offsetValue = _staticOffsetValueSize;
  53084. break;
  53085. // Color3
  53086. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53087. offsetValue = _staticOffsetValueColor3;
  53088. }
  53089. }
  53090. // Compute value
  53091. var repeatCount = (ratio / range) >> 0;
  53092. var currentFrame = returnValue ? from + ratio % range : to;
  53093. // Need to normalize?
  53094. if (this._host && this._host.syncRoot) {
  53095. var syncRoot = this._host.syncRoot;
  53096. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53097. currentFrame = from + (to - from) * hostNormalizedFrame;
  53098. }
  53099. // Reset events if looping
  53100. var events = this._events;
  53101. if (range > 0 && this.currentFrame > currentFrame ||
  53102. range < 0 && this.currentFrame < currentFrame) {
  53103. // Need to reset animation events
  53104. for (var index = 0; index < events.length; index++) {
  53105. if (!events[index].onlyOnce) {
  53106. // reset event, the animation is looping
  53107. events[index].isDone = false;
  53108. }
  53109. }
  53110. }
  53111. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53112. // Set value
  53113. this.setValue(currentValue, weight);
  53114. // Check events
  53115. for (var index = 0; index < events.length; index++) {
  53116. // Make sure current frame has passed event frame and that event frame is within the current range
  53117. // Also, handle both forward and reverse animations
  53118. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53119. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53120. var event = events[index];
  53121. if (!event.isDone) {
  53122. // If event should be done only once, remove it.
  53123. if (event.onlyOnce) {
  53124. events.splice(index, 1);
  53125. index--;
  53126. }
  53127. event.isDone = true;
  53128. event.action(currentFrame);
  53129. } // Don't do anything if the event has already be done.
  53130. }
  53131. }
  53132. if (!returnValue) {
  53133. this._stopped = true;
  53134. }
  53135. return returnValue;
  53136. };
  53137. return RuntimeAnimation;
  53138. }());
  53139. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53140. })(BABYLON || (BABYLON = {}));
  53141. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53142. var BABYLON;
  53143. (function (BABYLON) {
  53144. /**
  53145. * Class used to store an actual running animation
  53146. */
  53147. var Animatable = /** @class */ (function () {
  53148. /**
  53149. * Creates a new Animatable
  53150. * @param scene defines the hosting scene
  53151. * @param target defines the target object
  53152. * @param fromFrame defines the starting frame number (default is 0)
  53153. * @param toFrame defines the ending frame number (default is 100)
  53154. * @param loopAnimation defines if the animation must loop (default is false)
  53155. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53156. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53157. * @param animations defines a group of animation to add to the new Animatable
  53158. */
  53159. function Animatable(scene,
  53160. /** defines the target object */
  53161. target,
  53162. /** defines the starting frame number (default is 0) */
  53163. fromFrame,
  53164. /** defines the ending frame number (default is 100) */
  53165. toFrame,
  53166. /** defines if the animation must loop (default is false) */
  53167. loopAnimation, speedRatio,
  53168. /** defines a callback to call when animation ends if it is not looping */
  53169. onAnimationEnd, animations) {
  53170. if (fromFrame === void 0) { fromFrame = 0; }
  53171. if (toFrame === void 0) { toFrame = 100; }
  53172. if (loopAnimation === void 0) { loopAnimation = false; }
  53173. if (speedRatio === void 0) { speedRatio = 1.0; }
  53174. this.target = target;
  53175. this.fromFrame = fromFrame;
  53176. this.toFrame = toFrame;
  53177. this.loopAnimation = loopAnimation;
  53178. this.onAnimationEnd = onAnimationEnd;
  53179. this._localDelayOffset = null;
  53180. this._pausedDelay = null;
  53181. this._runtimeAnimations = new Array();
  53182. this._paused = false;
  53183. this._speedRatio = 1;
  53184. this._weight = -1.0;
  53185. /**
  53186. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53187. * This will only apply for non looping animation (default is true)
  53188. */
  53189. this.disposeOnEnd = true;
  53190. /**
  53191. * Gets a boolean indicating if the animation has started
  53192. */
  53193. this.animationStarted = false;
  53194. /**
  53195. * Observer raised when the animation ends
  53196. */
  53197. this.onAnimationEndObservable = new BABYLON.Observable();
  53198. this._scene = scene;
  53199. if (animations) {
  53200. this.appendAnimations(target, animations);
  53201. }
  53202. this._speedRatio = speedRatio;
  53203. scene._activeAnimatables.push(this);
  53204. }
  53205. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53206. /**
  53207. * Gets the root Animatable used to synchronize and normalize animations
  53208. */
  53209. get: function () {
  53210. return this._syncRoot;
  53211. },
  53212. enumerable: true,
  53213. configurable: true
  53214. });
  53215. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53216. /**
  53217. * Gets the current frame of the first RuntimeAnimation
  53218. * Used to synchronize Animatables
  53219. */
  53220. get: function () {
  53221. if (this._runtimeAnimations.length === 0) {
  53222. return 0;
  53223. }
  53224. return this._runtimeAnimations[0].currentFrame;
  53225. },
  53226. enumerable: true,
  53227. configurable: true
  53228. });
  53229. Object.defineProperty(Animatable.prototype, "weight", {
  53230. /**
  53231. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53232. */
  53233. get: function () {
  53234. return this._weight;
  53235. },
  53236. set: function (value) {
  53237. if (value === -1) { // -1 is ok and means no weight
  53238. this._weight = -1;
  53239. return;
  53240. }
  53241. // Else weight must be in [0, 1] range
  53242. this._weight = Math.min(Math.max(value, 0), 1.0);
  53243. },
  53244. enumerable: true,
  53245. configurable: true
  53246. });
  53247. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53248. /**
  53249. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53250. */
  53251. get: function () {
  53252. return this._speedRatio;
  53253. },
  53254. set: function (value) {
  53255. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53256. var animation = this._runtimeAnimations[index];
  53257. animation._prepareForSpeedRatioChange(value);
  53258. }
  53259. this._speedRatio = value;
  53260. },
  53261. enumerable: true,
  53262. configurable: true
  53263. });
  53264. // Methods
  53265. /**
  53266. * Synchronize and normalize current Animatable with a source Animatable
  53267. * This is useful when using animation weights and when animations are not of the same length
  53268. * @param root defines the root Animatable to synchronize with
  53269. * @returns the current Animatable
  53270. */
  53271. Animatable.prototype.syncWith = function (root) {
  53272. this._syncRoot = root;
  53273. if (root) {
  53274. // Make sure this animatable will animate after the root
  53275. var index = this._scene._activeAnimatables.indexOf(this);
  53276. if (index > -1) {
  53277. this._scene._activeAnimatables.splice(index, 1);
  53278. this._scene._activeAnimatables.push(this);
  53279. }
  53280. }
  53281. return this;
  53282. };
  53283. /**
  53284. * Gets the list of runtime animations
  53285. * @returns an array of RuntimeAnimation
  53286. */
  53287. Animatable.prototype.getAnimations = function () {
  53288. return this._runtimeAnimations;
  53289. };
  53290. /**
  53291. * Adds more animations to the current animatable
  53292. * @param target defines the target of the animations
  53293. * @param animations defines the new animations to add
  53294. */
  53295. Animatable.prototype.appendAnimations = function (target, animations) {
  53296. for (var index = 0; index < animations.length; index++) {
  53297. var animation = animations[index];
  53298. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53299. }
  53300. };
  53301. /**
  53302. * Gets the source animation for a specific property
  53303. * @param property defines the propertyu to look for
  53304. * @returns null or the source animation for the given property
  53305. */
  53306. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53307. var runtimeAnimations = this._runtimeAnimations;
  53308. for (var index = 0; index < runtimeAnimations.length; index++) {
  53309. if (runtimeAnimations[index].animation.targetProperty === property) {
  53310. return runtimeAnimations[index].animation;
  53311. }
  53312. }
  53313. return null;
  53314. };
  53315. /**
  53316. * Gets the runtime animation for a specific property
  53317. * @param property defines the propertyu to look for
  53318. * @returns null or the runtime animation for the given property
  53319. */
  53320. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53321. var runtimeAnimations = this._runtimeAnimations;
  53322. for (var index = 0; index < runtimeAnimations.length; index++) {
  53323. if (runtimeAnimations[index].animation.targetProperty === property) {
  53324. return runtimeAnimations[index];
  53325. }
  53326. }
  53327. return null;
  53328. };
  53329. /**
  53330. * Resets the animatable to its original state
  53331. */
  53332. Animatable.prototype.reset = function () {
  53333. var runtimeAnimations = this._runtimeAnimations;
  53334. for (var index = 0; index < runtimeAnimations.length; index++) {
  53335. runtimeAnimations[index].reset(true);
  53336. }
  53337. this._localDelayOffset = null;
  53338. this._pausedDelay = null;
  53339. };
  53340. /**
  53341. * Allows the animatable to blend with current running animations
  53342. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53343. * @param blendingSpeed defines the blending speed to use
  53344. */
  53345. Animatable.prototype.enableBlending = function (blendingSpeed) {
  53346. var runtimeAnimations = this._runtimeAnimations;
  53347. for (var index = 0; index < runtimeAnimations.length; index++) {
  53348. runtimeAnimations[index].animation.enableBlending = true;
  53349. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  53350. }
  53351. };
  53352. /**
  53353. * Disable animation blending
  53354. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53355. */
  53356. Animatable.prototype.disableBlending = function () {
  53357. var runtimeAnimations = this._runtimeAnimations;
  53358. for (var index = 0; index < runtimeAnimations.length; index++) {
  53359. runtimeAnimations[index].animation.enableBlending = false;
  53360. }
  53361. };
  53362. /**
  53363. * Jump directly to a given frame
  53364. * @param frame defines the frame to jump to
  53365. */
  53366. Animatable.prototype.goToFrame = function (frame) {
  53367. var runtimeAnimations = this._runtimeAnimations;
  53368. if (runtimeAnimations[0]) {
  53369. var fps = runtimeAnimations[0].animation.framePerSecond;
  53370. var currentFrame = runtimeAnimations[0].currentFrame;
  53371. var adjustTime = frame - currentFrame;
  53372. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  53373. if (this._localDelayOffset === null) {
  53374. this._localDelayOffset = 0;
  53375. }
  53376. this._localDelayOffset -= delay;
  53377. }
  53378. for (var index = 0; index < runtimeAnimations.length; index++) {
  53379. runtimeAnimations[index].goToFrame(frame);
  53380. }
  53381. };
  53382. /**
  53383. * Pause the animation
  53384. */
  53385. Animatable.prototype.pause = function () {
  53386. if (this._paused) {
  53387. return;
  53388. }
  53389. this._paused = true;
  53390. };
  53391. /**
  53392. * Restart the animation
  53393. */
  53394. Animatable.prototype.restart = function () {
  53395. this._paused = false;
  53396. };
  53397. Animatable.prototype._raiseOnAnimationEnd = function () {
  53398. if (this.onAnimationEnd) {
  53399. this.onAnimationEnd();
  53400. }
  53401. this.onAnimationEndObservable.notifyObservers(this);
  53402. };
  53403. /**
  53404. * Stop and delete the current animation
  53405. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  53406. * @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)
  53407. */
  53408. Animatable.prototype.stop = function (animationName, targetMask) {
  53409. if (animationName || targetMask) {
  53410. var idx = this._scene._activeAnimatables.indexOf(this);
  53411. if (idx > -1) {
  53412. var runtimeAnimations = this._runtimeAnimations;
  53413. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  53414. var runtimeAnimation = runtimeAnimations[index];
  53415. if (animationName && runtimeAnimation.animation.name != animationName) {
  53416. continue;
  53417. }
  53418. if (targetMask && !targetMask(runtimeAnimation.target)) {
  53419. continue;
  53420. }
  53421. runtimeAnimation.dispose();
  53422. runtimeAnimations.splice(index, 1);
  53423. }
  53424. if (runtimeAnimations.length == 0) {
  53425. this._scene._activeAnimatables.splice(idx, 1);
  53426. this._raiseOnAnimationEnd();
  53427. }
  53428. }
  53429. }
  53430. else {
  53431. var index = this._scene._activeAnimatables.indexOf(this);
  53432. if (index > -1) {
  53433. this._scene._activeAnimatables.splice(index, 1);
  53434. var runtimeAnimations = this._runtimeAnimations;
  53435. for (var index = 0; index < runtimeAnimations.length; index++) {
  53436. runtimeAnimations[index].dispose();
  53437. }
  53438. this._raiseOnAnimationEnd();
  53439. }
  53440. }
  53441. };
  53442. /**
  53443. * Wait asynchronously for the animation to end
  53444. * @returns a promise which will be fullfilled when the animation ends
  53445. */
  53446. Animatable.prototype.waitAsync = function () {
  53447. var _this = this;
  53448. return new Promise(function (resolve, reject) {
  53449. _this.onAnimationEndObservable.add(function () {
  53450. resolve(_this);
  53451. }, undefined, undefined, _this, true);
  53452. });
  53453. };
  53454. /** @hidden */
  53455. Animatable.prototype._animate = function (delay) {
  53456. if (this._paused) {
  53457. this.animationStarted = false;
  53458. if (this._pausedDelay === null) {
  53459. this._pausedDelay = delay;
  53460. }
  53461. return true;
  53462. }
  53463. if (this._localDelayOffset === null) {
  53464. this._localDelayOffset = delay;
  53465. this._pausedDelay = null;
  53466. }
  53467. else if (this._pausedDelay !== null) {
  53468. this._localDelayOffset += delay - this._pausedDelay;
  53469. this._pausedDelay = null;
  53470. }
  53471. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  53472. return true;
  53473. }
  53474. // Animating
  53475. var running = false;
  53476. var runtimeAnimations = this._runtimeAnimations;
  53477. var index;
  53478. for (index = 0; index < runtimeAnimations.length; index++) {
  53479. var animation = runtimeAnimations[index];
  53480. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  53481. running = running || isRunning;
  53482. }
  53483. this.animationStarted = running;
  53484. if (!running) {
  53485. if (this.disposeOnEnd) {
  53486. // Remove from active animatables
  53487. index = this._scene._activeAnimatables.indexOf(this);
  53488. this._scene._activeAnimatables.splice(index, 1);
  53489. // Dispose all runtime animations
  53490. for (index = 0; index < runtimeAnimations.length; index++) {
  53491. runtimeAnimations[index].dispose();
  53492. }
  53493. }
  53494. this._raiseOnAnimationEnd();
  53495. if (this.disposeOnEnd) {
  53496. this.onAnimationEnd = null;
  53497. this.onAnimationEndObservable.clear();
  53498. }
  53499. }
  53500. return running;
  53501. };
  53502. return Animatable;
  53503. }());
  53504. BABYLON.Animatable = Animatable;
  53505. })(BABYLON || (BABYLON = {}));
  53506. //# sourceMappingURL=babylon.animatable.js.map
  53507. var BABYLON;
  53508. (function (BABYLON) {
  53509. /**
  53510. * Base class used for every default easing function.
  53511. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53512. */
  53513. var EasingFunction = /** @class */ (function () {
  53514. function EasingFunction() {
  53515. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53516. }
  53517. /**
  53518. * Sets the easing mode of the current function.
  53519. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53520. */
  53521. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53522. var n = Math.min(Math.max(easingMode, 0), 2);
  53523. this._easingMode = n;
  53524. };
  53525. /**
  53526. * Gets the current easing mode.
  53527. * @returns the easing mode
  53528. */
  53529. EasingFunction.prototype.getEasingMode = function () {
  53530. return this._easingMode;
  53531. };
  53532. /**
  53533. * @hidden
  53534. */
  53535. EasingFunction.prototype.easeInCore = function (gradient) {
  53536. throw new Error('You must implement this method');
  53537. };
  53538. /**
  53539. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53540. * of the easing function.
  53541. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53542. * @returns the corresponding value on the curve defined by the easing function
  53543. */
  53544. EasingFunction.prototype.ease = function (gradient) {
  53545. switch (this._easingMode) {
  53546. case EasingFunction.EASINGMODE_EASEIN:
  53547. return this.easeInCore(gradient);
  53548. case EasingFunction.EASINGMODE_EASEOUT:
  53549. return (1 - this.easeInCore(1 - gradient));
  53550. }
  53551. if (gradient >= 0.5) {
  53552. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53553. }
  53554. return (this.easeInCore(gradient * 2) * 0.5);
  53555. };
  53556. /**
  53557. * Interpolation follows the mathematical formula associated with the easing function.
  53558. */
  53559. EasingFunction.EASINGMODE_EASEIN = 0;
  53560. /**
  53561. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53562. */
  53563. EasingFunction.EASINGMODE_EASEOUT = 1;
  53564. /**
  53565. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53566. */
  53567. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53568. return EasingFunction;
  53569. }());
  53570. BABYLON.EasingFunction = EasingFunction;
  53571. /**
  53572. * Easing function with a circle shape (see link below).
  53573. * @see https://easings.net/#easeInCirc
  53574. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53575. */
  53576. var CircleEase = /** @class */ (function (_super) {
  53577. __extends(CircleEase, _super);
  53578. function CircleEase() {
  53579. return _super !== null && _super.apply(this, arguments) || this;
  53580. }
  53581. /** @hidden */
  53582. CircleEase.prototype.easeInCore = function (gradient) {
  53583. gradient = Math.max(0, Math.min(1, gradient));
  53584. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53585. };
  53586. return CircleEase;
  53587. }(EasingFunction));
  53588. BABYLON.CircleEase = CircleEase;
  53589. /**
  53590. * Easing function with a ease back shape (see link below).
  53591. * @see https://easings.net/#easeInBack
  53592. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53593. */
  53594. var BackEase = /** @class */ (function (_super) {
  53595. __extends(BackEase, _super);
  53596. /**
  53597. * Instantiates a back ease easing
  53598. * @see https://easings.net/#easeInBack
  53599. * @param amplitude Defines the amplitude of the function
  53600. */
  53601. function BackEase(
  53602. /** Defines the amplitude of the function */
  53603. amplitude) {
  53604. if (amplitude === void 0) { amplitude = 1; }
  53605. var _this = _super.call(this) || this;
  53606. _this.amplitude = amplitude;
  53607. return _this;
  53608. }
  53609. /** @hidden */
  53610. BackEase.prototype.easeInCore = function (gradient) {
  53611. var num = Math.max(0, this.amplitude);
  53612. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53613. };
  53614. return BackEase;
  53615. }(EasingFunction));
  53616. BABYLON.BackEase = BackEase;
  53617. /**
  53618. * Easing function with a bouncing shape (see link below).
  53619. * @see https://easings.net/#easeInBounce
  53620. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53621. */
  53622. var BounceEase = /** @class */ (function (_super) {
  53623. __extends(BounceEase, _super);
  53624. /**
  53625. * Instantiates a bounce easing
  53626. * @see https://easings.net/#easeInBounce
  53627. * @param bounces Defines the number of bounces
  53628. * @param bounciness Defines the amplitude of the bounce
  53629. */
  53630. function BounceEase(
  53631. /** Defines the number of bounces */
  53632. bounces,
  53633. /** Defines the amplitude of the bounce */
  53634. bounciness) {
  53635. if (bounces === void 0) { bounces = 3; }
  53636. if (bounciness === void 0) { bounciness = 2; }
  53637. var _this = _super.call(this) || this;
  53638. _this.bounces = bounces;
  53639. _this.bounciness = bounciness;
  53640. return _this;
  53641. }
  53642. /** @hidden */
  53643. BounceEase.prototype.easeInCore = function (gradient) {
  53644. var y = Math.max(0.0, this.bounces);
  53645. var bounciness = this.bounciness;
  53646. if (bounciness <= 1.0) {
  53647. bounciness = 1.001;
  53648. }
  53649. var num9 = Math.pow(bounciness, y);
  53650. var num5 = 1.0 - bounciness;
  53651. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53652. var num15 = gradient * num4;
  53653. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53654. var num3 = Math.floor(num65);
  53655. var num13 = num3 + 1.0;
  53656. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53657. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53658. var num7 = (num8 + num12) * 0.5;
  53659. var num6 = gradient - num7;
  53660. var num2 = num7 - num8;
  53661. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53662. };
  53663. return BounceEase;
  53664. }(EasingFunction));
  53665. BABYLON.BounceEase = BounceEase;
  53666. /**
  53667. * Easing function with a power of 3 shape (see link below).
  53668. * @see https://easings.net/#easeInCubic
  53669. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53670. */
  53671. var CubicEase = /** @class */ (function (_super) {
  53672. __extends(CubicEase, _super);
  53673. function CubicEase() {
  53674. return _super !== null && _super.apply(this, arguments) || this;
  53675. }
  53676. /** @hidden */
  53677. CubicEase.prototype.easeInCore = function (gradient) {
  53678. return (gradient * gradient * gradient);
  53679. };
  53680. return CubicEase;
  53681. }(EasingFunction));
  53682. BABYLON.CubicEase = CubicEase;
  53683. /**
  53684. * Easing function with an elastic shape (see link below).
  53685. * @see https://easings.net/#easeInElastic
  53686. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53687. */
  53688. var ElasticEase = /** @class */ (function (_super) {
  53689. __extends(ElasticEase, _super);
  53690. /**
  53691. * Instantiates an elastic easing function
  53692. * @see https://easings.net/#easeInElastic
  53693. * @param oscillations Defines the number of oscillations
  53694. * @param springiness Defines the amplitude of the oscillations
  53695. */
  53696. function ElasticEase(
  53697. /** Defines the number of oscillations*/
  53698. oscillations,
  53699. /** Defines the amplitude of the oscillations*/
  53700. springiness) {
  53701. if (oscillations === void 0) { oscillations = 3; }
  53702. if (springiness === void 0) { springiness = 3; }
  53703. var _this = _super.call(this) || this;
  53704. _this.oscillations = oscillations;
  53705. _this.springiness = springiness;
  53706. return _this;
  53707. }
  53708. /** @hidden */
  53709. ElasticEase.prototype.easeInCore = function (gradient) {
  53710. var num2;
  53711. var num3 = Math.max(0.0, this.oscillations);
  53712. var num = Math.max(0.0, this.springiness);
  53713. if (num == 0) {
  53714. num2 = gradient;
  53715. }
  53716. else {
  53717. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53718. }
  53719. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53720. };
  53721. return ElasticEase;
  53722. }(EasingFunction));
  53723. BABYLON.ElasticEase = ElasticEase;
  53724. /**
  53725. * Easing function with an exponential shape (see link below).
  53726. * @see https://easings.net/#easeInExpo
  53727. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53728. */
  53729. var ExponentialEase = /** @class */ (function (_super) {
  53730. __extends(ExponentialEase, _super);
  53731. /**
  53732. * Instantiates an exponential easing function
  53733. * @see https://easings.net/#easeInExpo
  53734. * @param exponent Defines the exponent of the function
  53735. */
  53736. function ExponentialEase(
  53737. /** Defines the exponent of the function */
  53738. exponent) {
  53739. if (exponent === void 0) { exponent = 2; }
  53740. var _this = _super.call(this) || this;
  53741. _this.exponent = exponent;
  53742. return _this;
  53743. }
  53744. /** @hidden */
  53745. ExponentialEase.prototype.easeInCore = function (gradient) {
  53746. if (this.exponent <= 0) {
  53747. return gradient;
  53748. }
  53749. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53750. };
  53751. return ExponentialEase;
  53752. }(EasingFunction));
  53753. BABYLON.ExponentialEase = ExponentialEase;
  53754. /**
  53755. * Easing function with a power shape (see link below).
  53756. * @see https://easings.net/#easeInQuad
  53757. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53758. */
  53759. var PowerEase = /** @class */ (function (_super) {
  53760. __extends(PowerEase, _super);
  53761. /**
  53762. * Instantiates an power base easing function
  53763. * @see https://easings.net/#easeInQuad
  53764. * @param power Defines the power of the function
  53765. */
  53766. function PowerEase(
  53767. /** Defines the power of the function */
  53768. power) {
  53769. if (power === void 0) { power = 2; }
  53770. var _this = _super.call(this) || this;
  53771. _this.power = power;
  53772. return _this;
  53773. }
  53774. /** @hidden */
  53775. PowerEase.prototype.easeInCore = function (gradient) {
  53776. var y = Math.max(0.0, this.power);
  53777. return Math.pow(gradient, y);
  53778. };
  53779. return PowerEase;
  53780. }(EasingFunction));
  53781. BABYLON.PowerEase = PowerEase;
  53782. /**
  53783. * Easing function with a power of 2 shape (see link below).
  53784. * @see https://easings.net/#easeInQuad
  53785. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53786. */
  53787. var QuadraticEase = /** @class */ (function (_super) {
  53788. __extends(QuadraticEase, _super);
  53789. function QuadraticEase() {
  53790. return _super !== null && _super.apply(this, arguments) || this;
  53791. }
  53792. /** @hidden */
  53793. QuadraticEase.prototype.easeInCore = function (gradient) {
  53794. return (gradient * gradient);
  53795. };
  53796. return QuadraticEase;
  53797. }(EasingFunction));
  53798. BABYLON.QuadraticEase = QuadraticEase;
  53799. /**
  53800. * Easing function with a power of 4 shape (see link below).
  53801. * @see https://easings.net/#easeInQuart
  53802. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53803. */
  53804. var QuarticEase = /** @class */ (function (_super) {
  53805. __extends(QuarticEase, _super);
  53806. function QuarticEase() {
  53807. return _super !== null && _super.apply(this, arguments) || this;
  53808. }
  53809. /** @hidden */
  53810. QuarticEase.prototype.easeInCore = function (gradient) {
  53811. return (gradient * gradient * gradient * gradient);
  53812. };
  53813. return QuarticEase;
  53814. }(EasingFunction));
  53815. BABYLON.QuarticEase = QuarticEase;
  53816. /**
  53817. * Easing function with a power of 5 shape (see link below).
  53818. * @see https://easings.net/#easeInQuint
  53819. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53820. */
  53821. var QuinticEase = /** @class */ (function (_super) {
  53822. __extends(QuinticEase, _super);
  53823. function QuinticEase() {
  53824. return _super !== null && _super.apply(this, arguments) || this;
  53825. }
  53826. /** @hidden */
  53827. QuinticEase.prototype.easeInCore = function (gradient) {
  53828. return (gradient * gradient * gradient * gradient * gradient);
  53829. };
  53830. return QuinticEase;
  53831. }(EasingFunction));
  53832. BABYLON.QuinticEase = QuinticEase;
  53833. /**
  53834. * Easing function with a sin shape (see link below).
  53835. * @see https://easings.net/#easeInSine
  53836. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53837. */
  53838. var SineEase = /** @class */ (function (_super) {
  53839. __extends(SineEase, _super);
  53840. function SineEase() {
  53841. return _super !== null && _super.apply(this, arguments) || this;
  53842. }
  53843. /** @hidden */
  53844. SineEase.prototype.easeInCore = function (gradient) {
  53845. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53846. };
  53847. return SineEase;
  53848. }(EasingFunction));
  53849. BABYLON.SineEase = SineEase;
  53850. /**
  53851. * Easing function with a bezier shape (see link below).
  53852. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53853. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53854. */
  53855. var BezierCurveEase = /** @class */ (function (_super) {
  53856. __extends(BezierCurveEase, _super);
  53857. /**
  53858. * Instantiates a bezier function
  53859. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53860. * @param x1 Defines the x component of the start tangent in the bezier curve
  53861. * @param y1 Defines the y component of the start tangent in the bezier curve
  53862. * @param x2 Defines the x component of the end tangent in the bezier curve
  53863. * @param y2 Defines the y component of the end tangent in the bezier curve
  53864. */
  53865. function BezierCurveEase(
  53866. /** Defines the x component of the start tangent in the bezier curve */
  53867. x1,
  53868. /** Defines the y component of the start tangent in the bezier curve */
  53869. y1,
  53870. /** Defines the x component of the end tangent in the bezier curve */
  53871. x2,
  53872. /** Defines the y component of the end tangent in the bezier curve */
  53873. y2) {
  53874. if (x1 === void 0) { x1 = 0; }
  53875. if (y1 === void 0) { y1 = 0; }
  53876. if (x2 === void 0) { x2 = 1; }
  53877. if (y2 === void 0) { y2 = 1; }
  53878. var _this = _super.call(this) || this;
  53879. _this.x1 = x1;
  53880. _this.y1 = y1;
  53881. _this.x2 = x2;
  53882. _this.y2 = y2;
  53883. return _this;
  53884. }
  53885. /** @hidden */
  53886. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53887. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53888. };
  53889. return BezierCurveEase;
  53890. }(EasingFunction));
  53891. BABYLON.BezierCurveEase = BezierCurveEase;
  53892. })(BABYLON || (BABYLON = {}));
  53893. //# sourceMappingURL=babylon.easing.js.map
  53894. var BABYLON;
  53895. (function (BABYLON) {
  53896. /**
  53897. * A Condition applied to an Action
  53898. */
  53899. var Condition = /** @class */ (function () {
  53900. /**
  53901. * Creates a new Condition
  53902. * @param actionManager the manager of the action the condition is applied to
  53903. */
  53904. function Condition(actionManager) {
  53905. this._actionManager = actionManager;
  53906. }
  53907. /**
  53908. * Check if the current condition is valid
  53909. * @returns a boolean
  53910. */
  53911. Condition.prototype.isValid = function () {
  53912. return true;
  53913. };
  53914. /**
  53915. * Internal only
  53916. * @hidden
  53917. */
  53918. Condition.prototype._getProperty = function (propertyPath) {
  53919. return this._actionManager._getProperty(propertyPath);
  53920. };
  53921. /**
  53922. * Internal only
  53923. * @hidden
  53924. */
  53925. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53926. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53927. };
  53928. /**
  53929. * Serialize placeholder for child classes
  53930. * @returns the serialized object
  53931. */
  53932. Condition.prototype.serialize = function () {
  53933. };
  53934. /**
  53935. * Internal only
  53936. * @hidden
  53937. */
  53938. Condition.prototype._serialize = function (serializedCondition) {
  53939. return {
  53940. type: 2,
  53941. children: [],
  53942. name: serializedCondition.name,
  53943. properties: serializedCondition.properties
  53944. };
  53945. };
  53946. return Condition;
  53947. }());
  53948. BABYLON.Condition = Condition;
  53949. /**
  53950. * Defines specific conditional operators as extensions of Condition
  53951. */
  53952. var ValueCondition = /** @class */ (function (_super) {
  53953. __extends(ValueCondition, _super);
  53954. /**
  53955. * Creates a new ValueCondition
  53956. * @param actionManager manager for the action the condition applies to
  53957. * @param target for the action
  53958. * @param propertyPath path to specify the property of the target the conditional operator uses
  53959. * @param value the value compared by the conditional operator against the current value of the property
  53960. * @param operator the conditional operator, default ValueCondition.IsEqual
  53961. */
  53962. function ValueCondition(actionManager, target,
  53963. /** path to specify the property of the target the conditional operator uses */
  53964. propertyPath,
  53965. /** the value compared by the conditional operator against the current value of the property */
  53966. value,
  53967. /** the conditional operator, default ValueCondition.IsEqual */
  53968. operator) {
  53969. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53970. var _this = _super.call(this, actionManager) || this;
  53971. _this.propertyPath = propertyPath;
  53972. _this.value = value;
  53973. _this.operator = operator;
  53974. _this._target = target;
  53975. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53976. _this._property = _this._getProperty(_this.propertyPath);
  53977. return _this;
  53978. }
  53979. Object.defineProperty(ValueCondition, "IsEqual", {
  53980. /**
  53981. * returns the number for IsEqual
  53982. */
  53983. get: function () {
  53984. return ValueCondition._IsEqual;
  53985. },
  53986. enumerable: true,
  53987. configurable: true
  53988. });
  53989. Object.defineProperty(ValueCondition, "IsDifferent", {
  53990. /**
  53991. * Returns the number for IsDifferent
  53992. */
  53993. get: function () {
  53994. return ValueCondition._IsDifferent;
  53995. },
  53996. enumerable: true,
  53997. configurable: true
  53998. });
  53999. Object.defineProperty(ValueCondition, "IsGreater", {
  54000. /**
  54001. * Returns the number for IsGreater
  54002. */
  54003. get: function () {
  54004. return ValueCondition._IsGreater;
  54005. },
  54006. enumerable: true,
  54007. configurable: true
  54008. });
  54009. Object.defineProperty(ValueCondition, "IsLesser", {
  54010. /**
  54011. * Returns the number for IsLesser
  54012. */
  54013. get: function () {
  54014. return ValueCondition._IsLesser;
  54015. },
  54016. enumerable: true,
  54017. configurable: true
  54018. });
  54019. /**
  54020. * Compares the given value with the property value for the specified conditional operator
  54021. * @returns the result of the comparison
  54022. */
  54023. ValueCondition.prototype.isValid = function () {
  54024. switch (this.operator) {
  54025. case ValueCondition.IsGreater:
  54026. return this._effectiveTarget[this._property] > this.value;
  54027. case ValueCondition.IsLesser:
  54028. return this._effectiveTarget[this._property] < this.value;
  54029. case ValueCondition.IsEqual:
  54030. case ValueCondition.IsDifferent:
  54031. var check;
  54032. if (this.value.equals) {
  54033. check = this.value.equals(this._effectiveTarget[this._property]);
  54034. }
  54035. else {
  54036. check = this.value === this._effectiveTarget[this._property];
  54037. }
  54038. return this.operator === ValueCondition.IsEqual ? check : !check;
  54039. }
  54040. return false;
  54041. };
  54042. /**
  54043. * Serialize the ValueCondition into a JSON compatible object
  54044. * @returns serialization object
  54045. */
  54046. ValueCondition.prototype.serialize = function () {
  54047. return this._serialize({
  54048. name: "ValueCondition",
  54049. properties: [
  54050. BABYLON.Action._GetTargetProperty(this._target),
  54051. { name: "propertyPath", value: this.propertyPath },
  54052. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54053. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54054. ]
  54055. });
  54056. };
  54057. /**
  54058. * Gets the name of the conditional operator for the ValueCondition
  54059. * @param operator the conditional operator
  54060. * @returns the name
  54061. */
  54062. ValueCondition.GetOperatorName = function (operator) {
  54063. switch (operator) {
  54064. case ValueCondition._IsEqual: return "IsEqual";
  54065. case ValueCondition._IsDifferent: return "IsDifferent";
  54066. case ValueCondition._IsGreater: return "IsGreater";
  54067. case ValueCondition._IsLesser: return "IsLesser";
  54068. default: return "";
  54069. }
  54070. };
  54071. /**
  54072. * Internal only
  54073. * @hidden
  54074. */
  54075. ValueCondition._IsEqual = 0;
  54076. /**
  54077. * Internal only
  54078. * @hidden
  54079. */
  54080. ValueCondition._IsDifferent = 1;
  54081. /**
  54082. * Internal only
  54083. * @hidden
  54084. */
  54085. ValueCondition._IsGreater = 2;
  54086. /**
  54087. * Internal only
  54088. * @hidden
  54089. */
  54090. ValueCondition._IsLesser = 3;
  54091. return ValueCondition;
  54092. }(Condition));
  54093. BABYLON.ValueCondition = ValueCondition;
  54094. /**
  54095. * Defines a predicate condition as an extension of Condition
  54096. */
  54097. var PredicateCondition = /** @class */ (function (_super) {
  54098. __extends(PredicateCondition, _super);
  54099. /**
  54100. * Creates a new PredicateCondition
  54101. * @param actionManager manager for the action the condition applies to
  54102. * @param predicate defines the predicate function used to validate the condition
  54103. */
  54104. function PredicateCondition(actionManager,
  54105. /** defines the predicate function used to validate the condition */
  54106. predicate) {
  54107. var _this = _super.call(this, actionManager) || this;
  54108. _this.predicate = predicate;
  54109. return _this;
  54110. }
  54111. /**
  54112. * @returns the validity of the predicate condition
  54113. */
  54114. PredicateCondition.prototype.isValid = function () {
  54115. return this.predicate();
  54116. };
  54117. return PredicateCondition;
  54118. }(Condition));
  54119. BABYLON.PredicateCondition = PredicateCondition;
  54120. /**
  54121. * Defines a state condition as an extension of Condition
  54122. */
  54123. var StateCondition = /** @class */ (function (_super) {
  54124. __extends(StateCondition, _super);
  54125. /**
  54126. * Creates a new StateCondition
  54127. * @param actionManager manager for the action the condition applies to
  54128. * @param target of the condition
  54129. * @param value to compare with target state
  54130. */
  54131. function StateCondition(actionManager, target, value) {
  54132. var _this = _super.call(this, actionManager) || this;
  54133. _this.value = value;
  54134. _this._target = target;
  54135. return _this;
  54136. }
  54137. /**
  54138. * @returns the validity of the state
  54139. */
  54140. StateCondition.prototype.isValid = function () {
  54141. return this._target.state === this.value;
  54142. };
  54143. /**
  54144. * Serialize the StateCondition into a JSON compatible object
  54145. * @returns serialization object
  54146. */
  54147. StateCondition.prototype.serialize = function () {
  54148. return this._serialize({
  54149. name: "StateCondition",
  54150. properties: [
  54151. BABYLON.Action._GetTargetProperty(this._target),
  54152. { name: "value", value: this.value }
  54153. ]
  54154. });
  54155. };
  54156. return StateCondition;
  54157. }(Condition));
  54158. BABYLON.StateCondition = StateCondition;
  54159. })(BABYLON || (BABYLON = {}));
  54160. //# sourceMappingURL=babylon.condition.js.map
  54161. var BABYLON;
  54162. (function (BABYLON) {
  54163. /**
  54164. * The action to be carried out following a trigger
  54165. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54166. */
  54167. var Action = /** @class */ (function () {
  54168. /**
  54169. * Creates a new Action
  54170. * @param triggerOptions the trigger, with or without parameters, for the action
  54171. * @param condition an optional determinant of action
  54172. */
  54173. function Action(
  54174. /** the trigger, with or without parameters, for the action */
  54175. triggerOptions, condition) {
  54176. this.triggerOptions = triggerOptions;
  54177. /**
  54178. * An event triggered prior to action being executed.
  54179. */
  54180. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54181. if (triggerOptions.parameter) {
  54182. this.trigger = triggerOptions.trigger;
  54183. this._triggerParameter = triggerOptions.parameter;
  54184. }
  54185. else if (triggerOptions.trigger) {
  54186. this.trigger = triggerOptions.trigger;
  54187. }
  54188. else {
  54189. this.trigger = triggerOptions;
  54190. }
  54191. this._nextActiveAction = this;
  54192. this._condition = condition;
  54193. }
  54194. /**
  54195. * Internal only
  54196. * @hidden
  54197. */
  54198. Action.prototype._prepare = function () {
  54199. };
  54200. /**
  54201. * Gets the trigger parameters
  54202. * @returns the trigger parameters
  54203. */
  54204. Action.prototype.getTriggerParameter = function () {
  54205. return this._triggerParameter;
  54206. };
  54207. /**
  54208. * Internal only - executes current action event
  54209. * @hidden
  54210. */
  54211. Action.prototype._executeCurrent = function (evt) {
  54212. if (this._nextActiveAction._condition) {
  54213. var condition = this._nextActiveAction._condition;
  54214. var currentRenderId = this._actionManager.getScene().getRenderId();
  54215. // We cache the current evaluation for the current frame
  54216. if (condition._evaluationId === currentRenderId) {
  54217. if (!condition._currentResult) {
  54218. return;
  54219. }
  54220. }
  54221. else {
  54222. condition._evaluationId = currentRenderId;
  54223. if (!condition.isValid()) {
  54224. condition._currentResult = false;
  54225. return;
  54226. }
  54227. condition._currentResult = true;
  54228. }
  54229. }
  54230. this.onBeforeExecuteObservable.notifyObservers(this);
  54231. this._nextActiveAction.execute(evt);
  54232. this.skipToNextActiveAction();
  54233. };
  54234. /**
  54235. * Execute placeholder for child classes
  54236. * @param evt optional action event
  54237. */
  54238. Action.prototype.execute = function (evt) {
  54239. };
  54240. /**
  54241. * Skips to next active action
  54242. */
  54243. Action.prototype.skipToNextActiveAction = function () {
  54244. if (this._nextActiveAction._child) {
  54245. if (!this._nextActiveAction._child._actionManager) {
  54246. this._nextActiveAction._child._actionManager = this._actionManager;
  54247. }
  54248. this._nextActiveAction = this._nextActiveAction._child;
  54249. }
  54250. else {
  54251. this._nextActiveAction = this;
  54252. }
  54253. };
  54254. /**
  54255. * Adds action to chain of actions, may be a DoNothingAction
  54256. * @param action defines the next action to execute
  54257. * @returns The action passed in
  54258. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54259. */
  54260. Action.prototype.then = function (action) {
  54261. this._child = action;
  54262. action._actionManager = this._actionManager;
  54263. action._prepare();
  54264. return action;
  54265. };
  54266. /**
  54267. * Internal only
  54268. * @hidden
  54269. */
  54270. Action.prototype._getProperty = function (propertyPath) {
  54271. return this._actionManager._getProperty(propertyPath);
  54272. };
  54273. /**
  54274. * Internal only
  54275. * @hidden
  54276. */
  54277. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54278. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54279. };
  54280. /**
  54281. * Serialize placeholder for child classes
  54282. * @param parent of child
  54283. * @returns the serialized object
  54284. */
  54285. Action.prototype.serialize = function (parent) {
  54286. };
  54287. /**
  54288. * Internal only called by serialize
  54289. * @hidden
  54290. */
  54291. Action.prototype._serialize = function (serializedAction, parent) {
  54292. var serializationObject = {
  54293. type: 1,
  54294. children: [],
  54295. name: serializedAction.name,
  54296. properties: serializedAction.properties || []
  54297. };
  54298. // Serialize child
  54299. if (this._child) {
  54300. this._child.serialize(serializationObject);
  54301. }
  54302. // Check if "this" has a condition
  54303. if (this._condition) {
  54304. var serializedCondition = this._condition.serialize();
  54305. serializedCondition.children.push(serializationObject);
  54306. if (parent) {
  54307. parent.children.push(serializedCondition);
  54308. }
  54309. return serializedCondition;
  54310. }
  54311. if (parent) {
  54312. parent.children.push(serializationObject);
  54313. }
  54314. return serializationObject;
  54315. };
  54316. /**
  54317. * Internal only
  54318. * @hidden
  54319. */
  54320. Action._SerializeValueAsString = function (value) {
  54321. if (typeof value === "number") {
  54322. return value.toString();
  54323. }
  54324. if (typeof value === "boolean") {
  54325. return value ? "true" : "false";
  54326. }
  54327. if (value instanceof BABYLON.Vector2) {
  54328. return value.x + ", " + value.y;
  54329. }
  54330. if (value instanceof BABYLON.Vector3) {
  54331. return value.x + ", " + value.y + ", " + value.z;
  54332. }
  54333. if (value instanceof BABYLON.Color3) {
  54334. return value.r + ", " + value.g + ", " + value.b;
  54335. }
  54336. if (value instanceof BABYLON.Color4) {
  54337. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  54338. }
  54339. return value; // string
  54340. };
  54341. /**
  54342. * Internal only
  54343. * @hidden
  54344. */
  54345. Action._GetTargetProperty = function (target) {
  54346. return {
  54347. name: "target",
  54348. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  54349. : target instanceof BABYLON.Light ? "LightProperties"
  54350. : target instanceof BABYLON.Camera ? "CameraProperties"
  54351. : "SceneProperties",
  54352. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  54353. };
  54354. };
  54355. return Action;
  54356. }());
  54357. BABYLON.Action = Action;
  54358. })(BABYLON || (BABYLON = {}));
  54359. //# sourceMappingURL=babylon.action.js.map
  54360. var BABYLON;
  54361. (function (BABYLON) {
  54362. /**
  54363. * ActionEvent is the event being sent when an action is triggered.
  54364. */
  54365. var ActionEvent = /** @class */ (function () {
  54366. /**
  54367. * Creates a new ActionEvent
  54368. * @param source The mesh or sprite that triggered the action
  54369. * @param pointerX The X mouse cursor position at the time of the event
  54370. * @param pointerY The Y mouse cursor position at the time of the event
  54371. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  54372. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  54373. * @param additionalData additional data for the event
  54374. */
  54375. function ActionEvent(
  54376. /** The mesh or sprite that triggered the action */
  54377. source,
  54378. /** The X mouse cursor position at the time of the event */
  54379. pointerX,
  54380. /** The Y mouse cursor position at the time of the event */
  54381. pointerY,
  54382. /** The mesh that is currently pointed at (can be null) */
  54383. meshUnderPointer,
  54384. /** the original (browser) event that triggered the ActionEvent */
  54385. sourceEvent,
  54386. /** additional data for the event */
  54387. additionalData) {
  54388. this.source = source;
  54389. this.pointerX = pointerX;
  54390. this.pointerY = pointerY;
  54391. this.meshUnderPointer = meshUnderPointer;
  54392. this.sourceEvent = sourceEvent;
  54393. this.additionalData = additionalData;
  54394. }
  54395. /**
  54396. * Helper function to auto-create an ActionEvent from a source mesh.
  54397. * @param source The source mesh that triggered the event
  54398. * @param evt The original (browser) event
  54399. * @param additionalData additional data for the event
  54400. * @returns the new ActionEvent
  54401. */
  54402. ActionEvent.CreateNew = function (source, evt, additionalData) {
  54403. var scene = source.getScene();
  54404. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54405. };
  54406. /**
  54407. * Helper function to auto-create an ActionEvent from a source sprite
  54408. * @param source The source sprite that triggered the event
  54409. * @param scene Scene associated with the sprite
  54410. * @param evt The original (browser) event
  54411. * @param additionalData additional data for the event
  54412. * @returns the new ActionEvent
  54413. */
  54414. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  54415. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54416. };
  54417. /**
  54418. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  54419. * @param scene the scene where the event occurred
  54420. * @param evt The original (browser) event
  54421. * @returns the new ActionEvent
  54422. */
  54423. ActionEvent.CreateNewFromScene = function (scene, evt) {
  54424. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  54425. };
  54426. /**
  54427. * Helper function to auto-create an ActionEvent from a primitive
  54428. * @param prim defines the target primitive
  54429. * @param pointerPos defines the pointer position
  54430. * @param evt The original (browser) event
  54431. * @param additionalData additional data for the event
  54432. * @returns the new ActionEvent
  54433. */
  54434. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  54435. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  54436. };
  54437. return ActionEvent;
  54438. }());
  54439. BABYLON.ActionEvent = ActionEvent;
  54440. /**
  54441. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  54442. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  54443. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54444. */
  54445. var ActionManager = /** @class */ (function () {
  54446. /**
  54447. * Creates a new action manager
  54448. * @param scene defines the hosting scene
  54449. */
  54450. function ActionManager(scene) {
  54451. // Members
  54452. /** Gets the list of actions */
  54453. this.actions = new Array();
  54454. /** Gets the cursor to use when hovering items */
  54455. this.hoverCursor = '';
  54456. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54457. scene.actionManagers.push(this);
  54458. }
  54459. // Methods
  54460. /**
  54461. * Releases all associated resources
  54462. */
  54463. ActionManager.prototype.dispose = function () {
  54464. var index = this._scene.actionManagers.indexOf(this);
  54465. for (var i = 0; i < this.actions.length; i++) {
  54466. var action = this.actions[i];
  54467. ActionManager.Triggers[action.trigger]--;
  54468. if (ActionManager.Triggers[action.trigger] === 0) {
  54469. delete ActionManager.Triggers[action.trigger];
  54470. }
  54471. }
  54472. if (index > -1) {
  54473. this._scene.actionManagers.splice(index, 1);
  54474. }
  54475. };
  54476. /**
  54477. * Gets hosting scene
  54478. * @returns the hosting scene
  54479. */
  54480. ActionManager.prototype.getScene = function () {
  54481. return this._scene;
  54482. };
  54483. /**
  54484. * Does this action manager handles actions of any of the given triggers
  54485. * @param triggers defines the triggers to be tested
  54486. * @return a boolean indicating whether one (or more) of the triggers is handled
  54487. */
  54488. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  54489. for (var index = 0; index < this.actions.length; index++) {
  54490. var action = this.actions[index];
  54491. if (triggers.indexOf(action.trigger) > -1) {
  54492. return true;
  54493. }
  54494. }
  54495. return false;
  54496. };
  54497. /**
  54498. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54499. * speed.
  54500. * @param triggerA defines the trigger to be tested
  54501. * @param triggerB defines the trigger to be tested
  54502. * @return a boolean indicating whether one (or more) of the triggers is handled
  54503. */
  54504. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54505. for (var index = 0; index < this.actions.length; index++) {
  54506. var action = this.actions[index];
  54507. if (triggerA == action.trigger || triggerB == action.trigger) {
  54508. return true;
  54509. }
  54510. }
  54511. return false;
  54512. };
  54513. /**
  54514. * Does this action manager handles actions of a given trigger
  54515. * @param trigger defines the trigger to be tested
  54516. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54517. * @return whether the trigger is handled
  54518. */
  54519. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54520. for (var index = 0; index < this.actions.length; index++) {
  54521. var action = this.actions[index];
  54522. if (action.trigger === trigger) {
  54523. if (parameterPredicate) {
  54524. if (parameterPredicate(action.getTriggerParameter())) {
  54525. return true;
  54526. }
  54527. }
  54528. else {
  54529. return true;
  54530. }
  54531. }
  54532. }
  54533. return false;
  54534. };
  54535. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54536. /**
  54537. * Does this action manager has pointer triggers
  54538. */
  54539. get: function () {
  54540. for (var index = 0; index < this.actions.length; index++) {
  54541. var action = this.actions[index];
  54542. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54543. return true;
  54544. }
  54545. }
  54546. return false;
  54547. },
  54548. enumerable: true,
  54549. configurable: true
  54550. });
  54551. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54552. /**
  54553. * Does this action manager has pick triggers
  54554. */
  54555. get: function () {
  54556. for (var index = 0; index < this.actions.length; index++) {
  54557. var action = this.actions[index];
  54558. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54559. return true;
  54560. }
  54561. }
  54562. return false;
  54563. },
  54564. enumerable: true,
  54565. configurable: true
  54566. });
  54567. Object.defineProperty(ActionManager, "HasTriggers", {
  54568. /**
  54569. * Does exist one action manager with at least one trigger
  54570. **/
  54571. get: function () {
  54572. for (var t in ActionManager.Triggers) {
  54573. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54574. return true;
  54575. }
  54576. }
  54577. return false;
  54578. },
  54579. enumerable: true,
  54580. configurable: true
  54581. });
  54582. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54583. /**
  54584. * Does exist one action manager with at least one pick trigger
  54585. **/
  54586. get: function () {
  54587. for (var t in ActionManager.Triggers) {
  54588. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54589. var t_int = parseInt(t);
  54590. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54591. return true;
  54592. }
  54593. }
  54594. }
  54595. return false;
  54596. },
  54597. enumerable: true,
  54598. configurable: true
  54599. });
  54600. /**
  54601. * Does exist one action manager that handles actions of a given trigger
  54602. * @param trigger defines the trigger to be tested
  54603. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54604. **/
  54605. ActionManager.HasSpecificTrigger = function (trigger) {
  54606. for (var t in ActionManager.Triggers) {
  54607. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54608. var t_int = parseInt(t);
  54609. if (t_int === trigger) {
  54610. return true;
  54611. }
  54612. }
  54613. }
  54614. return false;
  54615. };
  54616. /**
  54617. * Registers an action to this action manager
  54618. * @param action defines the action to be registered
  54619. * @return the action amended (prepared) after registration
  54620. */
  54621. ActionManager.prototype.registerAction = function (action) {
  54622. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54623. if (this.getScene().actionManager !== this) {
  54624. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54625. return null;
  54626. }
  54627. }
  54628. this.actions.push(action);
  54629. if (ActionManager.Triggers[action.trigger]) {
  54630. ActionManager.Triggers[action.trigger]++;
  54631. }
  54632. else {
  54633. ActionManager.Triggers[action.trigger] = 1;
  54634. }
  54635. action._actionManager = this;
  54636. action._prepare();
  54637. return action;
  54638. };
  54639. /**
  54640. * Unregisters an action to this action manager
  54641. * @param action defines the action to be unregistered
  54642. * @return a boolean indicating whether the action has been unregistered
  54643. */
  54644. ActionManager.prototype.unregisterAction = function (action) {
  54645. var index = this.actions.indexOf(action);
  54646. if (index !== -1) {
  54647. this.actions.splice(index, 1);
  54648. ActionManager.Triggers[action.trigger] -= 1;
  54649. if (ActionManager.Triggers[action.trigger] === 0) {
  54650. delete ActionManager.Triggers[action.trigger];
  54651. }
  54652. delete action._actionManager;
  54653. return true;
  54654. }
  54655. return false;
  54656. };
  54657. /**
  54658. * Process a specific trigger
  54659. * @param trigger defines the trigger to process
  54660. * @param evt defines the event details to be processed
  54661. */
  54662. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54663. for (var index = 0; index < this.actions.length; index++) {
  54664. var action = this.actions[index];
  54665. if (action.trigger === trigger) {
  54666. if (evt) {
  54667. if (trigger === ActionManager.OnKeyUpTrigger
  54668. || trigger === ActionManager.OnKeyDownTrigger) {
  54669. var parameter = action.getTriggerParameter();
  54670. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54671. if (!parameter.toLowerCase) {
  54672. continue;
  54673. }
  54674. var lowerCase = parameter.toLowerCase();
  54675. if (lowerCase !== evt.sourceEvent.key) {
  54676. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54677. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54678. if (actualkey !== lowerCase) {
  54679. continue;
  54680. }
  54681. }
  54682. }
  54683. }
  54684. }
  54685. action._executeCurrent(evt);
  54686. }
  54687. }
  54688. };
  54689. /** @hidden */
  54690. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54691. var properties = propertyPath.split(".");
  54692. for (var index = 0; index < properties.length - 1; index++) {
  54693. target = target[properties[index]];
  54694. }
  54695. return target;
  54696. };
  54697. /** @hidden */
  54698. ActionManager.prototype._getProperty = function (propertyPath) {
  54699. var properties = propertyPath.split(".");
  54700. return properties[properties.length - 1];
  54701. };
  54702. /**
  54703. * Serialize this manager to a JSON object
  54704. * @param name defines the property name to store this manager
  54705. * @returns a JSON representation of this manager
  54706. */
  54707. ActionManager.prototype.serialize = function (name) {
  54708. var root = {
  54709. children: new Array(),
  54710. name: name,
  54711. type: 3,
  54712. properties: new Array() // Empty for root but required
  54713. };
  54714. for (var i = 0; i < this.actions.length; i++) {
  54715. var triggerObject = {
  54716. type: 0,
  54717. children: new Array(),
  54718. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54719. properties: new Array()
  54720. };
  54721. var triggerOptions = this.actions[i].triggerOptions;
  54722. if (triggerOptions && typeof triggerOptions !== "number") {
  54723. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54724. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54725. }
  54726. else {
  54727. var parameter = {};
  54728. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54729. if (triggerOptions.parameter.mesh) {
  54730. parameter._meshId = triggerOptions.parameter.mesh.id;
  54731. }
  54732. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54733. }
  54734. }
  54735. // Serialize child action, recursively
  54736. this.actions[i].serialize(triggerObject);
  54737. // Add serialized trigger
  54738. root.children.push(triggerObject);
  54739. }
  54740. return root;
  54741. };
  54742. /**
  54743. * Creates a new ActionManager from a JSON data
  54744. * @param parsedActions defines the JSON data to read from
  54745. * @param object defines the hosting mesh
  54746. * @param scene defines the hosting scene
  54747. */
  54748. ActionManager.Parse = function (parsedActions, object, scene) {
  54749. var actionManager = new ActionManager(scene);
  54750. if (object === null)
  54751. scene.actionManager = actionManager;
  54752. else
  54753. object.actionManager = actionManager;
  54754. // instanciate a new object
  54755. var instanciate = function (name, params) {
  54756. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54757. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54758. newInstance.constructor.apply(newInstance, params);
  54759. return newInstance;
  54760. };
  54761. var parseParameter = function (name, value, target, propertyPath) {
  54762. if (propertyPath === null) {
  54763. // String, boolean or float
  54764. var floatValue = parseFloat(value);
  54765. if (value === "true" || value === "false")
  54766. return value === "true";
  54767. else
  54768. return isNaN(floatValue) ? value : floatValue;
  54769. }
  54770. var effectiveTarget = propertyPath.split(".");
  54771. var values = value.split(",");
  54772. // Get effective Target
  54773. for (var i = 0; i < effectiveTarget.length; i++) {
  54774. target = target[effectiveTarget[i]];
  54775. }
  54776. // Return appropriate value with its type
  54777. if (typeof (target) === "boolean")
  54778. return values[0] === "true";
  54779. if (typeof (target) === "string")
  54780. return values[0];
  54781. // Parameters with multiple values such as Vector3 etc.
  54782. var split = new Array();
  54783. for (var i = 0; i < values.length; i++)
  54784. split.push(parseFloat(values[i]));
  54785. if (target instanceof BABYLON.Vector3)
  54786. return BABYLON.Vector3.FromArray(split);
  54787. if (target instanceof BABYLON.Vector4)
  54788. return BABYLON.Vector4.FromArray(split);
  54789. if (target instanceof BABYLON.Color3)
  54790. return BABYLON.Color3.FromArray(split);
  54791. if (target instanceof BABYLON.Color4)
  54792. return BABYLON.Color4.FromArray(split);
  54793. return parseFloat(values[0]);
  54794. };
  54795. // traverse graph per trigger
  54796. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54797. if (combineArray === void 0) { combineArray = null; }
  54798. if (parsedAction.detached)
  54799. return;
  54800. var parameters = new Array();
  54801. var target = null;
  54802. var propertyPath = null;
  54803. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54804. // Parameters
  54805. if (parsedAction.type === 2)
  54806. parameters.push(actionManager);
  54807. else
  54808. parameters.push(trigger);
  54809. if (combine) {
  54810. var actions = new Array();
  54811. for (var j = 0; j < parsedAction.combine.length; j++) {
  54812. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54813. }
  54814. parameters.push(actions);
  54815. }
  54816. else {
  54817. for (var i = 0; i < parsedAction.properties.length; i++) {
  54818. var value = parsedAction.properties[i].value;
  54819. var name = parsedAction.properties[i].name;
  54820. var targetType = parsedAction.properties[i].targetType;
  54821. if (name === "target")
  54822. if (targetType !== null && targetType === "SceneProperties")
  54823. value = target = scene;
  54824. else
  54825. value = target = scene.getNodeByName(value);
  54826. else if (name === "parent")
  54827. value = scene.getNodeByName(value);
  54828. else if (name === "sound") {
  54829. // Can not externalize to component, so only checks for the presence off the API.
  54830. if (scene.getSoundByName) {
  54831. value = scene.getSoundByName(value);
  54832. }
  54833. }
  54834. else if (name !== "propertyPath") {
  54835. if (parsedAction.type === 2 && name === "operator")
  54836. value = BABYLON.ValueCondition[value];
  54837. else
  54838. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54839. }
  54840. else {
  54841. propertyPath = value;
  54842. }
  54843. parameters.push(value);
  54844. }
  54845. }
  54846. if (combineArray === null) {
  54847. parameters.push(condition);
  54848. }
  54849. else {
  54850. parameters.push(null);
  54851. }
  54852. // If interpolate value action
  54853. if (parsedAction.name === "InterpolateValueAction") {
  54854. var param = parameters[parameters.length - 2];
  54855. parameters[parameters.length - 1] = param;
  54856. parameters[parameters.length - 2] = condition;
  54857. }
  54858. // Action or condition(s) and not CombineAction
  54859. var newAction = instanciate(parsedAction.name, parameters);
  54860. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54861. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54862. if (action)
  54863. action.then(nothing);
  54864. else
  54865. actionManager.registerAction(nothing);
  54866. action = nothing;
  54867. }
  54868. if (combineArray === null) {
  54869. if (newAction instanceof BABYLON.Condition) {
  54870. condition = newAction;
  54871. newAction = action;
  54872. }
  54873. else {
  54874. condition = null;
  54875. if (action)
  54876. action.then(newAction);
  54877. else
  54878. actionManager.registerAction(newAction);
  54879. }
  54880. }
  54881. else {
  54882. combineArray.push(newAction);
  54883. }
  54884. for (var i = 0; i < parsedAction.children.length; i++)
  54885. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54886. };
  54887. // triggers
  54888. for (var i = 0; i < parsedActions.children.length; i++) {
  54889. var triggerParams;
  54890. var trigger = parsedActions.children[i];
  54891. if (trigger.properties.length > 0) {
  54892. var param = trigger.properties[0].value;
  54893. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54894. if (value._meshId) {
  54895. value.mesh = scene.getMeshByID(value._meshId);
  54896. }
  54897. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54898. }
  54899. else
  54900. triggerParams = ActionManager[trigger.name];
  54901. for (var j = 0; j < trigger.children.length; j++) {
  54902. if (!trigger.detached)
  54903. traverse(trigger.children[j], triggerParams, null, null);
  54904. }
  54905. }
  54906. };
  54907. /**
  54908. * Get a trigger name by index
  54909. * @param trigger defines the trigger index
  54910. * @returns a trigger name
  54911. */
  54912. ActionManager.GetTriggerName = function (trigger) {
  54913. switch (trigger) {
  54914. case 0: return "NothingTrigger";
  54915. case 1: return "OnPickTrigger";
  54916. case 2: return "OnLeftPickTrigger";
  54917. case 3: return "OnRightPickTrigger";
  54918. case 4: return "OnCenterPickTrigger";
  54919. case 5: return "OnPickDownTrigger";
  54920. case 6: return "OnPickUpTrigger";
  54921. case 7: return "OnLongPressTrigger";
  54922. case 8: return "OnPointerOverTrigger";
  54923. case 9: return "OnPointerOutTrigger";
  54924. case 10: return "OnEveryFrameTrigger";
  54925. case 11: return "OnIntersectionEnterTrigger";
  54926. case 12: return "OnIntersectionExitTrigger";
  54927. case 13: return "OnKeyDownTrigger";
  54928. case 14: return "OnKeyUpTrigger";
  54929. case 15: return "OnPickOutTrigger";
  54930. default: return "";
  54931. }
  54932. };
  54933. /**
  54934. * Nothing
  54935. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54936. */
  54937. ActionManager.NothingTrigger = 0;
  54938. /**
  54939. * On pick
  54940. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54941. */
  54942. ActionManager.OnPickTrigger = 1;
  54943. /**
  54944. * On left pick
  54945. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54946. */
  54947. ActionManager.OnLeftPickTrigger = 2;
  54948. /**
  54949. * On right pick
  54950. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54951. */
  54952. ActionManager.OnRightPickTrigger = 3;
  54953. /**
  54954. * On center pick
  54955. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54956. */
  54957. ActionManager.OnCenterPickTrigger = 4;
  54958. /**
  54959. * On pick down
  54960. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54961. */
  54962. ActionManager.OnPickDownTrigger = 5;
  54963. /**
  54964. * On double pick
  54965. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54966. */
  54967. ActionManager.OnDoublePickTrigger = 6;
  54968. /**
  54969. * On pick up
  54970. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54971. */
  54972. ActionManager.OnPickUpTrigger = 7;
  54973. /**
  54974. * On pick out.
  54975. * This trigger will only be raised if you also declared a OnPickDown
  54976. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54977. */
  54978. ActionManager.OnPickOutTrigger = 16;
  54979. /**
  54980. * On long press
  54981. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54982. */
  54983. ActionManager.OnLongPressTrigger = 8;
  54984. /**
  54985. * On pointer over
  54986. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54987. */
  54988. ActionManager.OnPointerOverTrigger = 9;
  54989. /**
  54990. * On pointer out
  54991. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54992. */
  54993. ActionManager.OnPointerOutTrigger = 10;
  54994. /**
  54995. * On every frame
  54996. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54997. */
  54998. ActionManager.OnEveryFrameTrigger = 11;
  54999. /**
  55000. * On intersection enter
  55001. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55002. */
  55003. ActionManager.OnIntersectionEnterTrigger = 12;
  55004. /**
  55005. * On intersection exit
  55006. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55007. */
  55008. ActionManager.OnIntersectionExitTrigger = 13;
  55009. /**
  55010. * On key down
  55011. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55012. */
  55013. ActionManager.OnKeyDownTrigger = 14;
  55014. /**
  55015. * On key up
  55016. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55017. */
  55018. ActionManager.OnKeyUpTrigger = 15;
  55019. /** Gets the list of active triggers */
  55020. ActionManager.Triggers = {};
  55021. return ActionManager;
  55022. }());
  55023. BABYLON.ActionManager = ActionManager;
  55024. })(BABYLON || (BABYLON = {}));
  55025. //# sourceMappingURL=babylon.actionManager.js.map
  55026. var BABYLON;
  55027. (function (BABYLON) {
  55028. /**
  55029. * This defines an action responsible to change the value of a property
  55030. * by interpolating between its current value and the newly set one once triggered.
  55031. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55032. */
  55033. var InterpolateValueAction = /** @class */ (function (_super) {
  55034. __extends(InterpolateValueAction, _super);
  55035. /**
  55036. * Instantiate the action
  55037. * @param triggerOptions defines the trigger options
  55038. * @param target defines the object containing the value to interpolate
  55039. * @param propertyPath defines the path to the property in the target object
  55040. * @param value defines the target value at the end of the interpolation
  55041. * @param duration deines the time it will take for the property to interpolate to the value.
  55042. * @param condition defines the trigger related conditions
  55043. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55044. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55045. */
  55046. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55047. if (duration === void 0) { duration = 1000; }
  55048. var _this = _super.call(this, triggerOptions, condition) || this;
  55049. /**
  55050. * Defines the time it will take for the property to interpolate to the value.
  55051. */
  55052. _this.duration = 1000;
  55053. /**
  55054. * Observable triggered once the interpolation animation has been done.
  55055. */
  55056. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55057. _this.propertyPath = propertyPath;
  55058. _this.value = value;
  55059. _this.duration = duration;
  55060. _this.stopOtherAnimations = stopOtherAnimations;
  55061. _this.onInterpolationDone = onInterpolationDone;
  55062. _this._target = _this._effectiveTarget = target;
  55063. return _this;
  55064. }
  55065. /** @hidden */
  55066. InterpolateValueAction.prototype._prepare = function () {
  55067. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55068. this._property = this._getProperty(this.propertyPath);
  55069. };
  55070. /**
  55071. * Execute the action starts the value interpolation.
  55072. */
  55073. InterpolateValueAction.prototype.execute = function () {
  55074. var _this = this;
  55075. var scene = this._actionManager.getScene();
  55076. var keys = [
  55077. {
  55078. frame: 0,
  55079. value: this._effectiveTarget[this._property]
  55080. }, {
  55081. frame: 100,
  55082. value: this.value
  55083. }
  55084. ];
  55085. var dataType;
  55086. if (typeof this.value === "number") {
  55087. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55088. }
  55089. else if (this.value instanceof BABYLON.Color3) {
  55090. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55091. }
  55092. else if (this.value instanceof BABYLON.Vector3) {
  55093. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55094. }
  55095. else if (this.value instanceof BABYLON.Matrix) {
  55096. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55097. }
  55098. else if (this.value instanceof BABYLON.Quaternion) {
  55099. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55100. }
  55101. else {
  55102. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55103. return;
  55104. }
  55105. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55106. animation.setKeys(keys);
  55107. if (this.stopOtherAnimations) {
  55108. scene.stopAnimation(this._effectiveTarget);
  55109. }
  55110. var wrapper = function () {
  55111. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55112. if (_this.onInterpolationDone) {
  55113. _this.onInterpolationDone();
  55114. }
  55115. };
  55116. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55117. };
  55118. /**
  55119. * Serializes the actions and its related information.
  55120. * @param parent defines the object to serialize in
  55121. * @returns the serialized object
  55122. */
  55123. InterpolateValueAction.prototype.serialize = function (parent) {
  55124. return _super.prototype._serialize.call(this, {
  55125. name: "InterpolateValueAction",
  55126. properties: [
  55127. BABYLON.Action._GetTargetProperty(this._target),
  55128. { name: "propertyPath", value: this.propertyPath },
  55129. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55130. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55131. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55132. ]
  55133. }, parent);
  55134. };
  55135. return InterpolateValueAction;
  55136. }(BABYLON.Action));
  55137. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55138. })(BABYLON || (BABYLON = {}));
  55139. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55140. var BABYLON;
  55141. (function (BABYLON) {
  55142. /**
  55143. * This defines an action responsible to toggle a boolean once triggered.
  55144. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55145. */
  55146. var SwitchBooleanAction = /** @class */ (function (_super) {
  55147. __extends(SwitchBooleanAction, _super);
  55148. /**
  55149. * Instantiate the action
  55150. * @param triggerOptions defines the trigger options
  55151. * @param target defines the object containing the boolean
  55152. * @param propertyPath defines the path to the boolean property in the target object
  55153. * @param condition defines the trigger related conditions
  55154. */
  55155. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55156. var _this = _super.call(this, triggerOptions, condition) || this;
  55157. _this.propertyPath = propertyPath;
  55158. _this._target = _this._effectiveTarget = target;
  55159. return _this;
  55160. }
  55161. /** @hidden */
  55162. SwitchBooleanAction.prototype._prepare = function () {
  55163. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55164. this._property = this._getProperty(this.propertyPath);
  55165. };
  55166. /**
  55167. * Execute the action toggle the boolean value.
  55168. */
  55169. SwitchBooleanAction.prototype.execute = function () {
  55170. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55171. };
  55172. /**
  55173. * Serializes the actions and its related information.
  55174. * @param parent defines the object to serialize in
  55175. * @returns the serialized object
  55176. */
  55177. SwitchBooleanAction.prototype.serialize = function (parent) {
  55178. return _super.prototype._serialize.call(this, {
  55179. name: "SwitchBooleanAction",
  55180. properties: [
  55181. BABYLON.Action._GetTargetProperty(this._target),
  55182. { name: "propertyPath", value: this.propertyPath }
  55183. ]
  55184. }, parent);
  55185. };
  55186. return SwitchBooleanAction;
  55187. }(BABYLON.Action));
  55188. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55189. /**
  55190. * This defines an action responsible to set a the state field of the target
  55191. * to a desired value once triggered.
  55192. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55193. */
  55194. var SetStateAction = /** @class */ (function (_super) {
  55195. __extends(SetStateAction, _super);
  55196. /**
  55197. * Instantiate the action
  55198. * @param triggerOptions defines the trigger options
  55199. * @param target defines the object containing the state property
  55200. * @param value defines the value to store in the state field
  55201. * @param condition defines the trigger related conditions
  55202. */
  55203. function SetStateAction(triggerOptions, target, value, condition) {
  55204. var _this = _super.call(this, triggerOptions, condition) || this;
  55205. _this.value = value;
  55206. _this._target = target;
  55207. return _this;
  55208. }
  55209. /**
  55210. * Execute the action and store the value on the target state property.
  55211. */
  55212. SetStateAction.prototype.execute = function () {
  55213. this._target.state = this.value;
  55214. };
  55215. /**
  55216. * Serializes the actions and its related information.
  55217. * @param parent defines the object to serialize in
  55218. * @returns the serialized object
  55219. */
  55220. SetStateAction.prototype.serialize = function (parent) {
  55221. return _super.prototype._serialize.call(this, {
  55222. name: "SetStateAction",
  55223. properties: [
  55224. BABYLON.Action._GetTargetProperty(this._target),
  55225. { name: "value", value: this.value }
  55226. ]
  55227. }, parent);
  55228. };
  55229. return SetStateAction;
  55230. }(BABYLON.Action));
  55231. BABYLON.SetStateAction = SetStateAction;
  55232. /**
  55233. * This defines an action responsible to set a property of the target
  55234. * to a desired value once triggered.
  55235. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55236. */
  55237. var SetValueAction = /** @class */ (function (_super) {
  55238. __extends(SetValueAction, _super);
  55239. /**
  55240. * Instantiate the action
  55241. * @param triggerOptions defines the trigger options
  55242. * @param target defines the object containing the property
  55243. * @param propertyPath defines the path of the property to set in the target
  55244. * @param value defines the value to set in the property
  55245. * @param condition defines the trigger related conditions
  55246. */
  55247. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55248. var _this = _super.call(this, triggerOptions, condition) || this;
  55249. _this.propertyPath = propertyPath;
  55250. _this.value = value;
  55251. _this._target = _this._effectiveTarget = target;
  55252. return _this;
  55253. }
  55254. /** @hidden */
  55255. SetValueAction.prototype._prepare = function () {
  55256. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55257. this._property = this._getProperty(this.propertyPath);
  55258. };
  55259. /**
  55260. * Execute the action and set the targetted property to the desired value.
  55261. */
  55262. SetValueAction.prototype.execute = function () {
  55263. this._effectiveTarget[this._property] = this.value;
  55264. if (this._target.markAsDirty) {
  55265. this._target.markAsDirty(this._property);
  55266. }
  55267. };
  55268. /**
  55269. * Serializes the actions and its related information.
  55270. * @param parent defines the object to serialize in
  55271. * @returns the serialized object
  55272. */
  55273. SetValueAction.prototype.serialize = function (parent) {
  55274. return _super.prototype._serialize.call(this, {
  55275. name: "SetValueAction",
  55276. properties: [
  55277. BABYLON.Action._GetTargetProperty(this._target),
  55278. { name: "propertyPath", value: this.propertyPath },
  55279. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55280. ]
  55281. }, parent);
  55282. };
  55283. return SetValueAction;
  55284. }(BABYLON.Action));
  55285. BABYLON.SetValueAction = SetValueAction;
  55286. /**
  55287. * This defines an action responsible to increment the target value
  55288. * to a desired value once triggered.
  55289. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55290. */
  55291. var IncrementValueAction = /** @class */ (function (_super) {
  55292. __extends(IncrementValueAction, _super);
  55293. /**
  55294. * Instantiate the action
  55295. * @param triggerOptions defines the trigger options
  55296. * @param target defines the object containing the property
  55297. * @param propertyPath defines the path of the property to increment in the target
  55298. * @param value defines the value value we should increment the property by
  55299. * @param condition defines the trigger related conditions
  55300. */
  55301. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55302. var _this = _super.call(this, triggerOptions, condition) || this;
  55303. _this.propertyPath = propertyPath;
  55304. _this.value = value;
  55305. _this._target = _this._effectiveTarget = target;
  55306. return _this;
  55307. }
  55308. /** @hidden */
  55309. IncrementValueAction.prototype._prepare = function () {
  55310. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55311. this._property = this._getProperty(this.propertyPath);
  55312. if (typeof this._effectiveTarget[this._property] !== "number") {
  55313. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55314. }
  55315. };
  55316. /**
  55317. * Execute the action and increment the target of the value amount.
  55318. */
  55319. IncrementValueAction.prototype.execute = function () {
  55320. this._effectiveTarget[this._property] += this.value;
  55321. if (this._target.markAsDirty) {
  55322. this._target.markAsDirty(this._property);
  55323. }
  55324. };
  55325. /**
  55326. * Serializes the actions and its related information.
  55327. * @param parent defines the object to serialize in
  55328. * @returns the serialized object
  55329. */
  55330. IncrementValueAction.prototype.serialize = function (parent) {
  55331. return _super.prototype._serialize.call(this, {
  55332. name: "IncrementValueAction",
  55333. properties: [
  55334. BABYLON.Action._GetTargetProperty(this._target),
  55335. { name: "propertyPath", value: this.propertyPath },
  55336. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55337. ]
  55338. }, parent);
  55339. };
  55340. return IncrementValueAction;
  55341. }(BABYLON.Action));
  55342. BABYLON.IncrementValueAction = IncrementValueAction;
  55343. /**
  55344. * This defines an action responsible to start an animation once triggered.
  55345. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55346. */
  55347. var PlayAnimationAction = /** @class */ (function (_super) {
  55348. __extends(PlayAnimationAction, _super);
  55349. /**
  55350. * Instantiate the action
  55351. * @param triggerOptions defines the trigger options
  55352. * @param target defines the target animation or animation name
  55353. * @param from defines from where the animation should start (animation frame)
  55354. * @param end defines where the animation should stop (animation frame)
  55355. * @param loop defines if the animation should loop or stop after the first play
  55356. * @param condition defines the trigger related conditions
  55357. */
  55358. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  55359. var _this = _super.call(this, triggerOptions, condition) || this;
  55360. _this.from = from;
  55361. _this.to = to;
  55362. _this.loop = loop;
  55363. _this._target = target;
  55364. return _this;
  55365. }
  55366. /** @hidden */
  55367. PlayAnimationAction.prototype._prepare = function () {
  55368. };
  55369. /**
  55370. * Execute the action and play the animation.
  55371. */
  55372. PlayAnimationAction.prototype.execute = function () {
  55373. var scene = this._actionManager.getScene();
  55374. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  55375. };
  55376. /**
  55377. * Serializes the actions and its related information.
  55378. * @param parent defines the object to serialize in
  55379. * @returns the serialized object
  55380. */
  55381. PlayAnimationAction.prototype.serialize = function (parent) {
  55382. return _super.prototype._serialize.call(this, {
  55383. name: "PlayAnimationAction",
  55384. properties: [
  55385. BABYLON.Action._GetTargetProperty(this._target),
  55386. { name: "from", value: String(this.from) },
  55387. { name: "to", value: String(this.to) },
  55388. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  55389. ]
  55390. }, parent);
  55391. };
  55392. return PlayAnimationAction;
  55393. }(BABYLON.Action));
  55394. BABYLON.PlayAnimationAction = PlayAnimationAction;
  55395. /**
  55396. * This defines an action responsible to stop an animation once triggered.
  55397. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55398. */
  55399. var StopAnimationAction = /** @class */ (function (_super) {
  55400. __extends(StopAnimationAction, _super);
  55401. /**
  55402. * Instantiate the action
  55403. * @param triggerOptions defines the trigger options
  55404. * @param target defines the target animation or animation name
  55405. * @param condition defines the trigger related conditions
  55406. */
  55407. function StopAnimationAction(triggerOptions, target, condition) {
  55408. var _this = _super.call(this, triggerOptions, condition) || this;
  55409. _this._target = target;
  55410. return _this;
  55411. }
  55412. /** @hidden */
  55413. StopAnimationAction.prototype._prepare = function () {
  55414. };
  55415. /**
  55416. * Execute the action and stop the animation.
  55417. */
  55418. StopAnimationAction.prototype.execute = function () {
  55419. var scene = this._actionManager.getScene();
  55420. scene.stopAnimation(this._target);
  55421. };
  55422. /**
  55423. * Serializes the actions and its related information.
  55424. * @param parent defines the object to serialize in
  55425. * @returns the serialized object
  55426. */
  55427. StopAnimationAction.prototype.serialize = function (parent) {
  55428. return _super.prototype._serialize.call(this, {
  55429. name: "StopAnimationAction",
  55430. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  55431. }, parent);
  55432. };
  55433. return StopAnimationAction;
  55434. }(BABYLON.Action));
  55435. BABYLON.StopAnimationAction = StopAnimationAction;
  55436. /**
  55437. * This defines an action responsible that does nothing once triggered.
  55438. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55439. */
  55440. var DoNothingAction = /** @class */ (function (_super) {
  55441. __extends(DoNothingAction, _super);
  55442. /**
  55443. * Instantiate the action
  55444. * @param triggerOptions defines the trigger options
  55445. * @param condition defines the trigger related conditions
  55446. */
  55447. function DoNothingAction(triggerOptions, condition) {
  55448. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  55449. return _super.call(this, triggerOptions, condition) || this;
  55450. }
  55451. /**
  55452. * Execute the action and do nothing.
  55453. */
  55454. DoNothingAction.prototype.execute = function () {
  55455. };
  55456. /**
  55457. * Serializes the actions and its related information.
  55458. * @param parent defines the object to serialize in
  55459. * @returns the serialized object
  55460. */
  55461. DoNothingAction.prototype.serialize = function (parent) {
  55462. return _super.prototype._serialize.call(this, {
  55463. name: "DoNothingAction",
  55464. properties: []
  55465. }, parent);
  55466. };
  55467. return DoNothingAction;
  55468. }(BABYLON.Action));
  55469. BABYLON.DoNothingAction = DoNothingAction;
  55470. /**
  55471. * This defines an action responsible to trigger several actions once triggered.
  55472. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55473. */
  55474. var CombineAction = /** @class */ (function (_super) {
  55475. __extends(CombineAction, _super);
  55476. /**
  55477. * Instantiate the action
  55478. * @param triggerOptions defines the trigger options
  55479. * @param children defines the list of aggregated animations to run
  55480. * @param condition defines the trigger related conditions
  55481. */
  55482. function CombineAction(triggerOptions, children, condition) {
  55483. var _this = _super.call(this, triggerOptions, condition) || this;
  55484. _this.children = children;
  55485. return _this;
  55486. }
  55487. /** @hidden */
  55488. CombineAction.prototype._prepare = function () {
  55489. for (var index = 0; index < this.children.length; index++) {
  55490. this.children[index]._actionManager = this._actionManager;
  55491. this.children[index]._prepare();
  55492. }
  55493. };
  55494. /**
  55495. * Execute the action and executes all the aggregated actions.
  55496. */
  55497. CombineAction.prototype.execute = function (evt) {
  55498. for (var index = 0; index < this.children.length; index++) {
  55499. this.children[index].execute(evt);
  55500. }
  55501. };
  55502. /**
  55503. * Serializes the actions and its related information.
  55504. * @param parent defines the object to serialize in
  55505. * @returns the serialized object
  55506. */
  55507. CombineAction.prototype.serialize = function (parent) {
  55508. var serializationObject = _super.prototype._serialize.call(this, {
  55509. name: "CombineAction",
  55510. properties: [],
  55511. combine: []
  55512. }, parent);
  55513. for (var i = 0; i < this.children.length; i++) {
  55514. serializationObject.combine.push(this.children[i].serialize(null));
  55515. }
  55516. return serializationObject;
  55517. };
  55518. return CombineAction;
  55519. }(BABYLON.Action));
  55520. BABYLON.CombineAction = CombineAction;
  55521. /**
  55522. * This defines an action responsible to run code (external event) once triggered.
  55523. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55524. */
  55525. var ExecuteCodeAction = /** @class */ (function (_super) {
  55526. __extends(ExecuteCodeAction, _super);
  55527. /**
  55528. * Instantiate the action
  55529. * @param triggerOptions defines the trigger options
  55530. * @param func defines the callback function to run
  55531. * @param condition defines the trigger related conditions
  55532. */
  55533. function ExecuteCodeAction(triggerOptions, func, condition) {
  55534. var _this = _super.call(this, triggerOptions, condition) || this;
  55535. _this.func = func;
  55536. return _this;
  55537. }
  55538. /**
  55539. * Execute the action and run the attached code.
  55540. */
  55541. ExecuteCodeAction.prototype.execute = function (evt) {
  55542. this.func(evt);
  55543. };
  55544. return ExecuteCodeAction;
  55545. }(BABYLON.Action));
  55546. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55547. /**
  55548. * This defines an action responsible to set the parent property of the target once triggered.
  55549. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55550. */
  55551. var SetParentAction = /** @class */ (function (_super) {
  55552. __extends(SetParentAction, _super);
  55553. /**
  55554. * Instantiate the action
  55555. * @param triggerOptions defines the trigger options
  55556. * @param target defines the target containing the parent property
  55557. * @param parent defines from where the animation should start (animation frame)
  55558. * @param condition defines the trigger related conditions
  55559. */
  55560. function SetParentAction(triggerOptions, target, parent, condition) {
  55561. var _this = _super.call(this, triggerOptions, condition) || this;
  55562. _this._target = target;
  55563. _this._parent = parent;
  55564. return _this;
  55565. }
  55566. /** @hidden */
  55567. SetParentAction.prototype._prepare = function () {
  55568. };
  55569. /**
  55570. * Execute the action and set the parent property.
  55571. */
  55572. SetParentAction.prototype.execute = function () {
  55573. if (this._target.parent === this._parent) {
  55574. return;
  55575. }
  55576. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55577. invertParentWorldMatrix.invert();
  55578. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55579. this._target.parent = this._parent;
  55580. };
  55581. /**
  55582. * Serializes the actions and its related information.
  55583. * @param parent defines the object to serialize in
  55584. * @returns the serialized object
  55585. */
  55586. SetParentAction.prototype.serialize = function (parent) {
  55587. return _super.prototype._serialize.call(this, {
  55588. name: "SetParentAction",
  55589. properties: [
  55590. BABYLON.Action._GetTargetProperty(this._target),
  55591. BABYLON.Action._GetTargetProperty(this._parent),
  55592. ]
  55593. }, parent);
  55594. };
  55595. return SetParentAction;
  55596. }(BABYLON.Action));
  55597. BABYLON.SetParentAction = SetParentAction;
  55598. })(BABYLON || (BABYLON = {}));
  55599. //# sourceMappingURL=babylon.directActions.js.map
  55600. var BABYLON;
  55601. (function (BABYLON) {
  55602. var SpriteManager = /** @class */ (function () {
  55603. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55604. if (epsilon === void 0) { epsilon = 0.01; }
  55605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55606. this.name = name;
  55607. this.sprites = new Array();
  55608. this.renderingGroupId = 0;
  55609. this.layerMask = 0x0FFFFFFF;
  55610. this.fogEnabled = true;
  55611. this.isPickable = false;
  55612. /**
  55613. * An event triggered when the manager is disposed.
  55614. */
  55615. this.onDisposeObservable = new BABYLON.Observable();
  55616. this._vertexBuffers = {};
  55617. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55618. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55619. }
  55620. this._capacity = capacity;
  55621. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55622. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55623. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55624. if (cellSize.width && cellSize.height) {
  55625. this.cellWidth = cellSize.width;
  55626. this.cellHeight = cellSize.height;
  55627. }
  55628. else if (cellSize !== undefined) {
  55629. this.cellWidth = cellSize;
  55630. this.cellHeight = cellSize;
  55631. }
  55632. else {
  55633. return;
  55634. }
  55635. this._epsilon = epsilon;
  55636. this._scene = scene;
  55637. this._scene.spriteManagers.push(this);
  55638. var indices = [];
  55639. var index = 0;
  55640. for (var count = 0; count < capacity; count++) {
  55641. indices.push(index);
  55642. indices.push(index + 1);
  55643. indices.push(index + 2);
  55644. indices.push(index);
  55645. indices.push(index + 2);
  55646. indices.push(index + 3);
  55647. index += 4;
  55648. }
  55649. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55650. // VBO
  55651. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55652. this._vertexData = new Float32Array(capacity * 16 * 4);
  55653. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55654. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55655. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55656. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55657. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55659. this._vertexBuffers["options"] = options;
  55660. this._vertexBuffers["cellInfo"] = cellInfo;
  55661. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55662. // Effects
  55663. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55664. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55665. }
  55666. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55667. set: function (callback) {
  55668. if (this._onDisposeObserver) {
  55669. this.onDisposeObservable.remove(this._onDisposeObserver);
  55670. }
  55671. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55672. },
  55673. enumerable: true,
  55674. configurable: true
  55675. });
  55676. Object.defineProperty(SpriteManager.prototype, "texture", {
  55677. get: function () {
  55678. return this._spriteTexture;
  55679. },
  55680. set: function (value) {
  55681. this._spriteTexture = value;
  55682. },
  55683. enumerable: true,
  55684. configurable: true
  55685. });
  55686. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55687. var arrayOffset = index * 16;
  55688. if (offsetX === 0)
  55689. offsetX = this._epsilon;
  55690. else if (offsetX === 1)
  55691. offsetX = 1 - this._epsilon;
  55692. if (offsetY === 0)
  55693. offsetY = this._epsilon;
  55694. else if (offsetY === 1)
  55695. offsetY = 1 - this._epsilon;
  55696. this._vertexData[arrayOffset] = sprite.position.x;
  55697. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55698. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55699. this._vertexData[arrayOffset + 3] = sprite.angle;
  55700. this._vertexData[arrayOffset + 4] = sprite.width;
  55701. this._vertexData[arrayOffset + 5] = sprite.height;
  55702. this._vertexData[arrayOffset + 6] = offsetX;
  55703. this._vertexData[arrayOffset + 7] = offsetY;
  55704. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55705. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55706. var offset = (sprite.cellIndex / rowSize) >> 0;
  55707. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55708. this._vertexData[arrayOffset + 11] = offset;
  55709. // Color
  55710. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55711. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55712. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55713. this._vertexData[arrayOffset + 15] = sprite.color.a;
  55714. };
  55715. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  55716. var count = Math.min(this._capacity, this.sprites.length);
  55717. var min = BABYLON.Vector3.Zero();
  55718. var max = BABYLON.Vector3.Zero();
  55719. var distance = Number.MAX_VALUE;
  55720. var currentSprite = null;
  55721. var cameraSpacePosition = BABYLON.Vector3.Zero();
  55722. var cameraView = camera.getViewMatrix();
  55723. for (var index = 0; index < count; index++) {
  55724. var sprite = this.sprites[index];
  55725. if (!sprite) {
  55726. continue;
  55727. }
  55728. if (predicate) {
  55729. if (!predicate(sprite)) {
  55730. continue;
  55731. }
  55732. }
  55733. else if (!sprite.isPickable) {
  55734. continue;
  55735. }
  55736. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55737. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55738. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55739. if (ray.intersectsBoxMinMax(min, max)) {
  55740. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55741. if (distance > currentDistance) {
  55742. distance = currentDistance;
  55743. currentSprite = sprite;
  55744. if (fastCheck) {
  55745. break;
  55746. }
  55747. }
  55748. }
  55749. }
  55750. if (currentSprite) {
  55751. var result = new BABYLON.PickingInfo();
  55752. result.hit = true;
  55753. result.pickedSprite = currentSprite;
  55754. result.distance = distance;
  55755. return result;
  55756. }
  55757. return null;
  55758. };
  55759. SpriteManager.prototype.render = function () {
  55760. // Check
  55761. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55762. return;
  55763. var engine = this._scene.getEngine();
  55764. var baseSize = this._spriteTexture.getBaseSize();
  55765. // Sprites
  55766. var deltaTime = engine.getDeltaTime();
  55767. var max = Math.min(this._capacity, this.sprites.length);
  55768. var rowSize = baseSize.width / this.cellWidth;
  55769. var offset = 0;
  55770. for (var index = 0; index < max; index++) {
  55771. var sprite = this.sprites[index];
  55772. if (!sprite || !sprite.isVisible) {
  55773. continue;
  55774. }
  55775. sprite._animate(deltaTime);
  55776. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55777. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55778. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55779. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55780. }
  55781. this._buffer.update(this._vertexData);
  55782. // Render
  55783. var effect = this._effectBase;
  55784. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55785. effect = this._effectFog;
  55786. }
  55787. engine.enableEffect(effect);
  55788. var viewMatrix = this._scene.getViewMatrix();
  55789. effect.setTexture("diffuseSampler", this._spriteTexture);
  55790. effect.setMatrix("view", viewMatrix);
  55791. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55792. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55793. // Fog
  55794. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55795. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55796. effect.setColor3("vFogColor", this._scene.fogColor);
  55797. }
  55798. // VBOs
  55799. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55800. // Draw order
  55801. engine.setDepthFunctionToLessOrEqual();
  55802. effect.setBool("alphaTest", true);
  55803. engine.setColorWrite(false);
  55804. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55805. engine.setColorWrite(true);
  55806. effect.setBool("alphaTest", false);
  55807. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55808. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55809. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55810. };
  55811. SpriteManager.prototype.dispose = function () {
  55812. if (this._buffer) {
  55813. this._buffer.dispose();
  55814. this._buffer = null;
  55815. }
  55816. if (this._indexBuffer) {
  55817. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55818. this._indexBuffer = null;
  55819. }
  55820. if (this._spriteTexture) {
  55821. this._spriteTexture.dispose();
  55822. this._spriteTexture = null;
  55823. }
  55824. // Remove from scene
  55825. var index = this._scene.spriteManagers.indexOf(this);
  55826. this._scene.spriteManagers.splice(index, 1);
  55827. // Callback
  55828. this.onDisposeObservable.notifyObservers(this);
  55829. this.onDisposeObservable.clear();
  55830. };
  55831. return SpriteManager;
  55832. }());
  55833. BABYLON.SpriteManager = SpriteManager;
  55834. })(BABYLON || (BABYLON = {}));
  55835. //# sourceMappingURL=babylon.spriteManager.js.map
  55836. var BABYLON;
  55837. (function (BABYLON) {
  55838. var Sprite = /** @class */ (function () {
  55839. function Sprite(name, manager) {
  55840. this.name = name;
  55841. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55842. this.width = 1.0;
  55843. this.height = 1.0;
  55844. this.angle = 0;
  55845. this.cellIndex = 0;
  55846. this.invertU = 0;
  55847. this.invertV = 0;
  55848. this.animations = new Array();
  55849. this.isPickable = false;
  55850. this._animationStarted = false;
  55851. this._loopAnimation = false;
  55852. this._fromIndex = 0;
  55853. this._toIndex = 0;
  55854. this._delay = 0;
  55855. this._direction = 1;
  55856. this._time = 0;
  55857. /**
  55858. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55859. */
  55860. this.isVisible = true;
  55861. this._manager = manager;
  55862. this._manager.sprites.push(this);
  55863. this.position = BABYLON.Vector3.Zero();
  55864. }
  55865. Object.defineProperty(Sprite.prototype, "size", {
  55866. get: function () {
  55867. return this.width;
  55868. },
  55869. set: function (value) {
  55870. this.width = value;
  55871. this.height = value;
  55872. },
  55873. enumerable: true,
  55874. configurable: true
  55875. });
  55876. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55877. this._fromIndex = from;
  55878. this._toIndex = to;
  55879. this._loopAnimation = loop;
  55880. this._delay = delay;
  55881. this._animationStarted = true;
  55882. this._direction = from < to ? 1 : -1;
  55883. this.cellIndex = from;
  55884. this._time = 0;
  55885. this._onAnimationEnd = onAnimationEnd;
  55886. };
  55887. Sprite.prototype.stopAnimation = function () {
  55888. this._animationStarted = false;
  55889. };
  55890. /** @hidden */
  55891. Sprite.prototype._animate = function (deltaTime) {
  55892. if (!this._animationStarted)
  55893. return;
  55894. this._time += deltaTime;
  55895. if (this._time > this._delay) {
  55896. this._time = this._time % this._delay;
  55897. this.cellIndex += this._direction;
  55898. if (this.cellIndex > this._toIndex) {
  55899. if (this._loopAnimation) {
  55900. this.cellIndex = this._fromIndex;
  55901. }
  55902. else {
  55903. this.cellIndex = this._toIndex;
  55904. this._animationStarted = false;
  55905. if (this._onAnimationEnd) {
  55906. this._onAnimationEnd();
  55907. }
  55908. if (this.disposeWhenFinishedAnimating) {
  55909. this.dispose();
  55910. }
  55911. }
  55912. }
  55913. }
  55914. };
  55915. Sprite.prototype.dispose = function () {
  55916. for (var i = 0; i < this._manager.sprites.length; i++) {
  55917. if (this._manager.sprites[i] == this) {
  55918. this._manager.sprites.splice(i, 1);
  55919. }
  55920. }
  55921. };
  55922. return Sprite;
  55923. }());
  55924. BABYLON.Sprite = Sprite;
  55925. })(BABYLON || (BABYLON = {}));
  55926. //# sourceMappingURL=babylon.sprite.js.map
  55927. var BABYLON;
  55928. (function (BABYLON) {
  55929. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55930. if (!BABYLON.PickingInfo) {
  55931. return null;
  55932. }
  55933. var pickingInfo = null;
  55934. if (!camera) {
  55935. if (!this.activeCamera) {
  55936. return null;
  55937. }
  55938. camera = this.activeCamera;
  55939. }
  55940. if (this.spriteManagers.length > 0) {
  55941. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55942. var spriteManager = this.spriteManagers[spriteIndex];
  55943. if (!spriteManager.isPickable) {
  55944. continue;
  55945. }
  55946. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55947. if (!result || !result.hit)
  55948. continue;
  55949. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55950. continue;
  55951. pickingInfo = result;
  55952. if (fastCheck) {
  55953. break;
  55954. }
  55955. }
  55956. }
  55957. return pickingInfo || new BABYLON.PickingInfo();
  55958. };
  55959. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55960. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55961. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55962. };
  55963. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55964. if (!this._tempSpritePickingRay) {
  55965. return null;
  55966. }
  55967. if (!camera) {
  55968. if (!this.activeCamera) {
  55969. return null;
  55970. }
  55971. camera = this.activeCamera;
  55972. }
  55973. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55974. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55975. };
  55976. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55977. if (this._pointerOverSprite === sprite) {
  55978. return;
  55979. }
  55980. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55981. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55982. }
  55983. this._pointerOverSprite = sprite;
  55984. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55985. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55986. }
  55987. };
  55988. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55989. return this._pointerOverSprite;
  55990. };
  55991. /**
  55992. * Defines the sprite scene component responsible to manage sprites
  55993. * in a given scene.
  55994. */
  55995. var SpriteSceneComponent = /** @class */ (function () {
  55996. /**
  55997. * Creates a new instance of the component for the given scene
  55998. * @param scene Defines the scene to register the component in
  55999. */
  56000. function SpriteSceneComponent(scene) {
  56001. /**
  56002. * The component name helpfull to identify the component in the list of scene components.
  56003. */
  56004. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56005. this.scene = scene;
  56006. this.scene.spriteManagers = new Array();
  56007. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56008. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56009. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56010. this._spritePredicate = function (sprite) {
  56011. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  56012. };
  56013. }
  56014. /**
  56015. * Registers the component in a given scene
  56016. */
  56017. SpriteSceneComponent.prototype.register = function () {
  56018. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56019. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56020. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56021. };
  56022. /**
  56023. * Rebuilds the elements related to this component in case of
  56024. * context lost for instance.
  56025. */
  56026. SpriteSceneComponent.prototype.rebuild = function () {
  56027. /** Nothing to do for sprites */
  56028. };
  56029. /**
  56030. * Disposes the component and the associated ressources.
  56031. */
  56032. SpriteSceneComponent.prototype.dispose = function () {
  56033. this.scene.onBeforeSpritesRenderingObservable.clear();
  56034. this.scene.onAfterSpritesRenderingObservable.clear();
  56035. var spriteManagers = this.scene.spriteManagers;
  56036. while (spriteManagers.length) {
  56037. spriteManagers[0].dispose();
  56038. }
  56039. };
  56040. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56041. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56042. if (result) {
  56043. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56044. }
  56045. return result;
  56046. };
  56047. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56048. var scene = this.scene;
  56049. if (isMeshPicked) {
  56050. scene.setPointerOverSprite(null);
  56051. }
  56052. else {
  56053. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56054. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56055. scene.setPointerOverSprite(pickResult.pickedSprite);
  56056. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56057. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56058. }
  56059. else {
  56060. canvas.style.cursor = scene.hoverCursor;
  56061. }
  56062. }
  56063. else {
  56064. scene.setPointerOverSprite(null);
  56065. }
  56066. }
  56067. return pickResult;
  56068. };
  56069. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56070. var scene = this.scene;
  56071. scene._pickedDownSprite = null;
  56072. if (scene.spriteManagers.length > 0) {
  56073. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56074. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56075. if (pickResult.pickedSprite.actionManager) {
  56076. scene._pickedDownSprite = pickResult.pickedSprite;
  56077. switch (evt.button) {
  56078. case 0:
  56079. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56080. break;
  56081. case 1:
  56082. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56083. break;
  56084. case 2:
  56085. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56086. break;
  56087. }
  56088. if (pickResult.pickedSprite.actionManager) {
  56089. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56090. }
  56091. }
  56092. }
  56093. }
  56094. return pickResult;
  56095. };
  56096. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56097. var scene = this.scene;
  56098. if (scene.spriteManagers.length > 0) {
  56099. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56100. if (spritePickResult) {
  56101. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56102. if (spritePickResult.pickedSprite.actionManager) {
  56103. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56104. if (spritePickResult.pickedSprite.actionManager) {
  56105. if (!this.scene._isPointerSwiping()) {
  56106. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56107. }
  56108. }
  56109. }
  56110. }
  56111. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56112. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56113. }
  56114. }
  56115. }
  56116. return pickResult;
  56117. };
  56118. return SpriteSceneComponent;
  56119. }());
  56120. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56121. })(BABYLON || (BABYLON = {}));
  56122. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56123. var BABYLON;
  56124. (function (BABYLON) {
  56125. /**
  56126. * @hidden
  56127. */
  56128. var IntersectionInfo = /** @class */ (function () {
  56129. function IntersectionInfo(bu, bv, distance) {
  56130. this.bu = bu;
  56131. this.bv = bv;
  56132. this.distance = distance;
  56133. this.faceId = 0;
  56134. this.subMeshId = 0;
  56135. }
  56136. return IntersectionInfo;
  56137. }());
  56138. BABYLON.IntersectionInfo = IntersectionInfo;
  56139. /**
  56140. * Information about the result of picking within a scene
  56141. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56142. */
  56143. var PickingInfo = /** @class */ (function () {
  56144. function PickingInfo() {
  56145. /**
  56146. * If the pick collided with an object
  56147. */
  56148. this.hit = false;
  56149. /**
  56150. * Distance away where the pick collided
  56151. */
  56152. this.distance = 0;
  56153. /**
  56154. * The location of pick collision
  56155. */
  56156. this.pickedPoint = null;
  56157. /**
  56158. * The mesh corresponding the the pick collision
  56159. */
  56160. this.pickedMesh = null;
  56161. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56162. this.bu = 0;
  56163. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56164. this.bv = 0;
  56165. /** The id of the face on the mesh that was picked */
  56166. this.faceId = -1;
  56167. /** Id of the the submesh that was picked */
  56168. this.subMeshId = 0;
  56169. /** If a sprite was picked, this will be the sprite the pick collided with */
  56170. this.pickedSprite = null;
  56171. /**
  56172. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56173. */
  56174. this.originMesh = null;
  56175. /**
  56176. * The ray that was used to perform the picking.
  56177. */
  56178. this.ray = null;
  56179. }
  56180. /**
  56181. * Gets the normal correspodning to the face the pick collided with
  56182. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56183. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56184. * @returns The normal correspodning to the face the pick collided with
  56185. */
  56186. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56187. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56188. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56189. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56190. return null;
  56191. }
  56192. var indices = this.pickedMesh.getIndices();
  56193. if (!indices) {
  56194. return null;
  56195. }
  56196. var result;
  56197. if (useVerticesNormals) {
  56198. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56199. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56200. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56201. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56202. normal0 = normal0.scale(this.bu);
  56203. normal1 = normal1.scale(this.bv);
  56204. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56205. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56206. }
  56207. else {
  56208. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56209. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56210. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56211. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56212. var p1p2 = vertex1.subtract(vertex2);
  56213. var p3p2 = vertex3.subtract(vertex2);
  56214. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56215. }
  56216. if (useWorldCoordinates) {
  56217. var wm = this.pickedMesh.getWorldMatrix();
  56218. if (this.pickedMesh.nonUniformScaling) {
  56219. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56220. wm = BABYLON.Tmp.Matrix[0];
  56221. wm.setTranslationFromFloats(0, 0, 0);
  56222. wm.invert();
  56223. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56224. wm = BABYLON.Tmp.Matrix[1];
  56225. }
  56226. result = BABYLON.Vector3.TransformNormal(result, wm);
  56227. }
  56228. result.normalize();
  56229. return result;
  56230. };
  56231. /**
  56232. * Gets the texture coordinates of where the pick occured
  56233. * @returns the vector containing the coordnates of the texture
  56234. */
  56235. PickingInfo.prototype.getTextureCoordinates = function () {
  56236. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56237. return null;
  56238. }
  56239. var indices = this.pickedMesh.getIndices();
  56240. if (!indices) {
  56241. return null;
  56242. }
  56243. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56244. if (!uvs) {
  56245. return null;
  56246. }
  56247. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  56248. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  56249. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  56250. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  56251. uv1 = uv1.scale(this.bu);
  56252. uv2 = uv2.scale(this.bv);
  56253. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  56254. };
  56255. return PickingInfo;
  56256. }());
  56257. BABYLON.PickingInfo = PickingInfo;
  56258. })(BABYLON || (BABYLON = {}));
  56259. //# sourceMappingURL=babylon.pickingInfo.js.map
  56260. var BABYLON;
  56261. (function (BABYLON) {
  56262. var Ray = /** @class */ (function () {
  56263. function Ray(origin, direction, length) {
  56264. if (length === void 0) { length = Number.MAX_VALUE; }
  56265. this.origin = origin;
  56266. this.direction = direction;
  56267. this.length = length;
  56268. }
  56269. // Methods
  56270. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  56271. var d = 0.0;
  56272. var maxValue = Number.MAX_VALUE;
  56273. var inv;
  56274. var min;
  56275. var max;
  56276. var temp;
  56277. if (Math.abs(this.direction.x) < 0.0000001) {
  56278. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  56279. return false;
  56280. }
  56281. }
  56282. else {
  56283. inv = 1.0 / this.direction.x;
  56284. min = (minimum.x - this.origin.x) * inv;
  56285. max = (maximum.x - this.origin.x) * inv;
  56286. if (max === -Infinity) {
  56287. max = Infinity;
  56288. }
  56289. if (min > max) {
  56290. temp = min;
  56291. min = max;
  56292. max = temp;
  56293. }
  56294. d = Math.max(min, d);
  56295. maxValue = Math.min(max, maxValue);
  56296. if (d > maxValue) {
  56297. return false;
  56298. }
  56299. }
  56300. if (Math.abs(this.direction.y) < 0.0000001) {
  56301. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  56302. return false;
  56303. }
  56304. }
  56305. else {
  56306. inv = 1.0 / this.direction.y;
  56307. min = (minimum.y - this.origin.y) * inv;
  56308. max = (maximum.y - this.origin.y) * inv;
  56309. if (max === -Infinity) {
  56310. max = Infinity;
  56311. }
  56312. if (min > max) {
  56313. temp = min;
  56314. min = max;
  56315. max = temp;
  56316. }
  56317. d = Math.max(min, d);
  56318. maxValue = Math.min(max, maxValue);
  56319. if (d > maxValue) {
  56320. return false;
  56321. }
  56322. }
  56323. if (Math.abs(this.direction.z) < 0.0000001) {
  56324. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  56325. return false;
  56326. }
  56327. }
  56328. else {
  56329. inv = 1.0 / this.direction.z;
  56330. min = (minimum.z - this.origin.z) * inv;
  56331. max = (maximum.z - this.origin.z) * inv;
  56332. if (max === -Infinity) {
  56333. max = Infinity;
  56334. }
  56335. if (min > max) {
  56336. temp = min;
  56337. min = max;
  56338. max = temp;
  56339. }
  56340. d = Math.max(min, d);
  56341. maxValue = Math.min(max, maxValue);
  56342. if (d > maxValue) {
  56343. return false;
  56344. }
  56345. }
  56346. return true;
  56347. };
  56348. Ray.prototype.intersectsBox = function (box) {
  56349. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  56350. };
  56351. Ray.prototype.intersectsSphere = function (sphere) {
  56352. var x = sphere.center.x - this.origin.x;
  56353. var y = sphere.center.y - this.origin.y;
  56354. var z = sphere.center.z - this.origin.z;
  56355. var pyth = (x * x) + (y * y) + (z * z);
  56356. var rr = sphere.radius * sphere.radius;
  56357. if (pyth <= rr) {
  56358. return true;
  56359. }
  56360. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  56361. if (dot < 0.0) {
  56362. return false;
  56363. }
  56364. var temp = pyth - (dot * dot);
  56365. return temp <= rr;
  56366. };
  56367. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  56368. if (!this._edge1) {
  56369. this._edge1 = BABYLON.Vector3.Zero();
  56370. this._edge2 = BABYLON.Vector3.Zero();
  56371. this._pvec = BABYLON.Vector3.Zero();
  56372. this._tvec = BABYLON.Vector3.Zero();
  56373. this._qvec = BABYLON.Vector3.Zero();
  56374. }
  56375. vertex1.subtractToRef(vertex0, this._edge1);
  56376. vertex2.subtractToRef(vertex0, this._edge2);
  56377. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  56378. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  56379. if (det === 0) {
  56380. return null;
  56381. }
  56382. var invdet = 1 / det;
  56383. this.origin.subtractToRef(vertex0, this._tvec);
  56384. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  56385. if (bu < 0 || bu > 1.0) {
  56386. return null;
  56387. }
  56388. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  56389. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  56390. if (bv < 0 || bu + bv > 1.0) {
  56391. return null;
  56392. }
  56393. //check if the distance is longer than the predefined length.
  56394. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  56395. if (distance > this.length) {
  56396. return null;
  56397. }
  56398. return new BABYLON.IntersectionInfo(bu, bv, distance);
  56399. };
  56400. Ray.prototype.intersectsPlane = function (plane) {
  56401. var distance;
  56402. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  56403. if (Math.abs(result1) < 9.99999997475243E-07) {
  56404. return null;
  56405. }
  56406. else {
  56407. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  56408. distance = (-plane.d - result2) / result1;
  56409. if (distance < 0.0) {
  56410. if (distance < -9.99999997475243E-07) {
  56411. return null;
  56412. }
  56413. else {
  56414. return 0;
  56415. }
  56416. }
  56417. return distance;
  56418. }
  56419. };
  56420. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  56421. var tm = BABYLON.Tmp.Matrix[0];
  56422. mesh.getWorldMatrix().invertToRef(tm);
  56423. if (this._tmpRay) {
  56424. Ray.TransformToRef(this, tm, this._tmpRay);
  56425. }
  56426. else {
  56427. this._tmpRay = Ray.Transform(this, tm);
  56428. }
  56429. return mesh.intersects(this._tmpRay, fastCheck);
  56430. };
  56431. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  56432. if (results) {
  56433. results.length = 0;
  56434. }
  56435. else {
  56436. results = [];
  56437. }
  56438. for (var i = 0; i < meshes.length; i++) {
  56439. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  56440. if (pickInfo.hit) {
  56441. results.push(pickInfo);
  56442. }
  56443. }
  56444. results.sort(this._comparePickingInfo);
  56445. return results;
  56446. };
  56447. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  56448. if (pickingInfoA.distance < pickingInfoB.distance) {
  56449. return -1;
  56450. }
  56451. else if (pickingInfoA.distance > pickingInfoB.distance) {
  56452. return 1;
  56453. }
  56454. else {
  56455. return 0;
  56456. }
  56457. };
  56458. /**
  56459. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  56460. * @param sega the first point of the segment to test the intersection against
  56461. * @param segb the second point of the segment to test the intersection against
  56462. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  56463. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  56464. */
  56465. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  56466. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  56467. var u = segb.subtract(sega);
  56468. var v = rsegb.subtract(this.origin);
  56469. var w = sega.subtract(this.origin);
  56470. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  56471. var b = BABYLON.Vector3.Dot(u, v);
  56472. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  56473. var d = BABYLON.Vector3.Dot(u, w);
  56474. var e = BABYLON.Vector3.Dot(v, w);
  56475. var D = a * c - b * b; // always >= 0
  56476. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  56477. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  56478. // compute the line parameters of the two closest points
  56479. if (D < Ray.smallnum) { // the lines are almost parallel
  56480. sN = 0.0; // force using point P0 on segment S1
  56481. sD = 1.0; // to prevent possible division by 0.0 later
  56482. tN = e;
  56483. tD = c;
  56484. }
  56485. else { // get the closest points on the infinite lines
  56486. sN = (b * e - c * d);
  56487. tN = (a * e - b * d);
  56488. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  56489. sN = 0.0;
  56490. tN = e;
  56491. tD = c;
  56492. }
  56493. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56494. sN = sD;
  56495. tN = e + b;
  56496. tD = c;
  56497. }
  56498. }
  56499. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56500. tN = 0.0;
  56501. // recompute sc for this edge
  56502. if (-d < 0.0) {
  56503. sN = 0.0;
  56504. }
  56505. else if (-d > a)
  56506. sN = sD;
  56507. else {
  56508. sN = -d;
  56509. sD = a;
  56510. }
  56511. }
  56512. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56513. tN = tD;
  56514. // recompute sc for this edge
  56515. if ((-d + b) < 0.0) {
  56516. sN = 0;
  56517. }
  56518. else if ((-d + b) > a) {
  56519. sN = sD;
  56520. }
  56521. else {
  56522. sN = (-d + b);
  56523. sD = a;
  56524. }
  56525. }
  56526. // finally do the division to get sc and tc
  56527. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56528. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56529. // get the difference of the two closest points
  56530. var qtc = v.multiplyByFloats(tc, tc, tc);
  56531. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56532. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56533. if (isIntersected) {
  56534. return qtc.length();
  56535. }
  56536. return -1;
  56537. };
  56538. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56539. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56540. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56541. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56542. this.direction.normalize();
  56543. return this;
  56544. };
  56545. // Statics
  56546. Ray.Zero = function () {
  56547. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56548. };
  56549. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56550. var result = Ray.Zero();
  56551. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56552. };
  56553. /**
  56554. * 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
  56555. * transformed to the given world matrix.
  56556. * @param origin The origin point
  56557. * @param end The end point
  56558. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56559. */
  56560. Ray.CreateNewFromTo = function (origin, end, world) {
  56561. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56562. var direction = end.subtract(origin);
  56563. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56564. direction.normalize();
  56565. return Ray.Transform(new Ray(origin, direction, length), world);
  56566. };
  56567. Ray.Transform = function (ray, matrix) {
  56568. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56569. Ray.TransformToRef(ray, matrix, result);
  56570. return result;
  56571. };
  56572. Ray.TransformToRef = function (ray, matrix, result) {
  56573. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56574. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56575. result.length = ray.length;
  56576. var dir = result.direction;
  56577. var len = dir.length();
  56578. if (!(len === 0 || len === 1)) {
  56579. var num = 1.0 / len;
  56580. dir.x *= num;
  56581. dir.y *= num;
  56582. dir.z *= num;
  56583. result.length *= len;
  56584. }
  56585. };
  56586. Ray.smallnum = 0.00000001;
  56587. Ray.rayl = 10e8;
  56588. return Ray;
  56589. }());
  56590. BABYLON.Ray = Ray;
  56591. })(BABYLON || (BABYLON = {}));
  56592. //# sourceMappingURL=babylon.ray.js.map
  56593. var BABYLON;
  56594. (function (BABYLON) {
  56595. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56596. if (boxMin.x > sphereCenter.x + sphereRadius)
  56597. return false;
  56598. if (sphereCenter.x - sphereRadius > boxMax.x)
  56599. return false;
  56600. if (boxMin.y > sphereCenter.y + sphereRadius)
  56601. return false;
  56602. if (sphereCenter.y - sphereRadius > boxMax.y)
  56603. return false;
  56604. if (boxMin.z > sphereCenter.z + sphereRadius)
  56605. return false;
  56606. if (sphereCenter.z - sphereRadius > boxMax.z)
  56607. return false;
  56608. return true;
  56609. };
  56610. var getLowestRoot = (function () {
  56611. var result = { root: 0, found: false };
  56612. return function (a, b, c, maxR) {
  56613. result.root = 0;
  56614. result.found = false;
  56615. var determinant = b * b - 4.0 * a * c;
  56616. if (determinant < 0)
  56617. return result;
  56618. var sqrtD = Math.sqrt(determinant);
  56619. var r1 = (-b - sqrtD) / (2.0 * a);
  56620. var r2 = (-b + sqrtD) / (2.0 * a);
  56621. if (r1 > r2) {
  56622. var temp = r2;
  56623. r2 = r1;
  56624. r1 = temp;
  56625. }
  56626. if (r1 > 0 && r1 < maxR) {
  56627. result.root = r1;
  56628. result.found = true;
  56629. return result;
  56630. }
  56631. if (r2 > 0 && r2 < maxR) {
  56632. result.root = r2;
  56633. result.found = true;
  56634. return result;
  56635. }
  56636. return result;
  56637. };
  56638. })();
  56639. /** @hidden */
  56640. var Collider = /** @class */ (function () {
  56641. function Collider() {
  56642. this._collisionPoint = BABYLON.Vector3.Zero();
  56643. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56644. this._tempVector = BABYLON.Vector3.Zero();
  56645. this._tempVector2 = BABYLON.Vector3.Zero();
  56646. this._tempVector3 = BABYLON.Vector3.Zero();
  56647. this._tempVector4 = BABYLON.Vector3.Zero();
  56648. this._edge = BABYLON.Vector3.Zero();
  56649. this._baseToVertex = BABYLON.Vector3.Zero();
  56650. this._destinationPoint = BABYLON.Vector3.Zero();
  56651. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56652. this._displacementVector = BABYLON.Vector3.Zero();
  56653. /** @hidden */
  56654. this._radius = BABYLON.Vector3.One();
  56655. /** @hidden */
  56656. this._retry = 0;
  56657. /** @hidden */
  56658. this._basePointWorld = BABYLON.Vector3.Zero();
  56659. this._velocityWorld = BABYLON.Vector3.Zero();
  56660. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56661. this._collisionMask = -1;
  56662. }
  56663. Object.defineProperty(Collider.prototype, "collisionMask", {
  56664. get: function () {
  56665. return this._collisionMask;
  56666. },
  56667. set: function (mask) {
  56668. this._collisionMask = !isNaN(mask) ? mask : -1;
  56669. },
  56670. enumerable: true,
  56671. configurable: true
  56672. });
  56673. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56674. /**
  56675. * Gets the plane normal used to compute the sliding response (in local space)
  56676. */
  56677. get: function () {
  56678. return this._slidePlaneNormal;
  56679. },
  56680. enumerable: true,
  56681. configurable: true
  56682. });
  56683. // Methods
  56684. /** @hidden */
  56685. Collider.prototype._initialize = function (source, dir, e) {
  56686. this._velocity = dir;
  56687. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56688. this._basePoint = source;
  56689. source.multiplyToRef(this._radius, this._basePointWorld);
  56690. dir.multiplyToRef(this._radius, this._velocityWorld);
  56691. this._velocityWorldLength = this._velocityWorld.length();
  56692. this._epsilon = e;
  56693. this.collisionFound = false;
  56694. };
  56695. /** @hidden */
  56696. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56697. pa.subtractToRef(point, this._tempVector);
  56698. pb.subtractToRef(point, this._tempVector2);
  56699. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56700. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56701. if (d < 0)
  56702. return false;
  56703. pc.subtractToRef(point, this._tempVector3);
  56704. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56705. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56706. if (d < 0)
  56707. return false;
  56708. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56709. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56710. return d >= 0;
  56711. };
  56712. /** @hidden */
  56713. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  56714. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  56715. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  56716. if (distance > this._velocityWorldLength + max + sphereRadius) {
  56717. return false;
  56718. }
  56719. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  56720. return false;
  56721. return true;
  56722. };
  56723. /** @hidden */
  56724. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56725. var t0;
  56726. var embeddedInPlane = false;
  56727. //defensive programming, actually not needed.
  56728. if (!trianglePlaneArray) {
  56729. trianglePlaneArray = [];
  56730. }
  56731. if (!trianglePlaneArray[faceIndex]) {
  56732. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56733. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56734. }
  56735. var trianglePlane = trianglePlaneArray[faceIndex];
  56736. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56737. return;
  56738. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56739. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56740. if (normalDotVelocity == 0) {
  56741. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56742. return;
  56743. embeddedInPlane = true;
  56744. t0 = 0;
  56745. }
  56746. else {
  56747. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56748. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56749. if (t0 > t1) {
  56750. var temp = t1;
  56751. t1 = t0;
  56752. t0 = temp;
  56753. }
  56754. if (t0 > 1.0 || t1 < 0.0)
  56755. return;
  56756. if (t0 < 0)
  56757. t0 = 0;
  56758. if (t0 > 1.0)
  56759. t0 = 1.0;
  56760. }
  56761. this._collisionPoint.copyFromFloats(0, 0, 0);
  56762. var found = false;
  56763. var t = 1.0;
  56764. if (!embeddedInPlane) {
  56765. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56766. this._velocity.scaleToRef(t0, this._tempVector);
  56767. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56768. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56769. found = true;
  56770. t = t0;
  56771. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56772. }
  56773. }
  56774. if (!found) {
  56775. var velocitySquaredLength = this._velocity.lengthSquared();
  56776. var a = velocitySquaredLength;
  56777. this._basePoint.subtractToRef(p1, this._tempVector);
  56778. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56779. var c = this._tempVector.lengthSquared() - 1.0;
  56780. var lowestRoot = getLowestRoot(a, b, c, t);
  56781. if (lowestRoot.found) {
  56782. t = lowestRoot.root;
  56783. found = true;
  56784. this._collisionPoint.copyFrom(p1);
  56785. }
  56786. this._basePoint.subtractToRef(p2, this._tempVector);
  56787. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56788. c = this._tempVector.lengthSquared() - 1.0;
  56789. lowestRoot = getLowestRoot(a, b, c, t);
  56790. if (lowestRoot.found) {
  56791. t = lowestRoot.root;
  56792. found = true;
  56793. this._collisionPoint.copyFrom(p2);
  56794. }
  56795. this._basePoint.subtractToRef(p3, this._tempVector);
  56796. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56797. c = this._tempVector.lengthSquared() - 1.0;
  56798. lowestRoot = getLowestRoot(a, b, c, t);
  56799. if (lowestRoot.found) {
  56800. t = lowestRoot.root;
  56801. found = true;
  56802. this._collisionPoint.copyFrom(p3);
  56803. }
  56804. p2.subtractToRef(p1, this._edge);
  56805. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56806. var edgeSquaredLength = this._edge.lengthSquared();
  56807. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56808. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56809. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56810. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56811. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56812. lowestRoot = getLowestRoot(a, b, c, t);
  56813. if (lowestRoot.found) {
  56814. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56815. if (f >= 0.0 && f <= 1.0) {
  56816. t = lowestRoot.root;
  56817. found = true;
  56818. this._edge.scaleInPlace(f);
  56819. p1.addToRef(this._edge, this._collisionPoint);
  56820. }
  56821. }
  56822. p3.subtractToRef(p2, this._edge);
  56823. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56824. edgeSquaredLength = this._edge.lengthSquared();
  56825. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56826. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56827. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56828. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56829. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56830. lowestRoot = getLowestRoot(a, b, c, t);
  56831. if (lowestRoot.found) {
  56832. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56833. if (f >= 0.0 && f <= 1.0) {
  56834. t = lowestRoot.root;
  56835. found = true;
  56836. this._edge.scaleInPlace(f);
  56837. p2.addToRef(this._edge, this._collisionPoint);
  56838. }
  56839. }
  56840. p1.subtractToRef(p3, this._edge);
  56841. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56842. edgeSquaredLength = this._edge.lengthSquared();
  56843. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56844. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56845. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56846. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56847. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56848. lowestRoot = getLowestRoot(a, b, c, t);
  56849. if (lowestRoot.found) {
  56850. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56851. if (f >= 0.0 && f <= 1.0) {
  56852. t = lowestRoot.root;
  56853. found = true;
  56854. this._edge.scaleInPlace(f);
  56855. p3.addToRef(this._edge, this._collisionPoint);
  56856. }
  56857. }
  56858. }
  56859. if (found) {
  56860. var distToCollision = t * this._velocity.length();
  56861. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56862. if (!this.intersectionPoint) {
  56863. this.intersectionPoint = this._collisionPoint.clone();
  56864. }
  56865. else {
  56866. this.intersectionPoint.copyFrom(this._collisionPoint);
  56867. }
  56868. this._nearestDistance = distToCollision;
  56869. this.collisionFound = true;
  56870. }
  56871. }
  56872. };
  56873. /** @hidden */
  56874. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56875. for (var i = indexStart; i < indexEnd; i += 3) {
  56876. var p1 = pts[indices[i] - decal];
  56877. var p2 = pts[indices[i + 1] - decal];
  56878. var p3 = pts[indices[i + 2] - decal];
  56879. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56880. }
  56881. };
  56882. /** @hidden */
  56883. Collider.prototype._getResponse = function (pos, vel) {
  56884. pos.addToRef(vel, this._destinationPoint);
  56885. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56886. this._basePoint.addToRef(vel, pos);
  56887. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56888. this._slidePlaneNormal.normalize();
  56889. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56890. pos.addInPlace(this._displacementVector);
  56891. this.intersectionPoint.addInPlace(this._displacementVector);
  56892. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56893. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56894. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56895. };
  56896. return Collider;
  56897. }());
  56898. BABYLON.Collider = Collider;
  56899. })(BABYLON || (BABYLON = {}));
  56900. //# sourceMappingURL=babylon.collider.js.map
  56901. var BABYLON;
  56902. (function (BABYLON) {
  56903. //WebWorker code will be inserted to this variable.
  56904. /** @hidden */
  56905. BABYLON.CollisionWorker = "";
  56906. /** Defines supported task for worker process */
  56907. var WorkerTaskType;
  56908. (function (WorkerTaskType) {
  56909. /** Initialization */
  56910. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56911. /** Update of geometry */
  56912. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56913. /** Evaluate collision */
  56914. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56915. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56916. /** Defines kind of replies returned by worker */
  56917. var WorkerReplyType;
  56918. (function (WorkerReplyType) {
  56919. /** Success */
  56920. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56921. /** Unkown error */
  56922. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56923. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56924. /** @hidden */
  56925. var CollisionCoordinatorWorker = /** @class */ (function () {
  56926. function CollisionCoordinatorWorker() {
  56927. var _this = this;
  56928. this._scaledPosition = BABYLON.Vector3.Zero();
  56929. this._scaledVelocity = BABYLON.Vector3.Zero();
  56930. this.onMeshUpdated = function (transformNode) {
  56931. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56932. };
  56933. this.onGeometryUpdated = function (geometry) {
  56934. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56935. };
  56936. this._afterRender = function () {
  56937. if (!_this._init)
  56938. return;
  56939. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56940. return;
  56941. }
  56942. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56943. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56944. if (_this._runningUpdated > 4) {
  56945. return;
  56946. }
  56947. ++_this._runningUpdated;
  56948. var payload = {
  56949. updatedMeshes: _this._addUpdateMeshesList,
  56950. updatedGeometries: _this._addUpdateGeometriesList,
  56951. removedGeometries: _this._toRemoveGeometryArray,
  56952. removedMeshes: _this._toRemoveMeshesArray
  56953. };
  56954. var message = {
  56955. payload: payload,
  56956. taskType: WorkerTaskType.UPDATE
  56957. };
  56958. var serializable = [];
  56959. for (var id in payload.updatedGeometries) {
  56960. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56961. //prepare transferables
  56962. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56963. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56964. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56965. }
  56966. }
  56967. _this._worker.postMessage(message, serializable);
  56968. _this._addUpdateMeshesList = {};
  56969. _this._addUpdateGeometriesList = {};
  56970. _this._toRemoveGeometryArray = [];
  56971. _this._toRemoveMeshesArray = [];
  56972. };
  56973. this._onMessageFromWorker = function (e) {
  56974. var returnData = e.data;
  56975. if (returnData.error != WorkerReplyType.SUCCESS) {
  56976. //TODO what errors can be returned from the worker?
  56977. BABYLON.Tools.Warn("error returned from worker!");
  56978. return;
  56979. }
  56980. switch (returnData.taskType) {
  56981. case WorkerTaskType.INIT:
  56982. _this._init = true;
  56983. //Update the worked with ALL of the scene's current state
  56984. _this._scene.meshes.forEach(function (mesh) {
  56985. _this.onMeshAdded(mesh);
  56986. });
  56987. _this._scene.getGeometries().forEach(function (geometry) {
  56988. _this.onGeometryAdded(geometry);
  56989. });
  56990. break;
  56991. case WorkerTaskType.UPDATE:
  56992. _this._runningUpdated--;
  56993. break;
  56994. case WorkerTaskType.COLLIDE:
  56995. var returnPayload = returnData.payload;
  56996. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56997. return;
  56998. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56999. if (callback) {
  57000. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57001. if (mesh) {
  57002. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57003. }
  57004. }
  57005. //cleanup
  57006. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57007. break;
  57008. }
  57009. };
  57010. this._collisionsCallbackArray = [];
  57011. this._init = false;
  57012. this._runningUpdated = 0;
  57013. this._addUpdateMeshesList = {};
  57014. this._addUpdateGeometriesList = {};
  57015. this._toRemoveGeometryArray = [];
  57016. this._toRemoveMeshesArray = [];
  57017. }
  57018. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57019. if (!this._init)
  57020. return;
  57021. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57022. return;
  57023. position.divideToRef(collider._radius, this._scaledPosition);
  57024. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57025. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57026. var payload = {
  57027. collider: {
  57028. position: this._scaledPosition.asArray(),
  57029. velocity: this._scaledVelocity.asArray(),
  57030. radius: collider._radius.asArray()
  57031. },
  57032. collisionId: collisionIndex,
  57033. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57034. maximumRetry: maximumRetry
  57035. };
  57036. var message = {
  57037. payload: payload,
  57038. taskType: WorkerTaskType.COLLIDE
  57039. };
  57040. this._worker.postMessage(message);
  57041. };
  57042. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57043. this._scene = scene;
  57044. this._scene.registerAfterRender(this._afterRender);
  57045. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57046. this._worker = new Worker(workerUrl);
  57047. this._worker.onmessage = this._onMessageFromWorker;
  57048. var message = {
  57049. payload: {},
  57050. taskType: WorkerTaskType.INIT
  57051. };
  57052. this._worker.postMessage(message);
  57053. };
  57054. CollisionCoordinatorWorker.prototype.destroy = function () {
  57055. this._scene.unregisterAfterRender(this._afterRender);
  57056. this._worker.terminate();
  57057. };
  57058. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57059. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57060. this.onMeshUpdated(mesh);
  57061. };
  57062. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57063. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57064. };
  57065. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57066. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57067. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57068. this.onGeometryUpdated(geometry);
  57069. };
  57070. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57071. this._toRemoveGeometryArray.push(geometry.id);
  57072. };
  57073. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57074. var submeshes = [];
  57075. if (mesh.subMeshes) {
  57076. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57077. var boundingInfo = sm.getBoundingInfo();
  57078. return {
  57079. position: idx,
  57080. verticesStart: sm.verticesStart,
  57081. verticesCount: sm.verticesCount,
  57082. indexStart: sm.indexStart,
  57083. indexCount: sm.indexCount,
  57084. hasMaterial: !!sm.getMaterial(),
  57085. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57086. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57087. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57088. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57089. };
  57090. });
  57091. }
  57092. var geometryId = null;
  57093. if (mesh instanceof BABYLON.Mesh) {
  57094. var geometry = mesh.geometry;
  57095. geometryId = geometry ? geometry.id : null;
  57096. }
  57097. else if (mesh instanceof BABYLON.InstancedMesh) {
  57098. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57099. geometryId = geometry ? geometry.id : null;
  57100. }
  57101. var boundingInfo = mesh.getBoundingInfo();
  57102. return {
  57103. uniqueId: mesh.uniqueId,
  57104. id: mesh.id,
  57105. name: mesh.name,
  57106. geometryId: geometryId,
  57107. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57108. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57109. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57110. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57111. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57112. subMeshes: submeshes,
  57113. checkCollisions: mesh.checkCollisions
  57114. };
  57115. };
  57116. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57117. return {
  57118. id: geometry.id,
  57119. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57120. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57121. indices: new Uint32Array(geometry.getIndices() || []),
  57122. };
  57123. };
  57124. return CollisionCoordinatorWorker;
  57125. }());
  57126. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57127. /** @hidden */
  57128. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57129. function CollisionCoordinatorLegacy() {
  57130. this._scaledPosition = BABYLON.Vector3.Zero();
  57131. this._scaledVelocity = BABYLON.Vector3.Zero();
  57132. this._finalPosition = BABYLON.Vector3.Zero();
  57133. }
  57134. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57135. position.divideToRef(collider._radius, this._scaledPosition);
  57136. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57137. collider.collidedMesh = null;
  57138. collider._retry = 0;
  57139. collider._initialVelocity = this._scaledVelocity;
  57140. collider._initialPosition = this._scaledPosition;
  57141. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57142. this._finalPosition.multiplyInPlace(collider._radius);
  57143. //run the callback
  57144. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57145. };
  57146. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57147. this._scene = scene;
  57148. };
  57149. CollisionCoordinatorLegacy.prototype.destroy = function () {
  57150. //Legacy need no destruction method.
  57151. };
  57152. //No update in legacy mode
  57153. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  57154. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  57155. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  57156. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  57157. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  57158. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  57159. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  57160. if (excludedMesh === void 0) { excludedMesh = null; }
  57161. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  57162. if (collider._retry >= maximumRetry) {
  57163. finalPosition.copyFrom(position);
  57164. return;
  57165. }
  57166. // Check if this is a mesh else camera or -1
  57167. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  57168. collider._initialize(position, velocity, closeDistance);
  57169. // Check all meshes
  57170. for (var index = 0; index < this._scene.meshes.length; index++) {
  57171. var mesh = this._scene.meshes[index];
  57172. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  57173. mesh._checkCollision(collider);
  57174. }
  57175. }
  57176. if (!collider.collisionFound) {
  57177. position.addToRef(velocity, finalPosition);
  57178. return;
  57179. }
  57180. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  57181. collider._getResponse(position, velocity);
  57182. }
  57183. if (velocity.length() <= closeDistance) {
  57184. finalPosition.copyFrom(position);
  57185. return;
  57186. }
  57187. collider._retry++;
  57188. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  57189. };
  57190. return CollisionCoordinatorLegacy;
  57191. }());
  57192. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  57193. })(BABYLON || (BABYLON = {}));
  57194. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  57195. var BABYLON;
  57196. (function (BABYLON) {
  57197. /**
  57198. * A particle represents one of the element emitted by a particle system.
  57199. * This is mainly define by its coordinates, direction, velocity and age.
  57200. */
  57201. var Particle = /** @class */ (function () {
  57202. /**
  57203. * Creates a new instance Particle
  57204. * @param particleSystem the particle system the particle belongs to
  57205. */
  57206. function Particle(
  57207. /**
  57208. * The particle system the particle belongs to.
  57209. */
  57210. particleSystem) {
  57211. this.particleSystem = particleSystem;
  57212. /**
  57213. * The world position of the particle in the scene.
  57214. */
  57215. this.position = BABYLON.Vector3.Zero();
  57216. /**
  57217. * The world direction of the particle in the scene.
  57218. */
  57219. this.direction = BABYLON.Vector3.Zero();
  57220. /**
  57221. * The color of the particle.
  57222. */
  57223. this.color = new BABYLON.Color4(0, 0, 0, 0);
  57224. /**
  57225. * The color change of the particle per step.
  57226. */
  57227. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  57228. /**
  57229. * Defines how long will the life of the particle be.
  57230. */
  57231. this.lifeTime = 1.0;
  57232. /**
  57233. * The current age of the particle.
  57234. */
  57235. this.age = 0;
  57236. /**
  57237. * The current size of the particle.
  57238. */
  57239. this.size = 0;
  57240. /**
  57241. * The current scale of the particle.
  57242. */
  57243. this.scale = new BABYLON.Vector2(1, 1);
  57244. /**
  57245. * The current angle of the particle.
  57246. */
  57247. this.angle = 0;
  57248. /**
  57249. * Defines how fast is the angle changing.
  57250. */
  57251. this.angularSpeed = 0;
  57252. /**
  57253. * Defines the cell index used by the particle to be rendered from a sprite.
  57254. */
  57255. this.cellIndex = 0;
  57256. /** @hidden */
  57257. this._attachedSubEmitters = null;
  57258. /** @hidden */
  57259. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  57260. /** @hidden */
  57261. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  57262. /** @hidden */
  57263. this._currentSize1 = 0;
  57264. /** @hidden */
  57265. this._currentSize2 = 0;
  57266. /** @hidden */
  57267. this._currentAngularSpeed1 = 0;
  57268. /** @hidden */
  57269. this._currentAngularSpeed2 = 0;
  57270. /** @hidden */
  57271. this._currentVelocity1 = 0;
  57272. /** @hidden */
  57273. this._currentVelocity2 = 0;
  57274. /** @hidden */
  57275. this._currentLimitVelocity1 = 0;
  57276. /** @hidden */
  57277. this._currentLimitVelocity2 = 0;
  57278. /** @hidden */
  57279. this._currentDrag1 = 0;
  57280. /** @hidden */
  57281. this._currentDrag2 = 0;
  57282. this.id = Particle._Count++;
  57283. if (!this.particleSystem.isAnimationSheetEnabled) {
  57284. return;
  57285. }
  57286. this.updateCellInfoFromSystem();
  57287. }
  57288. Particle.prototype.updateCellInfoFromSystem = function () {
  57289. this.cellIndex = this.particleSystem.startSpriteCellID;
  57290. };
  57291. /**
  57292. * Defines how the sprite cell index is updated for the particle
  57293. */
  57294. Particle.prototype.updateCellIndex = function () {
  57295. var offsetAge = this.age;
  57296. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  57297. if (this.particleSystem.spriteRandomStartCell) {
  57298. if (this._randomCellOffset === undefined) {
  57299. this._randomCellOffset = Math.random() * this.lifeTime;
  57300. }
  57301. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  57302. changeSpeed = 1;
  57303. offsetAge = this._randomCellOffset;
  57304. }
  57305. else {
  57306. offsetAge += this._randomCellOffset;
  57307. }
  57308. }
  57309. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  57310. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  57311. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  57312. };
  57313. /** @hidden */
  57314. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  57315. if (subEmitter.particleSystem.emitter.position) {
  57316. var emitterMesh = subEmitter.particleSystem.emitter;
  57317. emitterMesh.position.copyFrom(this.position);
  57318. if (subEmitter.inheritDirection) {
  57319. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  57320. // Look at using Y as forward
  57321. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  57322. }
  57323. }
  57324. else {
  57325. var emitterPosition = subEmitter.particleSystem.emitter;
  57326. emitterPosition.copyFrom(this.position);
  57327. }
  57328. // Set inheritedVelocityOffset to be used when new particles are created
  57329. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  57330. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  57331. };
  57332. /** @hidden */
  57333. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  57334. var _this = this;
  57335. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  57336. this._attachedSubEmitters.forEach(function (subEmitter) {
  57337. _this._inheritParticleInfoToSubEmitter(subEmitter);
  57338. });
  57339. }
  57340. };
  57341. /** @hidden */
  57342. Particle.prototype._reset = function () {
  57343. this.age = 0;
  57344. this._currentColorGradient = null;
  57345. this._currentSizeGradient = null;
  57346. this._currentAngularSpeedGradient = null;
  57347. this._currentVelocityGradient = null;
  57348. this._currentLimitVelocityGradient = null;
  57349. this._currentDragGradient = null;
  57350. this.cellIndex = this.particleSystem.startSpriteCellID;
  57351. this._randomCellOffset = undefined;
  57352. };
  57353. /**
  57354. * Copy the properties of particle to another one.
  57355. * @param other the particle to copy the information to.
  57356. */
  57357. Particle.prototype.copyTo = function (other) {
  57358. other.position.copyFrom(this.position);
  57359. if (this._initialDirection) {
  57360. if (other._initialDirection) {
  57361. other._initialDirection.copyFrom(this._initialDirection);
  57362. }
  57363. else {
  57364. other._initialDirection = this._initialDirection.clone();
  57365. }
  57366. }
  57367. else {
  57368. other._initialDirection = null;
  57369. }
  57370. other.direction.copyFrom(this.direction);
  57371. other.color.copyFrom(this.color);
  57372. other.colorStep.copyFrom(this.colorStep);
  57373. other.lifeTime = this.lifeTime;
  57374. other.age = this.age;
  57375. other._randomCellOffset = this._randomCellOffset;
  57376. other.size = this.size;
  57377. other.scale.copyFrom(this.scale);
  57378. other.angle = this.angle;
  57379. other.angularSpeed = this.angularSpeed;
  57380. other.particleSystem = this.particleSystem;
  57381. other.cellIndex = this.cellIndex;
  57382. other.id = this.id;
  57383. other._attachedSubEmitters = this._attachedSubEmitters;
  57384. if (this._currentColorGradient) {
  57385. other._currentColorGradient = this._currentColorGradient;
  57386. other._currentColor1.copyFrom(this._currentColor1);
  57387. other._currentColor2.copyFrom(this._currentColor2);
  57388. }
  57389. if (this._currentSizeGradient) {
  57390. other._currentSizeGradient = this._currentSizeGradient;
  57391. other._currentSize1 = this._currentSize1;
  57392. other._currentSize2 = this._currentSize2;
  57393. }
  57394. if (this._currentAngularSpeedGradient) {
  57395. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  57396. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  57397. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  57398. }
  57399. if (this._currentVelocityGradient) {
  57400. other._currentVelocityGradient = this._currentVelocityGradient;
  57401. other._currentVelocity1 = this._currentVelocity1;
  57402. other._currentVelocity2 = this._currentVelocity2;
  57403. }
  57404. if (this._currentLimitVelocityGradient) {
  57405. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  57406. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  57407. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  57408. }
  57409. if (this._currentDragGradient) {
  57410. other._currentDragGradient = this._currentDragGradient;
  57411. other._currentDrag1 = this._currentDrag1;
  57412. other._currentDrag2 = this._currentDrag2;
  57413. }
  57414. if (this.particleSystem.isAnimationSheetEnabled) {
  57415. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  57416. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  57417. }
  57418. if (this.particleSystem.useRampGradients) {
  57419. other.remapData.copyFrom(this.remapData);
  57420. }
  57421. if (this._randomNoiseCoordinates1) {
  57422. if (other._randomNoiseCoordinates1) {
  57423. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  57424. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  57425. }
  57426. else {
  57427. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  57428. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  57429. }
  57430. }
  57431. };
  57432. Particle._Count = 0;
  57433. return Particle;
  57434. }());
  57435. BABYLON.Particle = Particle;
  57436. })(BABYLON || (BABYLON = {}));
  57437. //# sourceMappingURL=babylon.particle.js.map
  57438. var BABYLON;
  57439. (function (BABYLON) {
  57440. /**
  57441. * This represents the base class for particle system in Babylon.
  57442. * 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.
  57443. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57444. * @example https://doc.babylonjs.com/babylon101/particles
  57445. */
  57446. var BaseParticleSystem = /** @class */ (function () {
  57447. /**
  57448. * Instantiates a particle system.
  57449. * 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.
  57450. * @param name The name of the particle system
  57451. */
  57452. function BaseParticleSystem(name) {
  57453. /**
  57454. * List of animations used by the particle system.
  57455. */
  57456. this.animations = [];
  57457. /**
  57458. * The rendering group used by the Particle system to chose when to render.
  57459. */
  57460. this.renderingGroupId = 0;
  57461. /**
  57462. * The emitter represents the Mesh or position we are attaching the particle system to.
  57463. */
  57464. this.emitter = null;
  57465. /**
  57466. * The maximum number of particles to emit per frame
  57467. */
  57468. this.emitRate = 10;
  57469. /**
  57470. * If you want to launch only a few particles at once, that can be done, as well.
  57471. */
  57472. this.manualEmitCount = -1;
  57473. /**
  57474. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57475. */
  57476. this.updateSpeed = 0.01;
  57477. /**
  57478. * The amount of time the particle system is running (depends of the overall update speed).
  57479. */
  57480. this.targetStopDuration = 0;
  57481. /**
  57482. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  57483. */
  57484. this.disposeOnStop = false;
  57485. /**
  57486. * Minimum power of emitting particles.
  57487. */
  57488. this.minEmitPower = 1;
  57489. /**
  57490. * Maximum power of emitting particles.
  57491. */
  57492. this.maxEmitPower = 1;
  57493. /**
  57494. * Minimum life time of emitting particles.
  57495. */
  57496. this.minLifeTime = 1;
  57497. /**
  57498. * Maximum life time of emitting particles.
  57499. */
  57500. this.maxLifeTime = 1;
  57501. /**
  57502. * Minimum Size of emitting particles.
  57503. */
  57504. this.minSize = 1;
  57505. /**
  57506. * Maximum Size of emitting particles.
  57507. */
  57508. this.maxSize = 1;
  57509. /**
  57510. * Minimum scale of emitting particles on X axis.
  57511. */
  57512. this.minScaleX = 1;
  57513. /**
  57514. * Maximum scale of emitting particles on X axis.
  57515. */
  57516. this.maxScaleX = 1;
  57517. /**
  57518. * Minimum scale of emitting particles on Y axis.
  57519. */
  57520. this.minScaleY = 1;
  57521. /**
  57522. * Maximum scale of emitting particles on Y axis.
  57523. */
  57524. this.maxScaleY = 1;
  57525. /**
  57526. * Gets or sets the minimal initial rotation in radians.
  57527. */
  57528. this.minInitialRotation = 0;
  57529. /**
  57530. * Gets or sets the maximal initial rotation in radians.
  57531. */
  57532. this.maxInitialRotation = 0;
  57533. /**
  57534. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57535. */
  57536. this.minAngularSpeed = 0;
  57537. /**
  57538. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57539. */
  57540. this.maxAngularSpeed = 0;
  57541. /**
  57542. * The layer mask we are rendering the particles through.
  57543. */
  57544. this.layerMask = 0x0FFFFFFF;
  57545. /**
  57546. * This can help using your own shader to render the particle system.
  57547. * The according effect will be created
  57548. */
  57549. this.customShader = null;
  57550. /**
  57551. * By default particle system starts as soon as they are created. This prevents the
  57552. * automatic start to happen and let you decide when to start emitting particles.
  57553. */
  57554. this.preventAutoStart = false;
  57555. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57556. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57557. /**
  57558. * Callback triggered when the particle animation is ending.
  57559. */
  57560. this.onAnimationEnd = null;
  57561. /**
  57562. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57563. */
  57564. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57565. /**
  57566. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57567. * to override the particles.
  57568. */
  57569. this.forceDepthWrite = false;
  57570. /** 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 */
  57571. this.preWarmCycles = 0;
  57572. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57573. this.preWarmStepOffset = 1;
  57574. /**
  57575. * 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)
  57576. */
  57577. this.spriteCellChangeSpeed = 1;
  57578. /**
  57579. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57580. */
  57581. this.startSpriteCellID = 0;
  57582. /**
  57583. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57584. */
  57585. this.endSpriteCellID = 0;
  57586. /**
  57587. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57588. */
  57589. this.spriteCellWidth = 0;
  57590. /**
  57591. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57592. */
  57593. this.spriteCellHeight = 0;
  57594. /**
  57595. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57596. */
  57597. this.spriteRandomStartCell = false;
  57598. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57599. this.translationPivot = new BABYLON.Vector2(0, 0);
  57600. /**
  57601. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57602. */
  57603. this.beginAnimationOnStart = false;
  57604. /**
  57605. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57606. */
  57607. this.beginAnimationFrom = 0;
  57608. /**
  57609. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57610. */
  57611. this.beginAnimationTo = 60;
  57612. /**
  57613. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57614. */
  57615. this.beginAnimationLoop = false;
  57616. /**
  57617. * You can use gravity if you want to give an orientation to your particles.
  57618. */
  57619. this.gravity = BABYLON.Vector3.Zero();
  57620. this._colorGradients = null;
  57621. this._sizeGradients = null;
  57622. this._lifeTimeGradients = null;
  57623. this._angularSpeedGradients = null;
  57624. this._velocityGradients = null;
  57625. this._limitVelocityGradients = null;
  57626. this._dragGradients = null;
  57627. this._emitRateGradients = null;
  57628. this._startSizeGradients = null;
  57629. this._rampGradients = null;
  57630. this._colorRemapGradients = null;
  57631. this._alphaRemapGradients = null;
  57632. /**
  57633. * Defines the delay in milliseconds before starting the system (0 by default)
  57634. */
  57635. this.startDelay = 0;
  57636. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57637. this.limitVelocityDamping = 0.4;
  57638. /**
  57639. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57640. */
  57641. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57642. /**
  57643. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57644. */
  57645. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57646. /**
  57647. * Color the particle will have at the end of its lifetime
  57648. */
  57649. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57650. /**
  57651. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57652. */
  57653. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57654. /** @hidden */
  57655. this._isSubEmitter = false;
  57656. /**
  57657. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57658. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57659. */
  57660. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57661. this._isBillboardBased = true;
  57662. /**
  57663. * Local cache of defines for image processing.
  57664. */
  57665. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57666. this.id = name;
  57667. this.name = name;
  57668. }
  57669. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57670. /**
  57671. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57672. */
  57673. get: function () {
  57674. return this._isAnimationSheetEnabled;
  57675. },
  57676. set: function (value) {
  57677. if (this._isAnimationSheetEnabled == value) {
  57678. return;
  57679. }
  57680. this._isAnimationSheetEnabled = value;
  57681. this._reset();
  57682. },
  57683. enumerable: true,
  57684. configurable: true
  57685. });
  57686. /**
  57687. * Get hosting scene
  57688. * @returns the scene
  57689. */
  57690. BaseParticleSystem.prototype.getScene = function () {
  57691. return this._scene;
  57692. };
  57693. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57694. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57695. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57696. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57697. };
  57698. /**
  57699. * Gets the current list of drag gradients.
  57700. * You must use addDragGradient and removeDragGradient to udpate this list
  57701. * @returns the list of drag gradients
  57702. */
  57703. BaseParticleSystem.prototype.getDragGradients = function () {
  57704. return this._dragGradients;
  57705. };
  57706. /**
  57707. * Gets the current list of limit velocity gradients.
  57708. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57709. * @returns the list of limit velocity gradients
  57710. */
  57711. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57712. return this._limitVelocityGradients;
  57713. };
  57714. /**
  57715. * Gets the current list of color gradients.
  57716. * You must use addColorGradient and removeColorGradient to udpate this list
  57717. * @returns the list of color gradients
  57718. */
  57719. BaseParticleSystem.prototype.getColorGradients = function () {
  57720. return this._colorGradients;
  57721. };
  57722. /**
  57723. * Gets the current list of size gradients.
  57724. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57725. * @returns the list of size gradients
  57726. */
  57727. BaseParticleSystem.prototype.getSizeGradients = function () {
  57728. return this._sizeGradients;
  57729. };
  57730. /**
  57731. * Gets the current list of color remap gradients.
  57732. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57733. * @returns the list of color remap gradients
  57734. */
  57735. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57736. return this._colorRemapGradients;
  57737. };
  57738. /**
  57739. * Gets the current list of alpha remap gradients.
  57740. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57741. * @returns the list of alpha remap gradients
  57742. */
  57743. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57744. return this._alphaRemapGradients;
  57745. };
  57746. /**
  57747. * Gets the current list of life time gradients.
  57748. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57749. * @returns the list of life time gradients
  57750. */
  57751. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57752. return this._lifeTimeGradients;
  57753. };
  57754. /**
  57755. * Gets the current list of angular speed gradients.
  57756. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57757. * @returns the list of angular speed gradients
  57758. */
  57759. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57760. return this._angularSpeedGradients;
  57761. };
  57762. /**
  57763. * Gets the current list of velocity gradients.
  57764. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57765. * @returns the list of velocity gradients
  57766. */
  57767. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57768. return this._velocityGradients;
  57769. };
  57770. /**
  57771. * Gets the current list of start size gradients.
  57772. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57773. * @returns the list of start size gradients
  57774. */
  57775. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57776. return this._startSizeGradients;
  57777. };
  57778. /**
  57779. * Gets the current list of emit rate gradients.
  57780. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57781. * @returns the list of emit rate gradients
  57782. */
  57783. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57784. return this._emitRateGradients;
  57785. };
  57786. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57787. /**
  57788. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57789. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57790. */
  57791. get: function () {
  57792. if (this.particleEmitterType.direction1) {
  57793. return this.particleEmitterType.direction1;
  57794. }
  57795. return BABYLON.Vector3.Zero();
  57796. },
  57797. set: function (value) {
  57798. if (this.particleEmitterType.direction1) {
  57799. this.particleEmitterType.direction1 = value;
  57800. }
  57801. },
  57802. enumerable: true,
  57803. configurable: true
  57804. });
  57805. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57806. /**
  57807. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57808. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57809. */
  57810. get: function () {
  57811. if (this.particleEmitterType.direction2) {
  57812. return this.particleEmitterType.direction2;
  57813. }
  57814. return BABYLON.Vector3.Zero();
  57815. },
  57816. set: function (value) {
  57817. if (this.particleEmitterType.direction2) {
  57818. this.particleEmitterType.direction2 = value;
  57819. }
  57820. },
  57821. enumerable: true,
  57822. configurable: true
  57823. });
  57824. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57825. /**
  57826. * 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.
  57827. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57828. */
  57829. get: function () {
  57830. if (this.particleEmitterType.minEmitBox) {
  57831. return this.particleEmitterType.minEmitBox;
  57832. }
  57833. return BABYLON.Vector3.Zero();
  57834. },
  57835. set: function (value) {
  57836. if (this.particleEmitterType.minEmitBox) {
  57837. this.particleEmitterType.minEmitBox = value;
  57838. }
  57839. },
  57840. enumerable: true,
  57841. configurable: true
  57842. });
  57843. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57844. /**
  57845. * 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.
  57846. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57847. */
  57848. get: function () {
  57849. if (this.particleEmitterType.maxEmitBox) {
  57850. return this.particleEmitterType.maxEmitBox;
  57851. }
  57852. return BABYLON.Vector3.Zero();
  57853. },
  57854. set: function (value) {
  57855. if (this.particleEmitterType.maxEmitBox) {
  57856. this.particleEmitterType.maxEmitBox = value;
  57857. }
  57858. },
  57859. enumerable: true,
  57860. configurable: true
  57861. });
  57862. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57863. /**
  57864. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57865. */
  57866. get: function () {
  57867. return this._isBillboardBased;
  57868. },
  57869. set: function (value) {
  57870. if (this._isBillboardBased === value) {
  57871. return;
  57872. }
  57873. this._isBillboardBased = value;
  57874. this._reset();
  57875. },
  57876. enumerable: true,
  57877. configurable: true
  57878. });
  57879. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57880. /**
  57881. * Gets the image processing configuration used either in this material.
  57882. */
  57883. get: function () {
  57884. return this._imageProcessingConfiguration;
  57885. },
  57886. /**
  57887. * Sets the Default image processing configuration used either in the this material.
  57888. *
  57889. * If sets to null, the scene one is in use.
  57890. */
  57891. set: function (value) {
  57892. this._attachImageProcessingConfiguration(value);
  57893. },
  57894. enumerable: true,
  57895. configurable: true
  57896. });
  57897. /**
  57898. * Attaches a new image processing configuration to the Standard Material.
  57899. * @param configuration
  57900. */
  57901. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57902. if (configuration === this._imageProcessingConfiguration) {
  57903. return;
  57904. }
  57905. // Pick the scene configuration if needed.
  57906. if (!configuration) {
  57907. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57908. }
  57909. else {
  57910. this._imageProcessingConfiguration = configuration;
  57911. }
  57912. };
  57913. /** @hidden */
  57914. BaseParticleSystem.prototype._reset = function () {
  57915. };
  57916. /** @hidden */
  57917. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57918. if (!gradients) {
  57919. return this;
  57920. }
  57921. var index = 0;
  57922. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57923. var valueGradient = gradients_1[_i];
  57924. if (valueGradient.gradient === gradient) {
  57925. gradients.splice(index, 1);
  57926. break;
  57927. }
  57928. index++;
  57929. }
  57930. if (texture) {
  57931. texture.dispose();
  57932. }
  57933. return this;
  57934. };
  57935. /**
  57936. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57937. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57938. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57939. * @returns the emitter
  57940. */
  57941. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57942. var particleEmitter = new BABYLON.PointParticleEmitter();
  57943. particleEmitter.direction1 = direction1;
  57944. particleEmitter.direction2 = direction2;
  57945. this.particleEmitterType = particleEmitter;
  57946. return particleEmitter;
  57947. };
  57948. /**
  57949. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57950. * @param radius The radius of the hemisphere to emit from
  57951. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57952. * @returns the emitter
  57953. */
  57954. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57955. if (radius === void 0) { radius = 1; }
  57956. if (radiusRange === void 0) { radiusRange = 1; }
  57957. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57958. this.particleEmitterType = particleEmitter;
  57959. return particleEmitter;
  57960. };
  57961. /**
  57962. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57963. * @param radius The radius of the sphere to emit from
  57964. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57965. * @returns the emitter
  57966. */
  57967. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57968. if (radius === void 0) { radius = 1; }
  57969. if (radiusRange === void 0) { radiusRange = 1; }
  57970. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57971. this.particleEmitterType = particleEmitter;
  57972. return particleEmitter;
  57973. };
  57974. /**
  57975. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57976. * @param radius The radius of the sphere to emit from
  57977. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57978. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57979. * @returns the emitter
  57980. */
  57981. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57982. if (radius === void 0) { radius = 1; }
  57983. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57984. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57985. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57986. this.particleEmitterType = particleEmitter;
  57987. return particleEmitter;
  57988. };
  57989. /**
  57990. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57991. * @param radius The radius of the emission cylinder
  57992. * @param height The height of the emission cylinder
  57993. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57994. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57995. * @returns the emitter
  57996. */
  57997. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57998. if (radius === void 0) { radius = 1; }
  57999. if (height === void 0) { height = 1; }
  58000. if (radiusRange === void 0) { radiusRange = 1; }
  58001. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58002. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58003. this.particleEmitterType = particleEmitter;
  58004. return particleEmitter;
  58005. };
  58006. /**
  58007. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58008. * @param radius The radius of the cylinder to emit from
  58009. * @param height The height of the emission cylinder
  58010. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58011. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58012. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58013. * @returns the emitter
  58014. */
  58015. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58016. if (radius === void 0) { radius = 1; }
  58017. if (height === void 0) { height = 1; }
  58018. if (radiusRange === void 0) { radiusRange = 1; }
  58019. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58020. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58021. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58022. this.particleEmitterType = particleEmitter;
  58023. return particleEmitter;
  58024. };
  58025. /**
  58026. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58027. * @param radius The radius of the cone to emit from
  58028. * @param angle The base angle of the cone
  58029. * @returns the emitter
  58030. */
  58031. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58032. if (radius === void 0) { radius = 1; }
  58033. if (angle === void 0) { angle = Math.PI / 4; }
  58034. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58035. this.particleEmitterType = particleEmitter;
  58036. return particleEmitter;
  58037. };
  58038. /**
  58039. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58040. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58041. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58042. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58043. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58044. * @returns the emitter
  58045. */
  58046. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58047. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58048. this.particleEmitterType = particleEmitter;
  58049. this.direction1 = direction1;
  58050. this.direction2 = direction2;
  58051. this.minEmitBox = minEmitBox;
  58052. this.maxEmitBox = maxEmitBox;
  58053. return particleEmitter;
  58054. };
  58055. /**
  58056. * Source color is added to the destination color without alpha affecting the result
  58057. */
  58058. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58059. /**
  58060. * Blend current color and particle color using particle’s alpha
  58061. */
  58062. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58063. /**
  58064. * Add current color and particle color multiplied by particle’s alpha
  58065. */
  58066. BaseParticleSystem.BLENDMODE_ADD = 2;
  58067. /**
  58068. * Multiply current color with particle color
  58069. */
  58070. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58071. /**
  58072. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58073. */
  58074. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58075. return BaseParticleSystem;
  58076. }());
  58077. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58078. })(BABYLON || (BABYLON = {}));
  58079. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58080. var BABYLON;
  58081. (function (BABYLON) {
  58082. /**
  58083. * This represents a particle system in Babylon.
  58084. * 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.
  58085. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58086. * @example https://doc.babylonjs.com/babylon101/particles
  58087. */
  58088. var ParticleSystem = /** @class */ (function (_super) {
  58089. __extends(ParticleSystem, _super);
  58090. /**
  58091. * Instantiates a particle system.
  58092. * 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.
  58093. * @param name The name of the particle system
  58094. * @param capacity The max number of particles alive at the same time
  58095. * @param scene The scene the particle system belongs to
  58096. * @param customEffect a custom effect used to change the way particles are rendered by default
  58097. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58098. * @param epsilon Offset used to render the particles
  58099. */
  58100. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58101. if (customEffect === void 0) { customEffect = null; }
  58102. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58103. if (epsilon === void 0) { epsilon = 0.01; }
  58104. var _this = _super.call(this, name) || this;
  58105. /**
  58106. * @hidden
  58107. */
  58108. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58109. /**
  58110. * An event triggered when the system is disposed
  58111. */
  58112. _this.onDisposeObservable = new BABYLON.Observable();
  58113. _this._particles = new Array();
  58114. _this._stockParticles = new Array();
  58115. _this._newPartsExcess = 0;
  58116. _this._vertexBuffers = {};
  58117. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58118. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58119. _this._scaledDirection = BABYLON.Vector3.Zero();
  58120. _this._scaledGravity = BABYLON.Vector3.Zero();
  58121. _this._currentRenderId = -1;
  58122. _this._useInstancing = false;
  58123. _this._started = false;
  58124. _this._stopped = false;
  58125. _this._actualFrame = 0;
  58126. /** @hidden */
  58127. _this._currentEmitRate1 = 0;
  58128. /** @hidden */
  58129. _this._currentEmitRate2 = 0;
  58130. /** @hidden */
  58131. _this._currentStartSize1 = 0;
  58132. /** @hidden */
  58133. _this._currentStartSize2 = 0;
  58134. _this._rawTextureWidth = 256;
  58135. _this._useRampGradients = false;
  58136. /**
  58137. * @hidden
  58138. * If the particle systems emitter should be disposed when the particle system is disposed
  58139. */
  58140. _this._disposeEmitterOnDispose = false;
  58141. // start of sub system methods
  58142. /**
  58143. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58144. * Its lifetime will start back at 0.
  58145. */
  58146. _this.recycleParticle = function (particle) {
  58147. // move particle from activeParticle list to stock particles
  58148. var lastParticle = _this._particles.pop();
  58149. if (lastParticle !== particle) {
  58150. lastParticle.copyTo(particle);
  58151. }
  58152. _this._stockParticles.push(lastParticle);
  58153. };
  58154. _this._createParticle = function () {
  58155. var particle;
  58156. if (_this._stockParticles.length !== 0) {
  58157. particle = _this._stockParticles.pop();
  58158. particle._reset();
  58159. }
  58160. else {
  58161. particle = new BABYLON.Particle(_this);
  58162. }
  58163. // Attach emitters
  58164. if (_this._subEmitters && _this._subEmitters.length > 0) {
  58165. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  58166. particle._attachedSubEmitters = [];
  58167. subEmitters.forEach(function (subEmitter) {
  58168. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  58169. var newEmitter = subEmitter.clone();
  58170. particle._attachedSubEmitters.push(newEmitter);
  58171. newEmitter.particleSystem.start();
  58172. }
  58173. });
  58174. }
  58175. return particle;
  58176. };
  58177. _this._emitFromParticle = function (particle) {
  58178. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  58179. return;
  58180. }
  58181. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  58182. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  58183. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  58184. var subSystem = subEmitter.clone();
  58185. particle._inheritParticleInfoToSubEmitter(subSystem);
  58186. subSystem.particleSystem._rootParticleSystem = _this;
  58187. _this.activeSubSystems.push(subSystem.particleSystem);
  58188. subSystem.particleSystem.start();
  58189. }
  58190. });
  58191. };
  58192. _this._capacity = capacity;
  58193. _this._epsilon = epsilon;
  58194. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  58195. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58196. // Setup the default processing configuration to the scene.
  58197. _this._attachImageProcessingConfiguration(null);
  58198. _this._customEffect = customEffect;
  58199. _this._scene.particleSystems.push(_this);
  58200. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  58201. _this._createIndexBuffer();
  58202. _this._createVertexBuffers();
  58203. // Default emitter type
  58204. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  58205. // Update
  58206. _this.updateFunction = function (particles) {
  58207. var noiseTextureSize = null;
  58208. var noiseTextureData = null;
  58209. if (_this.noiseTexture) { // We need to get texture data back to CPU
  58210. noiseTextureSize = _this.noiseTexture.getSize();
  58211. noiseTextureData = (_this.noiseTexture.getContent());
  58212. }
  58213. var _loop_1 = function () {
  58214. particle = particles[index];
  58215. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  58216. var previousAge = particle.age;
  58217. particle.age += scaledUpdateSpeed;
  58218. // Evaluate step to death
  58219. if (particle.age > particle.lifeTime) {
  58220. var diff = particle.age - previousAge;
  58221. var oldDiff = particle.lifeTime - previousAge;
  58222. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  58223. particle.age = particle.lifeTime;
  58224. }
  58225. var ratio = particle.age / particle.lifeTime;
  58226. // Color
  58227. if (_this._colorGradients && _this._colorGradients.length > 0) {
  58228. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  58229. if (currentGradient !== particle._currentColorGradient) {
  58230. particle._currentColor1.copyFrom(particle._currentColor2);
  58231. nextGradient.getColorToRef(particle._currentColor2);
  58232. particle._currentColorGradient = currentGradient;
  58233. }
  58234. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  58235. });
  58236. }
  58237. else {
  58238. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  58239. particle.color.addInPlace(_this._scaledColorStep);
  58240. if (particle.color.a < 0) {
  58241. particle.color.a = 0;
  58242. }
  58243. }
  58244. // Angular speed
  58245. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  58246. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  58247. if (currentGradient !== particle._currentAngularSpeedGradient) {
  58248. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  58249. particle._currentAngularSpeed2 = nextGradient.getFactor();
  58250. particle._currentAngularSpeedGradient = currentGradient;
  58251. }
  58252. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  58253. });
  58254. }
  58255. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  58256. // Direction
  58257. var directionScale = scaledUpdateSpeed;
  58258. /// Velocity
  58259. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  58260. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  58261. if (currentGradient !== particle._currentVelocityGradient) {
  58262. particle._currentVelocity1 = particle._currentVelocity2;
  58263. particle._currentVelocity2 = nextGradient.getFactor();
  58264. particle._currentVelocityGradient = currentGradient;
  58265. }
  58266. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  58267. });
  58268. }
  58269. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  58270. /// Limit velocity
  58271. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  58272. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  58273. if (currentGradient !== particle._currentLimitVelocityGradient) {
  58274. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  58275. particle._currentLimitVelocity2 = nextGradient.getFactor();
  58276. particle._currentLimitVelocityGradient = currentGradient;
  58277. }
  58278. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  58279. var currentVelocity = particle.direction.length();
  58280. if (currentVelocity > limitVelocity) {
  58281. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  58282. }
  58283. });
  58284. }
  58285. /// Drag
  58286. if (_this._dragGradients && _this._dragGradients.length > 0) {
  58287. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  58288. if (currentGradient !== particle._currentDragGradient) {
  58289. particle._currentDrag1 = particle._currentDrag2;
  58290. particle._currentDrag2 = nextGradient.getFactor();
  58291. particle._currentDragGradient = currentGradient;
  58292. }
  58293. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  58294. _this._scaledDirection.scaleInPlace(1.0 - drag);
  58295. });
  58296. }
  58297. particle.position.addInPlace(_this._scaledDirection);
  58298. // Noise
  58299. if (noiseTextureData && noiseTextureSize) {
  58300. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58301. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58302. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58303. var force = BABYLON.Tmp.Vector3[0];
  58304. var scaledForce = BABYLON.Tmp.Vector3[1];
  58305. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  58306. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  58307. particle.direction.addInPlace(scaledForce);
  58308. }
  58309. // Gravity
  58310. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  58311. particle.direction.addInPlace(_this._scaledGravity);
  58312. // Size
  58313. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  58314. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  58315. if (currentGradient !== particle._currentSizeGradient) {
  58316. particle._currentSize1 = particle._currentSize2;
  58317. particle._currentSize2 = nextGradient.getFactor();
  58318. particle._currentSizeGradient = currentGradient;
  58319. }
  58320. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  58321. });
  58322. }
  58323. // Remap data
  58324. if (_this._useRampGradients) {
  58325. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  58326. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  58327. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58328. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58329. particle.remapData.x = min;
  58330. particle.remapData.y = max - min;
  58331. });
  58332. }
  58333. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  58334. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  58335. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58336. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58337. particle.remapData.z = min;
  58338. particle.remapData.w = max - min;
  58339. });
  58340. }
  58341. }
  58342. if (_this._isAnimationSheetEnabled) {
  58343. particle.updateCellIndex();
  58344. }
  58345. // Update the position of the attached sub-emitters to match their attached particle
  58346. particle._inheritParticleInfoToSubEmitters();
  58347. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  58348. _this._emitFromParticle(particle);
  58349. if (particle._attachedSubEmitters) {
  58350. particle._attachedSubEmitters.forEach(function (subEmitter) {
  58351. subEmitter.particleSystem.disposeOnStop = true;
  58352. subEmitter.particleSystem.stop();
  58353. });
  58354. particle._attachedSubEmitters = null;
  58355. }
  58356. _this.recycleParticle(particle);
  58357. index--;
  58358. return "continue";
  58359. }
  58360. };
  58361. var particle;
  58362. for (var index = 0; index < particles.length; index++) {
  58363. _loop_1();
  58364. }
  58365. };
  58366. return _this;
  58367. }
  58368. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  58369. /**
  58370. * Sets a callback that will be triggered when the system is disposed
  58371. */
  58372. set: function (callback) {
  58373. if (this._onDisposeObserver) {
  58374. this.onDisposeObservable.remove(this._onDisposeObserver);
  58375. }
  58376. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58377. },
  58378. enumerable: true,
  58379. configurable: true
  58380. });
  58381. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  58382. /** Gets or sets a boolean indicating that ramp gradients must be used
  58383. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  58384. */
  58385. get: function () {
  58386. return this._useRampGradients;
  58387. },
  58388. set: function (value) {
  58389. if (this._useRampGradients === value) {
  58390. return;
  58391. }
  58392. this._useRampGradients = value;
  58393. this._resetEffect();
  58394. },
  58395. enumerable: true,
  58396. configurable: true
  58397. });
  58398. Object.defineProperty(ParticleSystem.prototype, "particles", {
  58399. //end of Sub-emitter
  58400. /**
  58401. * Gets the current list of active particles
  58402. */
  58403. get: function () {
  58404. return this._particles;
  58405. },
  58406. enumerable: true,
  58407. configurable: true
  58408. });
  58409. /**
  58410. * Returns the string "ParticleSystem"
  58411. * @returns a string containing the class name
  58412. */
  58413. ParticleSystem.prototype.getClassName = function () {
  58414. return "ParticleSystem";
  58415. };
  58416. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  58417. var newGradient = new BABYLON.FactorGradient();
  58418. newGradient.gradient = gradient;
  58419. newGradient.factor1 = factor;
  58420. newGradient.factor2 = factor2;
  58421. factorGradients.push(newGradient);
  58422. factorGradients.sort(function (a, b) {
  58423. if (a.gradient < b.gradient) {
  58424. return -1;
  58425. }
  58426. else if (a.gradient > b.gradient) {
  58427. return 1;
  58428. }
  58429. return 0;
  58430. });
  58431. };
  58432. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  58433. if (!factorGradients) {
  58434. return;
  58435. }
  58436. var index = 0;
  58437. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  58438. var factorGradient = factorGradients_1[_i];
  58439. if (factorGradient.gradient === gradient) {
  58440. factorGradients.splice(index, 1);
  58441. break;
  58442. }
  58443. index++;
  58444. }
  58445. };
  58446. /**
  58447. * Adds a new life time gradient
  58448. * @param gradient defines the gradient to use (between 0 and 1)
  58449. * @param factor defines the life time factor to affect to the specified gradient
  58450. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58451. * @returns the current particle system
  58452. */
  58453. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  58454. if (!this._lifeTimeGradients) {
  58455. this._lifeTimeGradients = [];
  58456. }
  58457. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  58458. return this;
  58459. };
  58460. /**
  58461. * Remove a specific life time gradient
  58462. * @param gradient defines the gradient to remove
  58463. * @returns the current particle system
  58464. */
  58465. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  58466. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  58467. return this;
  58468. };
  58469. /**
  58470. * Adds a new size gradient
  58471. * @param gradient defines the gradient to use (between 0 and 1)
  58472. * @param factor defines the size factor to affect to the specified gradient
  58473. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58474. * @returns the current particle system
  58475. */
  58476. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  58477. if (!this._sizeGradients) {
  58478. this._sizeGradients = [];
  58479. }
  58480. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  58481. return this;
  58482. };
  58483. /**
  58484. * Remove a specific size gradient
  58485. * @param gradient defines the gradient to remove
  58486. * @returns the current particle system
  58487. */
  58488. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  58489. this._removeFactorGradient(this._sizeGradients, gradient);
  58490. return this;
  58491. };
  58492. /**
  58493. * Adds a new color remap gradient
  58494. * @param gradient defines the gradient to use (between 0 and 1)
  58495. * @param min defines the color remap minimal range
  58496. * @param max defines the color remap maximal range
  58497. * @returns the current particle system
  58498. */
  58499. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58500. if (!this._colorRemapGradients) {
  58501. this._colorRemapGradients = [];
  58502. }
  58503. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58504. return this;
  58505. };
  58506. /**
  58507. * Remove a specific color remap gradient
  58508. * @param gradient defines the gradient to remove
  58509. * @returns the current particle system
  58510. */
  58511. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58512. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58513. return this;
  58514. };
  58515. /**
  58516. * Adds a new alpha remap gradient
  58517. * @param gradient defines the gradient to use (between 0 and 1)
  58518. * @param min defines the alpha remap minimal range
  58519. * @param max defines the alpha remap maximal range
  58520. * @returns the current particle system
  58521. */
  58522. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58523. if (!this._alphaRemapGradients) {
  58524. this._alphaRemapGradients = [];
  58525. }
  58526. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58527. return this;
  58528. };
  58529. /**
  58530. * Remove a specific alpha remap gradient
  58531. * @param gradient defines the gradient to remove
  58532. * @returns the current particle system
  58533. */
  58534. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58535. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58536. return this;
  58537. };
  58538. /**
  58539. * Adds a new angular speed gradient
  58540. * @param gradient defines the gradient to use (between 0 and 1)
  58541. * @param factor defines the angular speed to affect to the specified gradient
  58542. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58543. * @returns the current particle system
  58544. */
  58545. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58546. if (!this._angularSpeedGradients) {
  58547. this._angularSpeedGradients = [];
  58548. }
  58549. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58550. return this;
  58551. };
  58552. /**
  58553. * Remove a specific angular speed gradient
  58554. * @param gradient defines the gradient to remove
  58555. * @returns the current particle system
  58556. */
  58557. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58558. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58559. return this;
  58560. };
  58561. /**
  58562. * Adds a new velocity gradient
  58563. * @param gradient defines the gradient to use (between 0 and 1)
  58564. * @param factor defines the velocity to affect to the specified gradient
  58565. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58566. * @returns the current particle system
  58567. */
  58568. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58569. if (!this._velocityGradients) {
  58570. this._velocityGradients = [];
  58571. }
  58572. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58573. return this;
  58574. };
  58575. /**
  58576. * Remove a specific velocity gradient
  58577. * @param gradient defines the gradient to remove
  58578. * @returns the current particle system
  58579. */
  58580. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58581. this._removeFactorGradient(this._velocityGradients, gradient);
  58582. return this;
  58583. };
  58584. /**
  58585. * Adds a new limit velocity gradient
  58586. * @param gradient defines the gradient to use (between 0 and 1)
  58587. * @param factor defines the limit velocity value to affect to the specified gradient
  58588. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58589. * @returns the current particle system
  58590. */
  58591. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58592. if (!this._limitVelocityGradients) {
  58593. this._limitVelocityGradients = [];
  58594. }
  58595. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58596. return this;
  58597. };
  58598. /**
  58599. * Remove a specific limit velocity gradient
  58600. * @param gradient defines the gradient to remove
  58601. * @returns the current particle system
  58602. */
  58603. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58604. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58605. return this;
  58606. };
  58607. /**
  58608. * Adds a new drag gradient
  58609. * @param gradient defines the gradient to use (between 0 and 1)
  58610. * @param factor defines the drag value to affect to the specified gradient
  58611. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58612. * @returns the current particle system
  58613. */
  58614. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58615. if (!this._dragGradients) {
  58616. this._dragGradients = [];
  58617. }
  58618. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58619. return this;
  58620. };
  58621. /**
  58622. * Remove a specific drag gradient
  58623. * @param gradient defines the gradient to remove
  58624. * @returns the current particle system
  58625. */
  58626. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58627. this._removeFactorGradient(this._dragGradients, gradient);
  58628. return this;
  58629. };
  58630. /**
  58631. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58632. * @param gradient defines the gradient to use (between 0 and 1)
  58633. * @param factor defines the emit rate value to affect to the specified gradient
  58634. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58635. * @returns the current particle system
  58636. */
  58637. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58638. if (!this._emitRateGradients) {
  58639. this._emitRateGradients = [];
  58640. }
  58641. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58642. if (!this._currentEmitRateGradient) {
  58643. this._currentEmitRateGradient = this._emitRateGradients[0];
  58644. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58645. this._currentEmitRate2 = this._currentEmitRate1;
  58646. }
  58647. if (this._emitRateGradients.length === 2) {
  58648. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58649. }
  58650. return this;
  58651. };
  58652. /**
  58653. * Remove a specific emit rate gradient
  58654. * @param gradient defines the gradient to remove
  58655. * @returns the current particle system
  58656. */
  58657. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58658. this._removeFactorGradient(this._emitRateGradients, gradient);
  58659. return this;
  58660. };
  58661. /**
  58662. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58663. * @param gradient defines the gradient to use (between 0 and 1)
  58664. * @param factor defines the start size value to affect to the specified gradient
  58665. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58666. * @returns the current particle system
  58667. */
  58668. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58669. if (!this._startSizeGradients) {
  58670. this._startSizeGradients = [];
  58671. }
  58672. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58673. if (!this._currentStartSizeGradient) {
  58674. this._currentStartSizeGradient = this._startSizeGradients[0];
  58675. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58676. this._currentStartSize2 = this._currentStartSize1;
  58677. }
  58678. if (this._startSizeGradients.length === 2) {
  58679. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58680. }
  58681. return this;
  58682. };
  58683. /**
  58684. * Remove a specific start size gradient
  58685. * @param gradient defines the gradient to remove
  58686. * @returns the current particle system
  58687. */
  58688. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58689. this._removeFactorGradient(this._emitRateGradients, gradient);
  58690. return this;
  58691. };
  58692. ParticleSystem.prototype._createRampGradientTexture = function () {
  58693. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58694. return;
  58695. }
  58696. var data = new Uint8Array(this._rawTextureWidth * 4);
  58697. var tmpColor = BABYLON.Tmp.Color3[0];
  58698. for (var x = 0; x < this._rawTextureWidth; x++) {
  58699. var ratio = x / this._rawTextureWidth;
  58700. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58701. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58702. data[x * 4] = tmpColor.r * 255;
  58703. data[x * 4 + 1] = tmpColor.g * 255;
  58704. data[x * 4 + 2] = tmpColor.b * 255;
  58705. data[x * 4 + 3] = 255;
  58706. });
  58707. }
  58708. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58709. };
  58710. /**
  58711. * Gets the current list of ramp gradients.
  58712. * You must use addRampGradient and removeRampGradient to udpate this list
  58713. * @returns the list of ramp gradients
  58714. */
  58715. ParticleSystem.prototype.getRampGradients = function () {
  58716. return this._rampGradients;
  58717. };
  58718. /**
  58719. * Adds a new ramp gradient used to remap particle colors
  58720. * @param gradient defines the gradient to use (between 0 and 1)
  58721. * @param color defines the color to affect to the specified gradient
  58722. * @returns the current particle system
  58723. */
  58724. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58725. if (!this._rampGradients) {
  58726. this._rampGradients = [];
  58727. }
  58728. var rampGradient = new BABYLON.Color3Gradient();
  58729. rampGradient.gradient = gradient;
  58730. rampGradient.color = color;
  58731. this._rampGradients.push(rampGradient);
  58732. this._rampGradients.sort(function (a, b) {
  58733. if (a.gradient < b.gradient) {
  58734. return -1;
  58735. }
  58736. else if (a.gradient > b.gradient) {
  58737. return 1;
  58738. }
  58739. return 0;
  58740. });
  58741. if (this._rampGradientsTexture) {
  58742. this._rampGradientsTexture.dispose();
  58743. this._rampGradientsTexture = null;
  58744. }
  58745. this._createRampGradientTexture();
  58746. return this;
  58747. };
  58748. /**
  58749. * Remove a specific ramp gradient
  58750. * @param gradient defines the gradient to remove
  58751. * @returns the current particle system
  58752. */
  58753. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58754. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58755. this._rampGradientsTexture = null;
  58756. if (this._rampGradients && this._rampGradients.length > 0) {
  58757. this._createRampGradientTexture();
  58758. }
  58759. return this;
  58760. };
  58761. /**
  58762. * Adds a new color gradient
  58763. * @param gradient defines the gradient to use (between 0 and 1)
  58764. * @param color1 defines the color to affect to the specified gradient
  58765. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58766. */
  58767. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58768. if (!this._colorGradients) {
  58769. this._colorGradients = [];
  58770. }
  58771. var colorGradient = new BABYLON.ColorGradient();
  58772. colorGradient.gradient = gradient;
  58773. colorGradient.color1 = color1;
  58774. colorGradient.color2 = color2;
  58775. this._colorGradients.push(colorGradient);
  58776. this._colorGradients.sort(function (a, b) {
  58777. if (a.gradient < b.gradient) {
  58778. return -1;
  58779. }
  58780. else if (a.gradient > b.gradient) {
  58781. return 1;
  58782. }
  58783. return 0;
  58784. });
  58785. return this;
  58786. };
  58787. /**
  58788. * Remove a specific color gradient
  58789. * @param gradient defines the gradient to remove
  58790. */
  58791. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58792. if (!this._colorGradients) {
  58793. return this;
  58794. }
  58795. var index = 0;
  58796. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58797. var colorGradient = _a[_i];
  58798. if (colorGradient.gradient === gradient) {
  58799. this._colorGradients.splice(index, 1);
  58800. break;
  58801. }
  58802. index++;
  58803. }
  58804. return this;
  58805. };
  58806. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58807. u = Math.abs(u) * 0.5 + 0.5;
  58808. v = Math.abs(v) * 0.5 + 0.5;
  58809. var wrappedU = ((u * width) % width) | 0;
  58810. var wrappedV = ((v * height) % height) | 0;
  58811. var position = (wrappedU + wrappedV * width) * 4;
  58812. return pixels[position] / 255;
  58813. };
  58814. ParticleSystem.prototype._reset = function () {
  58815. this._resetEffect();
  58816. };
  58817. ParticleSystem.prototype._resetEffect = function () {
  58818. if (this._vertexBuffer) {
  58819. this._vertexBuffer.dispose();
  58820. this._vertexBuffer = null;
  58821. }
  58822. if (this._spriteBuffer) {
  58823. this._spriteBuffer.dispose();
  58824. this._spriteBuffer = null;
  58825. }
  58826. this._createVertexBuffers();
  58827. };
  58828. ParticleSystem.prototype._createVertexBuffers = function () {
  58829. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58830. if (this._isAnimationSheetEnabled) {
  58831. this._vertexBufferSize += 1;
  58832. }
  58833. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58834. this._vertexBufferSize += 3;
  58835. }
  58836. if (this._useRampGradients) {
  58837. this._vertexBufferSize += 4;
  58838. }
  58839. var engine = this._scene.getEngine();
  58840. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58841. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58842. var dataOffset = 0;
  58843. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58844. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58845. dataOffset += 3;
  58846. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58847. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58848. dataOffset += 4;
  58849. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58850. this._vertexBuffers["angle"] = options;
  58851. dataOffset += 1;
  58852. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58853. this._vertexBuffers["size"] = size;
  58854. dataOffset += 2;
  58855. if (this._isAnimationSheetEnabled) {
  58856. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58857. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58858. dataOffset += 1;
  58859. }
  58860. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58861. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58862. this._vertexBuffers["direction"] = directionBuffer;
  58863. dataOffset += 3;
  58864. }
  58865. if (this._useRampGradients) {
  58866. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58867. this._vertexBuffers["remapData"] = rampDataBuffer;
  58868. dataOffset += 4;
  58869. }
  58870. var offsets;
  58871. if (this._useInstancing) {
  58872. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58873. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58874. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58875. }
  58876. else {
  58877. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58878. dataOffset += 2;
  58879. }
  58880. this._vertexBuffers["offset"] = offsets;
  58881. };
  58882. ParticleSystem.prototype._createIndexBuffer = function () {
  58883. if (this._useInstancing) {
  58884. return;
  58885. }
  58886. var indices = [];
  58887. var index = 0;
  58888. for (var count = 0; count < this._capacity; count++) {
  58889. indices.push(index);
  58890. indices.push(index + 1);
  58891. indices.push(index + 2);
  58892. indices.push(index);
  58893. indices.push(index + 2);
  58894. indices.push(index + 3);
  58895. index += 4;
  58896. }
  58897. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58898. };
  58899. /**
  58900. * Gets the maximum number of particles active at the same time.
  58901. * @returns The max number of active particles.
  58902. */
  58903. ParticleSystem.prototype.getCapacity = function () {
  58904. return this._capacity;
  58905. };
  58906. /**
  58907. * Gets whether there are still active particles in the system.
  58908. * @returns True if it is alive, otherwise false.
  58909. */
  58910. ParticleSystem.prototype.isAlive = function () {
  58911. return this._alive;
  58912. };
  58913. /**
  58914. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58915. * @returns True if it has been started, otherwise false.
  58916. */
  58917. ParticleSystem.prototype.isStarted = function () {
  58918. return this._started;
  58919. };
  58920. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58921. var _this = this;
  58922. this._subEmitters = new Array();
  58923. if (this.subEmitters) {
  58924. this.subEmitters.forEach(function (subEmitter) {
  58925. if (subEmitter instanceof ParticleSystem) {
  58926. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58927. }
  58928. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58929. _this._subEmitters.push([subEmitter]);
  58930. }
  58931. else if (subEmitter instanceof Array) {
  58932. _this._subEmitters.push(subEmitter);
  58933. }
  58934. });
  58935. }
  58936. };
  58937. /**
  58938. * Starts the particle system and begins to emit
  58939. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58940. */
  58941. ParticleSystem.prototype.start = function (delay) {
  58942. var _this = this;
  58943. if (delay === void 0) { delay = this.startDelay; }
  58944. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58945. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58946. }
  58947. if (delay) {
  58948. setTimeout(function () {
  58949. _this.start(0);
  58950. }, delay);
  58951. return;
  58952. }
  58953. // Convert the subEmitters field to the constant type field _subEmitters
  58954. this._prepareSubEmitterInternalArray();
  58955. this._started = true;
  58956. this._stopped = false;
  58957. this._actualFrame = 0;
  58958. if (this._subEmitters && this._subEmitters.length != 0) {
  58959. this.activeSubSystems = new Array();
  58960. }
  58961. if (this.preWarmCycles) {
  58962. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58963. this.emitter.computeWorldMatrix(true);
  58964. }
  58965. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58966. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58967. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58968. setTimeout(function () {
  58969. for (var index = 0; index < _this.preWarmCycles; index++) {
  58970. _this.animate(true);
  58971. noiseTextureAsProcedural_1.render();
  58972. }
  58973. });
  58974. });
  58975. }
  58976. else {
  58977. for (var index = 0; index < this.preWarmCycles; index++) {
  58978. this.animate(true);
  58979. }
  58980. }
  58981. }
  58982. // Animations
  58983. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  58984. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  58985. }
  58986. };
  58987. /**
  58988. * Stops the particle system.
  58989. * @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.
  58990. */
  58991. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58992. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58993. this._stopped = true;
  58994. if (stopSubEmitters) {
  58995. this._stopSubEmitters();
  58996. }
  58997. };
  58998. // animation sheet
  58999. /**
  59000. * Remove all active particles
  59001. */
  59002. ParticleSystem.prototype.reset = function () {
  59003. this._stockParticles = [];
  59004. this._particles = [];
  59005. };
  59006. /**
  59007. * @hidden (for internal use only)
  59008. */
  59009. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59010. var offset = index * this._vertexBufferSize;
  59011. this._vertexData[offset++] = particle.position.x;
  59012. this._vertexData[offset++] = particle.position.y;
  59013. this._vertexData[offset++] = particle.position.z;
  59014. this._vertexData[offset++] = particle.color.r;
  59015. this._vertexData[offset++] = particle.color.g;
  59016. this._vertexData[offset++] = particle.color.b;
  59017. this._vertexData[offset++] = particle.color.a;
  59018. this._vertexData[offset++] = particle.angle;
  59019. this._vertexData[offset++] = particle.scale.x * particle.size;
  59020. this._vertexData[offset++] = particle.scale.y * particle.size;
  59021. if (this._isAnimationSheetEnabled) {
  59022. this._vertexData[offset++] = particle.cellIndex;
  59023. }
  59024. if (!this._isBillboardBased) {
  59025. if (particle._initialDirection) {
  59026. this._vertexData[offset++] = particle._initialDirection.x;
  59027. this._vertexData[offset++] = particle._initialDirection.y;
  59028. this._vertexData[offset++] = particle._initialDirection.z;
  59029. }
  59030. else {
  59031. this._vertexData[offset++] = particle.direction.x;
  59032. this._vertexData[offset++] = particle.direction.y;
  59033. this._vertexData[offset++] = particle.direction.z;
  59034. }
  59035. }
  59036. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59037. this._vertexData[offset++] = particle.direction.x;
  59038. this._vertexData[offset++] = particle.direction.y;
  59039. this._vertexData[offset++] = particle.direction.z;
  59040. }
  59041. if (this._useRampGradients) {
  59042. this._vertexData[offset++] = particle.remapData.x;
  59043. this._vertexData[offset++] = particle.remapData.y;
  59044. this._vertexData[offset++] = particle.remapData.z;
  59045. this._vertexData[offset++] = particle.remapData.w;
  59046. }
  59047. if (!this._useInstancing) {
  59048. if (this._isAnimationSheetEnabled) {
  59049. if (offsetX === 0)
  59050. offsetX = this._epsilon;
  59051. else if (offsetX === 1)
  59052. offsetX = 1 - this._epsilon;
  59053. if (offsetY === 0)
  59054. offsetY = this._epsilon;
  59055. else if (offsetY === 1)
  59056. offsetY = 1 - this._epsilon;
  59057. }
  59058. this._vertexData[offset++] = offsetX;
  59059. this._vertexData[offset++] = offsetY;
  59060. }
  59061. };
  59062. ParticleSystem.prototype._stopSubEmitters = function () {
  59063. if (!this.activeSubSystems) {
  59064. return;
  59065. }
  59066. this.activeSubSystems.forEach(function (subSystem) {
  59067. subSystem.stop(true);
  59068. });
  59069. this.activeSubSystems = new Array();
  59070. };
  59071. ParticleSystem.prototype._removeFromRoot = function () {
  59072. if (!this._rootParticleSystem) {
  59073. return;
  59074. }
  59075. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59076. if (index !== -1) {
  59077. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59078. }
  59079. this._rootParticleSystem = null;
  59080. };
  59081. // End of sub system methods
  59082. ParticleSystem.prototype._update = function (newParticles) {
  59083. var _this = this;
  59084. // Update current
  59085. this._alive = this._particles.length > 0;
  59086. if (this.emitter.position) {
  59087. var emitterMesh = this.emitter;
  59088. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59089. }
  59090. else {
  59091. var emitterPosition = this.emitter;
  59092. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59093. }
  59094. this.updateFunction(this._particles);
  59095. // Add new ones
  59096. var particle;
  59097. var _loop_2 = function () {
  59098. if (this_1._particles.length === this_1._capacity) {
  59099. return "break";
  59100. }
  59101. particle = this_1._createParticle();
  59102. this_1._particles.push(particle);
  59103. // Emitter
  59104. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59105. if (this_1.startPositionFunction) {
  59106. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59107. }
  59108. else {
  59109. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59110. }
  59111. if (this_1.startDirectionFunction) {
  59112. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59113. }
  59114. else {
  59115. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59116. }
  59117. if (emitPower === 0) {
  59118. if (!particle._initialDirection) {
  59119. particle._initialDirection = particle.direction.clone();
  59120. }
  59121. else {
  59122. particle._initialDirection.copyFrom(particle.direction);
  59123. }
  59124. }
  59125. else {
  59126. particle._initialDirection = null;
  59127. }
  59128. particle.direction.scaleInPlace(emitPower);
  59129. // Life time
  59130. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59131. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59132. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59133. var factorGradient1 = currentGradient;
  59134. var factorGradient2 = nextGradient;
  59135. var lifeTime1 = factorGradient1.getFactor();
  59136. var lifeTime2 = factorGradient2.getFactor();
  59137. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59138. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59139. });
  59140. }
  59141. else {
  59142. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  59143. }
  59144. // Size
  59145. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  59146. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  59147. }
  59148. else {
  59149. particle._currentSizeGradient = this_1._sizeGradients[0];
  59150. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  59151. particle.size = particle._currentSize1;
  59152. if (this_1._sizeGradients.length > 1) {
  59153. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  59154. }
  59155. else {
  59156. particle._currentSize2 = particle._currentSize1;
  59157. }
  59158. }
  59159. // Size and scale
  59160. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  59161. // Adjust scale by start size
  59162. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  59163. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  59164. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  59165. if (currentGradient !== _this._currentStartSizeGradient) {
  59166. _this._currentStartSize1 = _this._currentStartSize2;
  59167. _this._currentStartSize2 = nextGradient.getFactor();
  59168. _this._currentStartSizeGradient = currentGradient;
  59169. }
  59170. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  59171. particle.scale.scaleInPlace(value);
  59172. });
  59173. }
  59174. // Angle
  59175. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  59176. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  59177. }
  59178. else {
  59179. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  59180. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  59181. particle._currentAngularSpeed1 = particle.angularSpeed;
  59182. if (this_1._angularSpeedGradients.length > 1) {
  59183. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  59184. }
  59185. else {
  59186. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  59187. }
  59188. }
  59189. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  59190. // Velocity
  59191. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  59192. particle._currentVelocityGradient = this_1._velocityGradients[0];
  59193. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  59194. if (this_1._velocityGradients.length > 1) {
  59195. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  59196. }
  59197. else {
  59198. particle._currentVelocity2 = particle._currentVelocity1;
  59199. }
  59200. }
  59201. // Limit velocity
  59202. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  59203. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  59204. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  59205. if (this_1._limitVelocityGradients.length > 1) {
  59206. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  59207. }
  59208. else {
  59209. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  59210. }
  59211. }
  59212. // Drag
  59213. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  59214. particle._currentDragGradient = this_1._dragGradients[0];
  59215. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  59216. if (this_1._dragGradients.length > 1) {
  59217. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  59218. }
  59219. else {
  59220. particle._currentDrag2 = particle._currentDrag1;
  59221. }
  59222. }
  59223. // Color
  59224. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  59225. step = BABYLON.Scalar.RandomRange(0, 1.0);
  59226. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  59227. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  59228. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  59229. }
  59230. else {
  59231. particle._currentColorGradient = this_1._colorGradients[0];
  59232. particle._currentColorGradient.getColorToRef(particle.color);
  59233. particle._currentColor1.copyFrom(particle.color);
  59234. if (this_1._colorGradients.length > 1) {
  59235. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  59236. }
  59237. else {
  59238. particle._currentColor2.copyFrom(particle.color);
  59239. }
  59240. }
  59241. // Sheet
  59242. if (this_1._isAnimationSheetEnabled) {
  59243. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  59244. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  59245. }
  59246. // Inherited Velocity
  59247. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  59248. // Ramp
  59249. if (this_1._useRampGradients) {
  59250. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  59251. }
  59252. // Noise texture coordinates
  59253. if (this_1.noiseTexture) {
  59254. if (particle._randomNoiseCoordinates1) {
  59255. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  59256. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  59257. }
  59258. else {
  59259. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59260. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59261. }
  59262. }
  59263. // Update the position of the attached sub-emitters to match their attached particle
  59264. particle._inheritParticleInfoToSubEmitters();
  59265. };
  59266. var this_1 = this, step;
  59267. for (var index = 0; index < newParticles; index++) {
  59268. var state_1 = _loop_2();
  59269. if (state_1 === "break")
  59270. break;
  59271. }
  59272. };
  59273. /** @hidden */
  59274. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  59275. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59276. if (isBillboardBased === void 0) { isBillboardBased = false; }
  59277. if (useRampGradients === void 0) { useRampGradients = false; }
  59278. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  59279. if (isAnimationSheetEnabled) {
  59280. attributeNamesOrOptions.push("cellIndex");
  59281. }
  59282. if (!isBillboardBased) {
  59283. attributeNamesOrOptions.push("direction");
  59284. }
  59285. if (useRampGradients) {
  59286. attributeNamesOrOptions.push("remapData");
  59287. }
  59288. return attributeNamesOrOptions;
  59289. };
  59290. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  59291. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59292. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  59293. if (isAnimationSheetEnabled) {
  59294. effectCreationOption.push("particlesInfos");
  59295. }
  59296. return effectCreationOption;
  59297. };
  59298. ParticleSystem.prototype._getEffect = function (blendMode) {
  59299. if (this._customEffect) {
  59300. return this._customEffect;
  59301. }
  59302. ;
  59303. var defines = [];
  59304. if (this._scene.clipPlane) {
  59305. defines.push("#define CLIPPLANE");
  59306. }
  59307. if (this._scene.clipPlane2) {
  59308. defines.push("#define CLIPPLANE2");
  59309. }
  59310. if (this._scene.clipPlane3) {
  59311. defines.push("#define CLIPPLANE3");
  59312. }
  59313. if (this._scene.clipPlane4) {
  59314. defines.push("#define CLIPPLANE4");
  59315. }
  59316. if (this._isAnimationSheetEnabled) {
  59317. defines.push("#define ANIMATESHEET");
  59318. }
  59319. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  59320. defines.push("#define BLENDMULTIPLYMODE");
  59321. }
  59322. if (this._useRampGradients) {
  59323. defines.push("#define RAMPGRADIENT");
  59324. }
  59325. if (this._isBillboardBased) {
  59326. defines.push("#define BILLBOARD");
  59327. switch (this.billboardMode) {
  59328. case ParticleSystem.BILLBOARDMODE_Y:
  59329. defines.push("#define BILLBOARDY");
  59330. break;
  59331. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  59332. defines.push("#define BILLBOARDSTRETCHED");
  59333. break;
  59334. case ParticleSystem.BILLBOARDMODE_ALL:
  59335. default:
  59336. break;
  59337. }
  59338. }
  59339. if (this._imageProcessingConfiguration) {
  59340. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  59341. defines.push(this._imageProcessingConfigurationDefines.toString());
  59342. }
  59343. // Effect
  59344. var join = defines.join("\n");
  59345. if (this._cachedDefines !== join) {
  59346. this._cachedDefines = join;
  59347. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  59348. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  59349. var samplers = ["diffuseSampler", "rampSampler"];
  59350. if (BABYLON.ImageProcessingConfiguration) {
  59351. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  59352. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  59353. }
  59354. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  59355. }
  59356. return this._effect;
  59357. };
  59358. /**
  59359. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59360. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  59361. */
  59362. ParticleSystem.prototype.animate = function (preWarmOnly) {
  59363. var _this = this;
  59364. if (preWarmOnly === void 0) { preWarmOnly = false; }
  59365. if (!this._started)
  59366. return;
  59367. if (!preWarmOnly) {
  59368. // Check
  59369. if (!this.isReady())
  59370. return;
  59371. if (this._currentRenderId === this._scene.getRenderId()) {
  59372. return;
  59373. }
  59374. this._currentRenderId = this._scene.getRenderId();
  59375. }
  59376. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59377. // Determine the number of particles we need to create
  59378. var newParticles;
  59379. if (this.manualEmitCount > -1) {
  59380. newParticles = this.manualEmitCount;
  59381. this._newPartsExcess = 0;
  59382. this.manualEmitCount = 0;
  59383. }
  59384. else {
  59385. var rate_1 = this.emitRate;
  59386. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  59387. var ratio = this._actualFrame / this.targetStopDuration;
  59388. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  59389. if (currentGradient !== _this._currentEmitRateGradient) {
  59390. _this._currentEmitRate1 = _this._currentEmitRate2;
  59391. _this._currentEmitRate2 = nextGradient.getFactor();
  59392. _this._currentEmitRateGradient = currentGradient;
  59393. }
  59394. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  59395. });
  59396. }
  59397. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  59398. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  59399. }
  59400. if (this._newPartsExcess > 1.0) {
  59401. newParticles += this._newPartsExcess >> 0;
  59402. this._newPartsExcess -= this._newPartsExcess >> 0;
  59403. }
  59404. this._alive = false;
  59405. if (!this._stopped) {
  59406. this._actualFrame += this._scaledUpdateSpeed;
  59407. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  59408. this.stop();
  59409. }
  59410. else {
  59411. newParticles = 0;
  59412. }
  59413. this._update(newParticles);
  59414. // Stopped?
  59415. if (this._stopped) {
  59416. if (!this._alive) {
  59417. this._started = false;
  59418. if (this.onAnimationEnd) {
  59419. this.onAnimationEnd();
  59420. }
  59421. if (this.disposeOnStop) {
  59422. this._scene._toBeDisposed.push(this);
  59423. }
  59424. }
  59425. }
  59426. if (!preWarmOnly) {
  59427. // Update VBO
  59428. var offset = 0;
  59429. for (var index = 0; index < this._particles.length; index++) {
  59430. var particle = this._particles[index];
  59431. this._appendParticleVertices(offset, particle);
  59432. offset += this._useInstancing ? 1 : 4;
  59433. }
  59434. if (this._vertexBuffer) {
  59435. this._vertexBuffer.update(this._vertexData);
  59436. }
  59437. }
  59438. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  59439. this.stop();
  59440. }
  59441. };
  59442. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  59443. this._appendParticleVertex(offset++, particle, 0, 0);
  59444. if (!this._useInstancing) {
  59445. this._appendParticleVertex(offset++, particle, 1, 0);
  59446. this._appendParticleVertex(offset++, particle, 1, 1);
  59447. this._appendParticleVertex(offset++, particle, 0, 1);
  59448. }
  59449. };
  59450. /**
  59451. * Rebuilds the particle system.
  59452. */
  59453. ParticleSystem.prototype.rebuild = function () {
  59454. this._createIndexBuffer();
  59455. if (this._vertexBuffer) {
  59456. this._vertexBuffer._rebuild();
  59457. }
  59458. };
  59459. /**
  59460. * Is this system ready to be used/rendered
  59461. * @return true if the system is ready
  59462. */
  59463. ParticleSystem.prototype.isReady = function () {
  59464. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59465. return false;
  59466. }
  59467. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59468. if (!this._getEffect(this.blendMode).isReady()) {
  59469. return false;
  59470. }
  59471. }
  59472. else {
  59473. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  59474. return false;
  59475. }
  59476. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  59477. return false;
  59478. }
  59479. }
  59480. return true;
  59481. };
  59482. ParticleSystem.prototype._render = function (blendMode) {
  59483. var effect = this._getEffect(blendMode);
  59484. var engine = this._scene.getEngine();
  59485. // Render
  59486. engine.enableEffect(effect);
  59487. var viewMatrix = this._scene.getViewMatrix();
  59488. effect.setTexture("diffuseSampler", this.particleTexture);
  59489. effect.setMatrix("view", viewMatrix);
  59490. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59491. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59492. var baseSize = this.particleTexture.getBaseSize();
  59493. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59494. }
  59495. effect.setVector2("translationPivot", this.translationPivot);
  59496. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59497. if (this._isBillboardBased) {
  59498. var camera = this._scene.activeCamera;
  59499. effect.setVector3("eyePosition", camera.globalPosition);
  59500. }
  59501. if (this._rampGradientsTexture) {
  59502. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59503. }
  59504. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59505. var invView = viewMatrix.clone();
  59506. invView.invert();
  59507. effect.setMatrix("invView", invView);
  59508. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59509. }
  59510. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59511. // image processing
  59512. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59513. this._imageProcessingConfiguration.bind(effect);
  59514. }
  59515. // Draw order
  59516. switch (blendMode) {
  59517. case ParticleSystem.BLENDMODE_ADD:
  59518. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59519. break;
  59520. case ParticleSystem.BLENDMODE_ONEONE:
  59521. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59522. break;
  59523. case ParticleSystem.BLENDMODE_STANDARD:
  59524. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59525. break;
  59526. case ParticleSystem.BLENDMODE_MULTIPLY:
  59527. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59528. break;
  59529. }
  59530. if (this._useInstancing) {
  59531. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59532. }
  59533. else {
  59534. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59535. }
  59536. return this._particles.length;
  59537. };
  59538. /**
  59539. * Renders the particle system in its current state.
  59540. * @returns the current number of particles
  59541. */
  59542. ParticleSystem.prototype.render = function () {
  59543. // Check
  59544. if (!this.isReady() || !this._particles.length) {
  59545. return 0;
  59546. }
  59547. var engine = this._scene.getEngine();
  59548. engine.setState(false);
  59549. if (this.forceDepthWrite) {
  59550. engine.setDepthWrite(true);
  59551. }
  59552. var outparticles = 0;
  59553. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59554. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59555. }
  59556. outparticles = this._render(this.blendMode);
  59557. engine.unbindInstanceAttributes();
  59558. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59559. return outparticles;
  59560. };
  59561. /**
  59562. * Disposes the particle system and free the associated resources
  59563. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59564. */
  59565. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59566. if (disposeTexture === void 0) { disposeTexture = true; }
  59567. if (this._vertexBuffer) {
  59568. this._vertexBuffer.dispose();
  59569. this._vertexBuffer = null;
  59570. }
  59571. if (this._spriteBuffer) {
  59572. this._spriteBuffer.dispose();
  59573. this._spriteBuffer = null;
  59574. }
  59575. if (this._indexBuffer) {
  59576. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59577. this._indexBuffer = null;
  59578. }
  59579. if (disposeTexture && this.particleTexture) {
  59580. this.particleTexture.dispose();
  59581. this.particleTexture = null;
  59582. }
  59583. if (disposeTexture && this.noiseTexture) {
  59584. this.noiseTexture.dispose();
  59585. this.noiseTexture = null;
  59586. }
  59587. if (this._rampGradientsTexture) {
  59588. this._rampGradientsTexture.dispose();
  59589. this._rampGradientsTexture = null;
  59590. }
  59591. this._removeFromRoot();
  59592. if (this._subEmitters && this._subEmitters.length) {
  59593. for (var index = 0; index < this._subEmitters.length; index++) {
  59594. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59595. var subEmitter = _a[_i];
  59596. subEmitter.dispose();
  59597. }
  59598. }
  59599. this._subEmitters = [];
  59600. this.subEmitters = [];
  59601. }
  59602. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59603. this.emitter.dispose(true);
  59604. }
  59605. // Remove from scene
  59606. var index = this._scene.particleSystems.indexOf(this);
  59607. if (index > -1) {
  59608. this._scene.particleSystems.splice(index, 1);
  59609. }
  59610. this._scene._activeParticleSystems.dispose();
  59611. // Callback
  59612. this.onDisposeObservable.notifyObservers(this);
  59613. this.onDisposeObservable.clear();
  59614. this.reset();
  59615. };
  59616. // Clone
  59617. /**
  59618. * Clones the particle system.
  59619. * @param name The name of the cloned object
  59620. * @param newEmitter The new emitter to use
  59621. * @returns the cloned particle system
  59622. */
  59623. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59624. var custom = null;
  59625. var program = null;
  59626. if (this.customShader != null) {
  59627. program = this.customShader;
  59628. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59629. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59630. }
  59631. else if (this._customEffect) {
  59632. custom = this._customEffect;
  59633. }
  59634. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59635. result.customShader = program;
  59636. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59637. if (newEmitter === undefined) {
  59638. newEmitter = this.emitter;
  59639. }
  59640. result.noiseTexture = this.noiseTexture;
  59641. result.emitter = newEmitter;
  59642. if (this.particleTexture) {
  59643. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59644. }
  59645. // Clone gradients
  59646. if (this._colorGradients) {
  59647. this._colorGradients.forEach(function (v) {
  59648. result.addColorGradient(v.gradient, v.color1, v.color2);
  59649. });
  59650. }
  59651. if (this._dragGradients) {
  59652. this._dragGradients.forEach(function (v) {
  59653. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59654. });
  59655. }
  59656. if (this._angularSpeedGradients) {
  59657. this._angularSpeedGradients.forEach(function (v) {
  59658. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59659. });
  59660. }
  59661. if (this._emitRateGradients) {
  59662. this._emitRateGradients.forEach(function (v) {
  59663. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59664. });
  59665. }
  59666. if (this._lifeTimeGradients) {
  59667. this._lifeTimeGradients.forEach(function (v) {
  59668. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59669. });
  59670. }
  59671. if (this._limitVelocityGradients) {
  59672. this._limitVelocityGradients.forEach(function (v) {
  59673. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59674. });
  59675. }
  59676. if (this._sizeGradients) {
  59677. this._sizeGradients.forEach(function (v) {
  59678. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59679. });
  59680. }
  59681. if (this._startSizeGradients) {
  59682. this._startSizeGradients.forEach(function (v) {
  59683. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59684. });
  59685. }
  59686. if (this._velocityGradients) {
  59687. this._velocityGradients.forEach(function (v) {
  59688. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59689. });
  59690. }
  59691. if (this._rampGradients) {
  59692. this._rampGradients.forEach(function (v) {
  59693. result.addRampGradient(v.gradient, v.color);
  59694. });
  59695. }
  59696. if (this._colorRemapGradients) {
  59697. this._colorRemapGradients.forEach(function (v) {
  59698. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59699. });
  59700. }
  59701. if (this._alphaRemapGradients) {
  59702. this._alphaRemapGradients.forEach(function (v) {
  59703. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59704. });
  59705. }
  59706. if (!this.preventAutoStart) {
  59707. result.start();
  59708. }
  59709. return result;
  59710. };
  59711. /**
  59712. * Serializes the particle system to a JSON object.
  59713. * @returns the JSON object
  59714. */
  59715. ParticleSystem.prototype.serialize = function () {
  59716. var serializationObject = {};
  59717. ParticleSystem._Serialize(serializationObject, this);
  59718. serializationObject.textureMask = this.textureMask.asArray();
  59719. serializationObject.customShader = this.customShader;
  59720. serializationObject.preventAutoStart = this.preventAutoStart;
  59721. // SubEmitters
  59722. if (this.subEmitters) {
  59723. serializationObject.subEmitters = [];
  59724. if (!this._subEmitters) {
  59725. this._prepareSubEmitterInternalArray();
  59726. }
  59727. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59728. var subs = _a[_i];
  59729. var cell = [];
  59730. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59731. var sub = subs_1[_b];
  59732. cell.push(sub.serialize());
  59733. }
  59734. serializationObject.subEmitters.push(cell);
  59735. }
  59736. }
  59737. return serializationObject;
  59738. };
  59739. /** @hidden */
  59740. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59741. serializationObject.name = particleSystem.name;
  59742. serializationObject.id = particleSystem.id;
  59743. serializationObject.capacity = particleSystem.getCapacity();
  59744. // Emitter
  59745. if (particleSystem.emitter.position) {
  59746. var emitterMesh = particleSystem.emitter;
  59747. serializationObject.emitterId = emitterMesh.id;
  59748. }
  59749. else {
  59750. var emitterPosition = particleSystem.emitter;
  59751. serializationObject.emitter = emitterPosition.asArray();
  59752. }
  59753. // Emitter
  59754. if (particleSystem.particleEmitterType) {
  59755. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59756. }
  59757. if (particleSystem.particleTexture) {
  59758. serializationObject.textureName = particleSystem.particleTexture.name;
  59759. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59760. }
  59761. // Animations
  59762. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59763. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59764. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59765. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59766. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59767. // Particle system
  59768. serializationObject.startDelay = particleSystem.startDelay;
  59769. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59770. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59771. serializationObject.billboardMode = particleSystem.billboardMode;
  59772. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59773. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59774. serializationObject.minSize = particleSystem.minSize;
  59775. serializationObject.maxSize = particleSystem.maxSize;
  59776. serializationObject.minScaleX = particleSystem.minScaleX;
  59777. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59778. serializationObject.minScaleY = particleSystem.minScaleY;
  59779. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59780. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59781. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59782. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59783. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59784. serializationObject.emitRate = particleSystem.emitRate;
  59785. serializationObject.gravity = particleSystem.gravity.asArray();
  59786. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59787. serializationObject.color1 = particleSystem.color1.asArray();
  59788. serializationObject.color2 = particleSystem.color2.asArray();
  59789. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59790. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59791. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59792. serializationObject.blendMode = particleSystem.blendMode;
  59793. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59794. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59795. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59796. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59797. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59798. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59799. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59800. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59801. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59802. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59803. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59804. var colorGradients = particleSystem.getColorGradients();
  59805. if (colorGradients) {
  59806. serializationObject.colorGradients = [];
  59807. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59808. var colorGradient = colorGradients_1[_i];
  59809. var serializedGradient = {
  59810. gradient: colorGradient.gradient,
  59811. color1: colorGradient.color1.asArray()
  59812. };
  59813. if (colorGradient.color2) {
  59814. serializedGradient.color2 = colorGradient.color2.asArray();
  59815. }
  59816. serializationObject.colorGradients.push(serializedGradient);
  59817. }
  59818. }
  59819. var rampGradients = particleSystem.getRampGradients();
  59820. if (rampGradients) {
  59821. serializationObject.rampGradients = [];
  59822. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59823. var rampGradient = rampGradients_1[_a];
  59824. var serializedGradient = {
  59825. gradient: rampGradient.gradient,
  59826. color: rampGradient.color.asArray()
  59827. };
  59828. serializationObject.rampGradients.push(serializedGradient);
  59829. }
  59830. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59831. }
  59832. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59833. if (colorRemapGradients) {
  59834. serializationObject.colorRemapGradients = [];
  59835. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59836. var colorRemapGradient = colorRemapGradients_1[_b];
  59837. var serializedGradient = {
  59838. gradient: colorRemapGradient.gradient,
  59839. factor1: colorRemapGradient.factor1
  59840. };
  59841. if (colorRemapGradient.factor2 !== undefined) {
  59842. serializedGradient.factor2 = colorRemapGradient.factor2;
  59843. }
  59844. serializationObject.colorRemapGradients.push(serializedGradient);
  59845. }
  59846. }
  59847. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59848. if (alphaRemapGradients) {
  59849. serializationObject.alphaRemapGradients = [];
  59850. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59851. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59852. var serializedGradient = {
  59853. gradient: alphaRemapGradient.gradient,
  59854. factor1: alphaRemapGradient.factor1
  59855. };
  59856. if (alphaRemapGradient.factor2 !== undefined) {
  59857. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59858. }
  59859. serializationObject.alphaRemapGradients.push(serializedGradient);
  59860. }
  59861. }
  59862. var sizeGradients = particleSystem.getSizeGradients();
  59863. if (sizeGradients) {
  59864. serializationObject.sizeGradients = [];
  59865. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59866. var sizeGradient = sizeGradients_1[_d];
  59867. var serializedGradient = {
  59868. gradient: sizeGradient.gradient,
  59869. factor1: sizeGradient.factor1
  59870. };
  59871. if (sizeGradient.factor2 !== undefined) {
  59872. serializedGradient.factor2 = sizeGradient.factor2;
  59873. }
  59874. serializationObject.sizeGradients.push(serializedGradient);
  59875. }
  59876. }
  59877. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59878. if (angularSpeedGradients) {
  59879. serializationObject.angularSpeedGradients = [];
  59880. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59881. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59882. var serializedGradient = {
  59883. gradient: angularSpeedGradient.gradient,
  59884. factor1: angularSpeedGradient.factor1
  59885. };
  59886. if (angularSpeedGradient.factor2 !== undefined) {
  59887. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59888. }
  59889. serializationObject.angularSpeedGradients.push(serializedGradient);
  59890. }
  59891. }
  59892. var velocityGradients = particleSystem.getVelocityGradients();
  59893. if (velocityGradients) {
  59894. serializationObject.velocityGradients = [];
  59895. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59896. var velocityGradient = velocityGradients_1[_f];
  59897. var serializedGradient = {
  59898. gradient: velocityGradient.gradient,
  59899. factor1: velocityGradient.factor1
  59900. };
  59901. if (velocityGradient.factor2 !== undefined) {
  59902. serializedGradient.factor2 = velocityGradient.factor2;
  59903. }
  59904. serializationObject.velocityGradients.push(serializedGradient);
  59905. }
  59906. }
  59907. var dragGradients = particleSystem.getDragGradients();
  59908. if (dragGradients) {
  59909. serializationObject.dragyGradients = [];
  59910. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59911. var dragGradient = dragGradients_1[_g];
  59912. var serializedGradient = {
  59913. gradient: dragGradient.gradient,
  59914. factor1: dragGradient.factor1
  59915. };
  59916. if (dragGradient.factor2 !== undefined) {
  59917. serializedGradient.factor2 = dragGradient.factor2;
  59918. }
  59919. serializationObject.dragGradients.push(serializedGradient);
  59920. }
  59921. }
  59922. var emitRateGradients = particleSystem.getEmitRateGradients();
  59923. if (emitRateGradients) {
  59924. serializationObject.emitRateGradients = [];
  59925. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59926. var emitRateGradient = emitRateGradients_1[_h];
  59927. var serializedGradient = {
  59928. gradient: emitRateGradient.gradient,
  59929. factor1: emitRateGradient.factor1
  59930. };
  59931. if (emitRateGradient.factor2 !== undefined) {
  59932. serializedGradient.factor2 = emitRateGradient.factor2;
  59933. }
  59934. serializationObject.emitRateGradients.push(serializedGradient);
  59935. }
  59936. }
  59937. var startSizeGradients = particleSystem.getStartSizeGradients();
  59938. if (startSizeGradients) {
  59939. serializationObject.startSizeGradients = [];
  59940. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59941. var startSizeGradient = startSizeGradients_1[_j];
  59942. var serializedGradient = {
  59943. gradient: startSizeGradient.gradient,
  59944. factor1: startSizeGradient.factor1
  59945. };
  59946. if (startSizeGradient.factor2 !== undefined) {
  59947. serializedGradient.factor2 = startSizeGradient.factor2;
  59948. }
  59949. serializationObject.startSizeGradients.push(serializedGradient);
  59950. }
  59951. }
  59952. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59953. if (lifeTimeGradients) {
  59954. serializationObject.lifeTimeGradients = [];
  59955. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59956. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59957. var serializedGradient = {
  59958. gradient: lifeTimeGradient.gradient,
  59959. factor1: lifeTimeGradient.factor1
  59960. };
  59961. if (lifeTimeGradient.factor2 !== undefined) {
  59962. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59963. }
  59964. serializationObject.lifeTimeGradients.push(serializedGradient);
  59965. }
  59966. }
  59967. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59968. if (limitVelocityGradients) {
  59969. serializationObject.limitVelocityGradients = [];
  59970. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59971. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59972. var serializedGradient = {
  59973. gradient: limitVelocityGradient.gradient,
  59974. factor1: limitVelocityGradient.factor1
  59975. };
  59976. if (limitVelocityGradient.factor2 !== undefined) {
  59977. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59978. }
  59979. serializationObject.limitVelocityGradients.push(serializedGradient);
  59980. }
  59981. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59982. }
  59983. if (particleSystem.noiseTexture) {
  59984. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59985. }
  59986. };
  59987. /** @hidden */
  59988. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59989. // Texture
  59990. if (parsedParticleSystem.textureName) {
  59991. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59992. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59993. }
  59994. // Emitter
  59995. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59996. particleSystem.emitter = BABYLON.Vector3.Zero();
  59997. }
  59998. else if (parsedParticleSystem.emitterId) {
  59999. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60000. }
  60001. else {
  60002. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60003. }
  60004. // Misc.
  60005. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60006. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60007. }
  60008. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60009. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60010. }
  60011. if (parsedParticleSystem.billboardMode !== undefined) {
  60012. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60013. }
  60014. // Animations
  60015. if (parsedParticleSystem.animations) {
  60016. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60017. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60018. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60019. }
  60020. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60021. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60022. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60023. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60024. }
  60025. if (parsedParticleSystem.autoAnimate) {
  60026. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60027. }
  60028. // Particle system
  60029. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60030. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60031. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60032. particleSystem.minSize = parsedParticleSystem.minSize;
  60033. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60034. if (parsedParticleSystem.minScaleX) {
  60035. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60036. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60037. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60038. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60039. }
  60040. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60041. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60042. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60043. }
  60044. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60045. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60046. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60047. }
  60048. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60049. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60050. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60051. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60052. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60053. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60054. if (parsedParticleSystem.noiseStrength) {
  60055. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60056. }
  60057. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60058. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60059. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60060. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60061. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60062. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60063. if (parsedParticleSystem.colorGradients) {
  60064. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60065. var colorGradient = _a[_i];
  60066. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60067. }
  60068. }
  60069. if (parsedParticleSystem.rampGradients) {
  60070. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60071. var rampGradient = _c[_b];
  60072. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60073. }
  60074. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60075. }
  60076. if (parsedParticleSystem.colorRemapGradients) {
  60077. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60078. var colorRemapGradient = _e[_d];
  60079. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60080. }
  60081. }
  60082. if (parsedParticleSystem.alphaRemapGradients) {
  60083. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60084. var alphaRemapGradient = _g[_f];
  60085. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60086. }
  60087. }
  60088. if (parsedParticleSystem.sizeGradients) {
  60089. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60090. var sizeGradient = _j[_h];
  60091. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60092. }
  60093. }
  60094. if (parsedParticleSystem.sizeGradients) {
  60095. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60096. var sizeGradient = _l[_k];
  60097. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60098. }
  60099. }
  60100. if (parsedParticleSystem.angularSpeedGradients) {
  60101. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60102. var angularSpeedGradient = _o[_m];
  60103. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60104. }
  60105. }
  60106. if (parsedParticleSystem.velocityGradients) {
  60107. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60108. var velocityGradient = _q[_p];
  60109. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60110. }
  60111. }
  60112. if (parsedParticleSystem.dragGradients) {
  60113. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60114. var dragGradient = _s[_r];
  60115. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60116. }
  60117. }
  60118. if (parsedParticleSystem.emitRateGradients) {
  60119. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60120. var emitRateGradient = _u[_t];
  60121. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60122. }
  60123. }
  60124. if (parsedParticleSystem.startSizeGradients) {
  60125. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60126. var startSizeGradient = _w[_v];
  60127. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60128. }
  60129. }
  60130. if (parsedParticleSystem.lifeTimeGradients) {
  60131. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60132. var lifeTimeGradient = _y[_x];
  60133. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60134. }
  60135. }
  60136. if (parsedParticleSystem.limitVelocityGradients) {
  60137. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  60138. var limitVelocityGradient = _0[_z];
  60139. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  60140. }
  60141. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  60142. }
  60143. if (parsedParticleSystem.noiseTexture) {
  60144. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  60145. }
  60146. // Emitter
  60147. var emitterType;
  60148. if (parsedParticleSystem.particleEmitterType) {
  60149. switch (parsedParticleSystem.particleEmitterType.type) {
  60150. case "SphereParticleEmitter":
  60151. emitterType = new BABYLON.SphereParticleEmitter();
  60152. break;
  60153. case "SphereDirectedParticleEmitter":
  60154. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  60155. break;
  60156. case "ConeEmitter":
  60157. case "ConeParticleEmitter":
  60158. emitterType = new BABYLON.ConeParticleEmitter();
  60159. break;
  60160. case "CylinderParticleEmitter":
  60161. emitterType = new BABYLON.CylinderParticleEmitter();
  60162. break;
  60163. case "HemisphericParticleEmitter":
  60164. emitterType = new BABYLON.HemisphericParticleEmitter();
  60165. break;
  60166. case "BoxEmitter":
  60167. case "BoxParticleEmitter":
  60168. default:
  60169. emitterType = new BABYLON.BoxParticleEmitter();
  60170. break;
  60171. }
  60172. emitterType.parse(parsedParticleSystem.particleEmitterType);
  60173. }
  60174. else {
  60175. emitterType = new BABYLON.BoxParticleEmitter();
  60176. emitterType.parse(parsedParticleSystem);
  60177. }
  60178. particleSystem.particleEmitterType = emitterType;
  60179. // Animation sheet
  60180. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  60181. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  60182. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  60183. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  60184. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  60185. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  60186. };
  60187. /**
  60188. * Parses a JSON object to create a particle system.
  60189. * @param parsedParticleSystem The JSON object to parse
  60190. * @param scene The scene to create the particle system in
  60191. * @param rootUrl The root url to use to load external dependencies like texture
  60192. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  60193. * @returns the Parsed particle system
  60194. */
  60195. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  60196. if (doNotStart === void 0) { doNotStart = false; }
  60197. var name = parsedParticleSystem.name;
  60198. var custom = null;
  60199. var program = null;
  60200. if (parsedParticleSystem.customShader) {
  60201. program = parsedParticleSystem.customShader;
  60202. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60203. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60204. }
  60205. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  60206. particleSystem.customShader = program;
  60207. if (parsedParticleSystem.id) {
  60208. particleSystem.id = parsedParticleSystem.id;
  60209. }
  60210. // SubEmitters
  60211. if (parsedParticleSystem.subEmitters) {
  60212. particleSystem.subEmitters = [];
  60213. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  60214. var cell = _a[_i];
  60215. var cellArray = [];
  60216. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  60217. var sub = cell_1[_b];
  60218. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  60219. }
  60220. particleSystem.subEmitters.push(cellArray);
  60221. }
  60222. }
  60223. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60224. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  60225. // Auto start
  60226. if (parsedParticleSystem.preventAutoStart) {
  60227. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  60228. }
  60229. if (!doNotStart && !particleSystem.preventAutoStart) {
  60230. particleSystem.start();
  60231. }
  60232. return particleSystem;
  60233. };
  60234. /**
  60235. * Billboard mode will only apply to Y axis
  60236. */
  60237. ParticleSystem.BILLBOARDMODE_Y = 2;
  60238. /**
  60239. * Billboard mode will apply to all axes
  60240. */
  60241. ParticleSystem.BILLBOARDMODE_ALL = 7;
  60242. /**
  60243. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  60244. */
  60245. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  60246. return ParticleSystem;
  60247. }(BABYLON.BaseParticleSystem));
  60248. BABYLON.ParticleSystem = ParticleSystem;
  60249. })(BABYLON || (BABYLON = {}));
  60250. //# sourceMappingURL=babylon.particleSystem.js.map
  60251. var BABYLON;
  60252. (function (BABYLON) {
  60253. /**
  60254. * Particle emitter emitting particles from the inside of a box.
  60255. * It emits the particles randomly between 2 given directions.
  60256. */
  60257. var BoxParticleEmitter = /** @class */ (function () {
  60258. /**
  60259. * Creates a new instance BoxParticleEmitter
  60260. */
  60261. function BoxParticleEmitter() {
  60262. /**
  60263. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60264. */
  60265. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60266. /**
  60267. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60268. */
  60269. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60270. /**
  60271. * 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.
  60272. */
  60273. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  60274. /**
  60275. * 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.
  60276. */
  60277. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  60278. }
  60279. /**
  60280. * Called by the particle System when the direction is computed for the created particle.
  60281. * @param worldMatrix is the world matrix of the particle system
  60282. * @param directionToUpdate is the direction vector to update with the result
  60283. * @param particle is the particle we are computed the direction for
  60284. */
  60285. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60286. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60287. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60288. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60289. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60290. };
  60291. /**
  60292. * Called by the particle System when the position is computed for the created particle.
  60293. * @param worldMatrix is the world matrix of the particle system
  60294. * @param positionToUpdate is the position vector to update with the result
  60295. * @param particle is the particle we are computed the position for
  60296. */
  60297. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60298. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  60299. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  60300. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  60301. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60302. };
  60303. /**
  60304. * Clones the current emitter and returns a copy of it
  60305. * @returns the new emitter
  60306. */
  60307. BoxParticleEmitter.prototype.clone = function () {
  60308. var newOne = new BoxParticleEmitter();
  60309. BABYLON.Tools.DeepCopy(this, newOne);
  60310. return newOne;
  60311. };
  60312. /**
  60313. * Called by the GPUParticleSystem to setup the update shader
  60314. * @param effect defines the update shader
  60315. */
  60316. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  60317. effect.setVector3("direction1", this.direction1);
  60318. effect.setVector3("direction2", this.direction2);
  60319. effect.setVector3("minEmitBox", this.minEmitBox);
  60320. effect.setVector3("maxEmitBox", this.maxEmitBox);
  60321. };
  60322. /**
  60323. * Returns a string to use to update the GPU particles update shader
  60324. * @returns a string containng the defines string
  60325. */
  60326. BoxParticleEmitter.prototype.getEffectDefines = function () {
  60327. return "#define BOXEMITTER";
  60328. };
  60329. /**
  60330. * Returns the string "BoxParticleEmitter"
  60331. * @returns a string containing the class name
  60332. */
  60333. BoxParticleEmitter.prototype.getClassName = function () {
  60334. return "BoxParticleEmitter";
  60335. };
  60336. /**
  60337. * Serializes the particle system to a JSON object.
  60338. * @returns the JSON object
  60339. */
  60340. BoxParticleEmitter.prototype.serialize = function () {
  60341. var serializationObject = {};
  60342. serializationObject.type = this.getClassName();
  60343. serializationObject.direction1 = this.direction1.asArray();
  60344. serializationObject.direction2 = this.direction2.asArray();
  60345. serializationObject.minEmitBox = this.minEmitBox.asArray();
  60346. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  60347. return serializationObject;
  60348. };
  60349. /**
  60350. * Parse properties from a JSON object
  60351. * @param serializationObject defines the JSON object
  60352. */
  60353. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  60354. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60355. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60356. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  60357. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  60358. };
  60359. return BoxParticleEmitter;
  60360. }());
  60361. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  60362. })(BABYLON || (BABYLON = {}));
  60363. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  60364. var BABYLON;
  60365. (function (BABYLON) {
  60366. /**
  60367. * Particle emitter emitting particles from the inside of a cylinder.
  60368. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  60369. */
  60370. var CylinderParticleEmitter = /** @class */ (function () {
  60371. /**
  60372. * Creates a new instance CylinderParticleEmitter
  60373. * @param radius the radius of the emission cylinder (1 by default)
  60374. * @param height the height of the emission cylinder (1 by default)
  60375. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60376. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60377. */
  60378. function CylinderParticleEmitter(
  60379. /**
  60380. * The radius of the emission cylinder.
  60381. */
  60382. radius,
  60383. /**
  60384. * The height of the emission cylinder.
  60385. */
  60386. height,
  60387. /**
  60388. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60389. */
  60390. radiusRange,
  60391. /**
  60392. * How much to randomize the particle direction [0-1].
  60393. */
  60394. directionRandomizer) {
  60395. if (radius === void 0) { radius = 1; }
  60396. if (height === void 0) { height = 1; }
  60397. if (radiusRange === void 0) { radiusRange = 1; }
  60398. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60399. this.radius = radius;
  60400. this.height = height;
  60401. this.radiusRange = radiusRange;
  60402. this.directionRandomizer = directionRandomizer;
  60403. }
  60404. /**
  60405. * Called by the particle System when the direction is computed for the created particle.
  60406. * @param worldMatrix is the world matrix of the particle system
  60407. * @param directionToUpdate is the direction vector to update with the result
  60408. * @param particle is the particle we are computed the direction for
  60409. */
  60410. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60411. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60412. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  60413. var angle = Math.atan2(direction.x, direction.z);
  60414. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  60415. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  60416. direction.x = Math.sin(angle);
  60417. direction.z = Math.cos(angle);
  60418. direction.normalize();
  60419. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60420. };
  60421. /**
  60422. * Called by the particle System when the position is computed for the created particle.
  60423. * @param worldMatrix is the world matrix of the particle system
  60424. * @param positionToUpdate is the position vector to update with the result
  60425. * @param particle is the particle we are computed the position for
  60426. */
  60427. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60428. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  60429. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60430. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  60431. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  60432. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  60433. var xPos = positionRadius * Math.cos(angle);
  60434. var zPos = positionRadius * Math.sin(angle);
  60435. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  60436. };
  60437. /**
  60438. * Clones the current emitter and returns a copy of it
  60439. * @returns the new emitter
  60440. */
  60441. CylinderParticleEmitter.prototype.clone = function () {
  60442. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  60443. BABYLON.Tools.DeepCopy(this, newOne);
  60444. return newOne;
  60445. };
  60446. /**
  60447. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60448. * @param effect defines the update shader
  60449. */
  60450. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  60451. effect.setFloat("radius", this.radius);
  60452. effect.setFloat("height", this.height);
  60453. effect.setFloat("radiusRange", this.radiusRange);
  60454. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60455. };
  60456. /**
  60457. * Returns a string to use to update the GPU particles update shader
  60458. * @returns a string containng the defines string
  60459. */
  60460. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  60461. return "#define CYLINDEREMITTER";
  60462. };
  60463. /**
  60464. * Returns the string "CylinderParticleEmitter"
  60465. * @returns a string containing the class name
  60466. */
  60467. CylinderParticleEmitter.prototype.getClassName = function () {
  60468. return "CylinderParticleEmitter";
  60469. };
  60470. /**
  60471. * Serializes the particle system to a JSON object.
  60472. * @returns the JSON object
  60473. */
  60474. CylinderParticleEmitter.prototype.serialize = function () {
  60475. var serializationObject = {};
  60476. serializationObject.type = this.getClassName();
  60477. serializationObject.radius = this.radius;
  60478. serializationObject.height = this.height;
  60479. serializationObject.radiusRange = this.radiusRange;
  60480. serializationObject.directionRandomizer = this.directionRandomizer;
  60481. return serializationObject;
  60482. };
  60483. /**
  60484. * Parse properties from a JSON object
  60485. * @param serializationObject defines the JSON object
  60486. */
  60487. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  60488. this.radius = serializationObject.radius;
  60489. this.height = serializationObject.height;
  60490. this.radiusRange = serializationObject.radiusRange;
  60491. this.directionRandomizer = serializationObject.directionRandomizer;
  60492. };
  60493. return CylinderParticleEmitter;
  60494. }());
  60495. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60496. /**
  60497. * Particle emitter emitting particles from the inside of a cylinder.
  60498. * It emits the particles randomly between two vectors.
  60499. */
  60500. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60501. __extends(CylinderDirectedParticleEmitter, _super);
  60502. /**
  60503. * Creates a new instance CylinderDirectedParticleEmitter
  60504. * @param radius the radius of the emission cylinder (1 by default)
  60505. * @param height the height of the emission cylinder (1 by default)
  60506. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60507. * @param direction1 the min limit of the emission direction (up vector by default)
  60508. * @param direction2 the max limit of the emission direction (up vector by default)
  60509. */
  60510. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60511. /**
  60512. * The min limit of the emission direction.
  60513. */
  60514. direction1,
  60515. /**
  60516. * The max limit of the emission direction.
  60517. */
  60518. direction2) {
  60519. if (radius === void 0) { radius = 1; }
  60520. if (height === void 0) { height = 1; }
  60521. if (radiusRange === void 0) { radiusRange = 1; }
  60522. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60523. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60524. var _this = _super.call(this, radius, height, radiusRange) || this;
  60525. _this.direction1 = direction1;
  60526. _this.direction2 = direction2;
  60527. return _this;
  60528. }
  60529. /**
  60530. * Called by the particle System when the direction is computed for the created particle.
  60531. * @param worldMatrix is the world matrix of the particle system
  60532. * @param directionToUpdate is the direction vector to update with the result
  60533. * @param particle is the particle we are computed the direction for
  60534. */
  60535. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60536. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60537. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60538. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60539. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60540. };
  60541. /**
  60542. * Clones the current emitter and returns a copy of it
  60543. * @returns the new emitter
  60544. */
  60545. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60546. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60547. BABYLON.Tools.DeepCopy(this, newOne);
  60548. return newOne;
  60549. };
  60550. /**
  60551. * Called by the GPUParticleSystem to setup the update shader
  60552. * @param effect defines the update shader
  60553. */
  60554. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60555. effect.setFloat("radius", this.radius);
  60556. effect.setFloat("height", this.height);
  60557. effect.setFloat("radiusRange", this.radiusRange);
  60558. effect.setVector3("direction1", this.direction1);
  60559. effect.setVector3("direction2", this.direction2);
  60560. };
  60561. /**
  60562. * Returns a string to use to update the GPU particles update shader
  60563. * @returns a string containng the defines string
  60564. */
  60565. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60566. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60567. };
  60568. /**
  60569. * Returns the string "CylinderDirectedParticleEmitter"
  60570. * @returns a string containing the class name
  60571. */
  60572. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60573. return "CylinderDirectedParticleEmitter";
  60574. };
  60575. /**
  60576. * Serializes the particle system to a JSON object.
  60577. * @returns the JSON object
  60578. */
  60579. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60580. var serializationObject = _super.prototype.serialize.call(this);
  60581. serializationObject.direction1 = this.direction1.asArray();
  60582. serializationObject.direction2 = this.direction2.asArray();
  60583. return serializationObject;
  60584. };
  60585. /**
  60586. * Parse properties from a JSON object
  60587. * @param serializationObject defines the JSON object
  60588. */
  60589. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60590. _super.prototype.parse.call(this, serializationObject);
  60591. this.direction1.copyFrom(serializationObject.direction1);
  60592. this.direction2.copyFrom(serializationObject.direction2);
  60593. };
  60594. return CylinderDirectedParticleEmitter;
  60595. }(CylinderParticleEmitter));
  60596. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60597. })(BABYLON || (BABYLON = {}));
  60598. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60599. var BABYLON;
  60600. (function (BABYLON) {
  60601. /**
  60602. * Particle emitter emitting particles from the inside of a cone.
  60603. * It emits the particles alongside the cone volume from the base to the particle.
  60604. * The emission direction might be randomized.
  60605. */
  60606. var ConeParticleEmitter = /** @class */ (function () {
  60607. /**
  60608. * Creates a new instance ConeParticleEmitter
  60609. * @param radius the radius of the emission cone (1 by default)
  60610. * @param angles the cone base angle (PI by default)
  60611. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60612. */
  60613. function ConeParticleEmitter(radius, angle,
  60614. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60615. directionRandomizer) {
  60616. if (radius === void 0) { radius = 1; }
  60617. if (angle === void 0) { angle = Math.PI; }
  60618. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60619. this.directionRandomizer = directionRandomizer;
  60620. /**
  60621. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60622. */
  60623. this.radiusRange = 1;
  60624. /**
  60625. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60626. */
  60627. this.heightRange = 1;
  60628. /**
  60629. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60630. */
  60631. this.emitFromSpawnPointOnly = false;
  60632. this.angle = angle;
  60633. this.radius = radius;
  60634. }
  60635. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60636. /**
  60637. * Gets or sets the radius of the emission cone
  60638. */
  60639. get: function () {
  60640. return this._radius;
  60641. },
  60642. set: function (value) {
  60643. this._radius = value;
  60644. this._buildHeight();
  60645. },
  60646. enumerable: true,
  60647. configurable: true
  60648. });
  60649. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60650. /**
  60651. * Gets or sets the angle of the emission cone
  60652. */
  60653. get: function () {
  60654. return this._angle;
  60655. },
  60656. set: function (value) {
  60657. this._angle = value;
  60658. this._buildHeight();
  60659. },
  60660. enumerable: true,
  60661. configurable: true
  60662. });
  60663. ConeParticleEmitter.prototype._buildHeight = function () {
  60664. if (this._angle !== 0) {
  60665. this._height = this._radius / Math.tan(this._angle / 2);
  60666. }
  60667. else {
  60668. this._height = 1;
  60669. }
  60670. };
  60671. /**
  60672. * Called by the particle System when the direction is computed for the created particle.
  60673. * @param worldMatrix is the world matrix of the particle system
  60674. * @param directionToUpdate is the direction vector to update with the result
  60675. * @param particle is the particle we are computed the direction for
  60676. */
  60677. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60678. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60679. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60680. }
  60681. else {
  60682. // measure the direction Vector from the emitter to the particle.
  60683. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60684. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60685. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60686. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60687. direction.x += randX;
  60688. direction.y += randY;
  60689. direction.z += randZ;
  60690. direction.normalize();
  60691. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60692. }
  60693. };
  60694. /**
  60695. * Called by the particle System when the position is computed for the created particle.
  60696. * @param worldMatrix is the world matrix of the particle system
  60697. * @param positionToUpdate is the position vector to update with the result
  60698. * @param particle is the particle we are computed the position for
  60699. */
  60700. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60701. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60702. var h;
  60703. if (!this.emitFromSpawnPointOnly) {
  60704. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60705. // Better distribution in a cone at normal angles.
  60706. h = 1 - h * h;
  60707. }
  60708. else {
  60709. h = 0.0001;
  60710. }
  60711. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  60712. radius = radius * h;
  60713. var randX = radius * Math.sin(s);
  60714. var randZ = radius * Math.cos(s);
  60715. var randY = h * this._height;
  60716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60717. };
  60718. /**
  60719. * Clones the current emitter and returns a copy of it
  60720. * @returns the new emitter
  60721. */
  60722. ConeParticleEmitter.prototype.clone = function () {
  60723. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60724. BABYLON.Tools.DeepCopy(this, newOne);
  60725. return newOne;
  60726. };
  60727. /**
  60728. * Called by the GPUParticleSystem to setup the update shader
  60729. * @param effect defines the update shader
  60730. */
  60731. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60732. effect.setFloat2("radius", this._radius, this.radiusRange);
  60733. effect.setFloat("coneAngle", this._angle);
  60734. effect.setFloat2("height", this._height, this.heightRange);
  60735. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60736. };
  60737. /**
  60738. * Returns a string to use to update the GPU particles update shader
  60739. * @returns a string containng the defines string
  60740. */
  60741. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60742. var defines = "#define CONEEMITTER";
  60743. if (this.emitFromSpawnPointOnly) {
  60744. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60745. }
  60746. return defines;
  60747. };
  60748. /**
  60749. * Returns the string "ConeParticleEmitter"
  60750. * @returns a string containing the class name
  60751. */
  60752. ConeParticleEmitter.prototype.getClassName = function () {
  60753. return "ConeParticleEmitter";
  60754. };
  60755. /**
  60756. * Serializes the particle system to a JSON object.
  60757. * @returns the JSON object
  60758. */
  60759. ConeParticleEmitter.prototype.serialize = function () {
  60760. var serializationObject = {};
  60761. serializationObject.type = this.getClassName();
  60762. serializationObject.radius = this._radius;
  60763. serializationObject.angle = this._angle;
  60764. serializationObject.directionRandomizer = this.directionRandomizer;
  60765. return serializationObject;
  60766. };
  60767. /**
  60768. * Parse properties from a JSON object
  60769. * @param serializationObject defines the JSON object
  60770. */
  60771. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60772. this.radius = serializationObject.radius;
  60773. this.angle = serializationObject.angle;
  60774. this.directionRandomizer = serializationObject.directionRandomizer;
  60775. };
  60776. return ConeParticleEmitter;
  60777. }());
  60778. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60779. })(BABYLON || (BABYLON = {}));
  60780. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60781. var BABYLON;
  60782. (function (BABYLON) {
  60783. /**
  60784. * Particle emitter emitting particles from the inside of a sphere.
  60785. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60786. */
  60787. var SphereParticleEmitter = /** @class */ (function () {
  60788. /**
  60789. * Creates a new instance SphereParticleEmitter
  60790. * @param radius the radius of the emission sphere (1 by default)
  60791. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60792. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60793. */
  60794. function SphereParticleEmitter(
  60795. /**
  60796. * The radius of the emission sphere.
  60797. */
  60798. radius,
  60799. /**
  60800. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60801. */
  60802. radiusRange,
  60803. /**
  60804. * How much to randomize the particle direction [0-1].
  60805. */
  60806. directionRandomizer) {
  60807. if (radius === void 0) { radius = 1; }
  60808. if (radiusRange === void 0) { radiusRange = 1; }
  60809. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60810. this.radius = radius;
  60811. this.radiusRange = radiusRange;
  60812. this.directionRandomizer = directionRandomizer;
  60813. }
  60814. /**
  60815. * Called by the particle System when the direction is computed for the created particle.
  60816. * @param worldMatrix is the world matrix of the particle system
  60817. * @param directionToUpdate is the direction vector to update with the result
  60818. * @param particle is the particle we are computed the direction for
  60819. */
  60820. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60821. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60822. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60823. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60824. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60825. direction.x += randX;
  60826. direction.y += randY;
  60827. direction.z += randZ;
  60828. direction.normalize();
  60829. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60830. };
  60831. /**
  60832. * Called by the particle System when the position is computed for the created particle.
  60833. * @param worldMatrix is the world matrix of the particle system
  60834. * @param positionToUpdate is the position vector to update with the result
  60835. * @param particle is the particle we are computed the position for
  60836. */
  60837. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60838. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60839. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60840. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60841. var theta = Math.acos(2 * v - 1);
  60842. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60843. var randY = randRadius * Math.cos(theta);
  60844. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60845. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60846. };
  60847. /**
  60848. * Clones the current emitter and returns a copy of it
  60849. * @returns the new emitter
  60850. */
  60851. SphereParticleEmitter.prototype.clone = function () {
  60852. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60853. BABYLON.Tools.DeepCopy(this, newOne);
  60854. return newOne;
  60855. };
  60856. /**
  60857. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60858. * @param effect defines the update shader
  60859. */
  60860. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60861. effect.setFloat("radius", this.radius);
  60862. effect.setFloat("radiusRange", this.radiusRange);
  60863. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60864. };
  60865. /**
  60866. * Returns a string to use to update the GPU particles update shader
  60867. * @returns a string containng the defines string
  60868. */
  60869. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60870. return "#define SPHEREEMITTER";
  60871. };
  60872. /**
  60873. * Returns the string "SphereParticleEmitter"
  60874. * @returns a string containing the class name
  60875. */
  60876. SphereParticleEmitter.prototype.getClassName = function () {
  60877. return "SphereParticleEmitter";
  60878. };
  60879. /**
  60880. * Serializes the particle system to a JSON object.
  60881. * @returns the JSON object
  60882. */
  60883. SphereParticleEmitter.prototype.serialize = function () {
  60884. var serializationObject = {};
  60885. serializationObject.type = this.getClassName();
  60886. serializationObject.radius = this.radius;
  60887. serializationObject.radiusRange = this.radiusRange;
  60888. serializationObject.directionRandomizer = this.directionRandomizer;
  60889. return serializationObject;
  60890. };
  60891. /**
  60892. * Parse properties from a JSON object
  60893. * @param serializationObject defines the JSON object
  60894. */
  60895. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60896. this.radius = serializationObject.radius;
  60897. this.radiusRange = serializationObject.radiusRange;
  60898. this.directionRandomizer = serializationObject.directionRandomizer;
  60899. };
  60900. return SphereParticleEmitter;
  60901. }());
  60902. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60903. /**
  60904. * Particle emitter emitting particles from the inside of a sphere.
  60905. * It emits the particles randomly between two vectors.
  60906. */
  60907. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60908. __extends(SphereDirectedParticleEmitter, _super);
  60909. /**
  60910. * Creates a new instance SphereDirectedParticleEmitter
  60911. * @param radius the radius of the emission sphere (1 by default)
  60912. * @param direction1 the min limit of the emission direction (up vector by default)
  60913. * @param direction2 the max limit of the emission direction (up vector by default)
  60914. */
  60915. function SphereDirectedParticleEmitter(radius,
  60916. /**
  60917. * The min limit of the emission direction.
  60918. */
  60919. direction1,
  60920. /**
  60921. * The max limit of the emission direction.
  60922. */
  60923. direction2) {
  60924. if (radius === void 0) { radius = 1; }
  60925. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60926. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60927. var _this = _super.call(this, radius) || this;
  60928. _this.direction1 = direction1;
  60929. _this.direction2 = direction2;
  60930. return _this;
  60931. }
  60932. /**
  60933. * Called by the particle System when the direction is computed for the created particle.
  60934. * @param worldMatrix is the world matrix of the particle system
  60935. * @param directionToUpdate is the direction vector to update with the result
  60936. * @param particle is the particle we are computed the direction for
  60937. */
  60938. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60939. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60940. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60941. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60942. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60943. };
  60944. /**
  60945. * Clones the current emitter and returns a copy of it
  60946. * @returns the new emitter
  60947. */
  60948. SphereDirectedParticleEmitter.prototype.clone = function () {
  60949. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60950. BABYLON.Tools.DeepCopy(this, newOne);
  60951. return newOne;
  60952. };
  60953. /**
  60954. * Called by the GPUParticleSystem to setup the update shader
  60955. * @param effect defines the update shader
  60956. */
  60957. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60958. effect.setFloat("radius", this.radius);
  60959. effect.setFloat("radiusRange", this.radiusRange);
  60960. effect.setVector3("direction1", this.direction1);
  60961. effect.setVector3("direction2", this.direction2);
  60962. };
  60963. /**
  60964. * Returns a string to use to update the GPU particles update shader
  60965. * @returns a string containng the defines string
  60966. */
  60967. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60968. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60969. };
  60970. /**
  60971. * Returns the string "SphereDirectedParticleEmitter"
  60972. * @returns a string containing the class name
  60973. */
  60974. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60975. return "SphereDirectedParticleEmitter";
  60976. };
  60977. /**
  60978. * Serializes the particle system to a JSON object.
  60979. * @returns the JSON object
  60980. */
  60981. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60982. var serializationObject = _super.prototype.serialize.call(this);
  60983. serializationObject.direction1 = this.direction1.asArray();
  60984. serializationObject.direction2 = this.direction2.asArray();
  60985. return serializationObject;
  60986. };
  60987. /**
  60988. * Parse properties from a JSON object
  60989. * @param serializationObject defines the JSON object
  60990. */
  60991. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60992. _super.prototype.parse.call(this, serializationObject);
  60993. this.direction1.copyFrom(serializationObject.direction1);
  60994. this.direction2.copyFrom(serializationObject.direction2);
  60995. };
  60996. return SphereDirectedParticleEmitter;
  60997. }(SphereParticleEmitter));
  60998. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60999. })(BABYLON || (BABYLON = {}));
  61000. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61001. var BABYLON;
  61002. (function (BABYLON) {
  61003. /**
  61004. * Particle emitter emitting particles from the inside of a hemisphere.
  61005. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61006. */
  61007. var HemisphericParticleEmitter = /** @class */ (function () {
  61008. /**
  61009. * Creates a new instance HemisphericParticleEmitter
  61010. * @param radius the radius of the emission hemisphere (1 by default)
  61011. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61012. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61013. */
  61014. function HemisphericParticleEmitter(
  61015. /**
  61016. * The radius of the emission hemisphere.
  61017. */
  61018. radius,
  61019. /**
  61020. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61021. */
  61022. radiusRange,
  61023. /**
  61024. * How much to randomize the particle direction [0-1].
  61025. */
  61026. directionRandomizer) {
  61027. if (radius === void 0) { radius = 1; }
  61028. if (radiusRange === void 0) { radiusRange = 1; }
  61029. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61030. this.radius = radius;
  61031. this.radiusRange = radiusRange;
  61032. this.directionRandomizer = directionRandomizer;
  61033. }
  61034. /**
  61035. * Called by the particle System when the direction is computed for the created particle.
  61036. * @param worldMatrix is the world matrix of the particle system
  61037. * @param directionToUpdate is the direction vector to update with the result
  61038. * @param particle is the particle we are computed the direction for
  61039. */
  61040. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61041. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61042. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61043. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61044. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61045. direction.x += randX;
  61046. direction.y += randY;
  61047. direction.z += randZ;
  61048. direction.normalize();
  61049. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61050. };
  61051. /**
  61052. * Called by the particle System when the position is computed for the created particle.
  61053. * @param worldMatrix is the world matrix of the particle system
  61054. * @param positionToUpdate is the position vector to update with the result
  61055. * @param particle is the particle we are computed the position for
  61056. */
  61057. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61058. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61059. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61060. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61061. var theta = Math.acos(2 * v - 1);
  61062. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61063. var randY = randRadius * Math.cos(theta);
  61064. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61065. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61066. };
  61067. /**
  61068. * Clones the current emitter and returns a copy of it
  61069. * @returns the new emitter
  61070. */
  61071. HemisphericParticleEmitter.prototype.clone = function () {
  61072. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61073. BABYLON.Tools.DeepCopy(this, newOne);
  61074. return newOne;
  61075. };
  61076. /**
  61077. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61078. * @param effect defines the update shader
  61079. */
  61080. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61081. effect.setFloat("radius", this.radius);
  61082. effect.setFloat("radiusRange", this.radiusRange);
  61083. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61084. };
  61085. /**
  61086. * Returns a string to use to update the GPU particles update shader
  61087. * @returns a string containng the defines string
  61088. */
  61089. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61090. return "#define HEMISPHERICEMITTER";
  61091. };
  61092. /**
  61093. * Returns the string "HemisphericParticleEmitter"
  61094. * @returns a string containing the class name
  61095. */
  61096. HemisphericParticleEmitter.prototype.getClassName = function () {
  61097. return "HemisphericParticleEmitter";
  61098. };
  61099. /**
  61100. * Serializes the particle system to a JSON object.
  61101. * @returns the JSON object
  61102. */
  61103. HemisphericParticleEmitter.prototype.serialize = function () {
  61104. var serializationObject = {};
  61105. serializationObject.type = this.getClassName();
  61106. serializationObject.radius = this.radius;
  61107. serializationObject.radiusRange = this.radiusRange;
  61108. serializationObject.directionRandomizer = this.directionRandomizer;
  61109. return serializationObject;
  61110. };
  61111. /**
  61112. * Parse properties from a JSON object
  61113. * @param serializationObject defines the JSON object
  61114. */
  61115. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61116. this.radius = serializationObject.radius;
  61117. this.radiusRange = serializationObject.radiusRange;
  61118. this.directionRandomizer = serializationObject.directionRandomizer;
  61119. };
  61120. return HemisphericParticleEmitter;
  61121. }());
  61122. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61123. })(BABYLON || (BABYLON = {}));
  61124. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61125. var BABYLON;
  61126. (function (BABYLON) {
  61127. /**
  61128. * Particle emitter emitting particles from a point.
  61129. * It emits the particles randomly between 2 given directions.
  61130. */
  61131. var PointParticleEmitter = /** @class */ (function () {
  61132. /**
  61133. * Creates a new instance PointParticleEmitter
  61134. */
  61135. function PointParticleEmitter() {
  61136. /**
  61137. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61138. */
  61139. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61140. /**
  61141. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61142. */
  61143. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61144. }
  61145. /**
  61146. * Called by the particle System when the direction is computed for the created particle.
  61147. * @param worldMatrix is the world matrix of the particle system
  61148. * @param directionToUpdate is the direction vector to update with the result
  61149. * @param particle is the particle we are computed the direction for
  61150. */
  61151. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61152. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61153. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61154. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61155. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61156. };
  61157. /**
  61158. * Called by the particle System when the position is computed for the created particle.
  61159. * @param worldMatrix is the world matrix of the particle system
  61160. * @param positionToUpdate is the position vector to update with the result
  61161. * @param particle is the particle we are computed the position for
  61162. */
  61163. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  61165. };
  61166. /**
  61167. * Clones the current emitter and returns a copy of it
  61168. * @returns the new emitter
  61169. */
  61170. PointParticleEmitter.prototype.clone = function () {
  61171. var newOne = new PointParticleEmitter();
  61172. BABYLON.Tools.DeepCopy(this, newOne);
  61173. return newOne;
  61174. };
  61175. /**
  61176. * Called by the GPUParticleSystem to setup the update shader
  61177. * @param effect defines the update shader
  61178. */
  61179. PointParticleEmitter.prototype.applyToShader = function (effect) {
  61180. effect.setVector3("direction1", this.direction1);
  61181. effect.setVector3("direction2", this.direction2);
  61182. };
  61183. /**
  61184. * Returns a string to use to update the GPU particles update shader
  61185. * @returns a string containng the defines string
  61186. */
  61187. PointParticleEmitter.prototype.getEffectDefines = function () {
  61188. return "#define POINTEMITTER";
  61189. };
  61190. /**
  61191. * Returns the string "PointParticleEmitter"
  61192. * @returns a string containing the class name
  61193. */
  61194. PointParticleEmitter.prototype.getClassName = function () {
  61195. return "PointParticleEmitter";
  61196. };
  61197. /**
  61198. * Serializes the particle system to a JSON object.
  61199. * @returns the JSON object
  61200. */
  61201. PointParticleEmitter.prototype.serialize = function () {
  61202. var serializationObject = {};
  61203. serializationObject.type = this.getClassName();
  61204. serializationObject.direction1 = this.direction1.asArray();
  61205. serializationObject.direction2 = this.direction2.asArray();
  61206. return serializationObject;
  61207. };
  61208. /**
  61209. * Parse properties from a JSON object
  61210. * @param serializationObject defines the JSON object
  61211. */
  61212. PointParticleEmitter.prototype.parse = function (serializationObject) {
  61213. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61214. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61215. };
  61216. return PointParticleEmitter;
  61217. }());
  61218. BABYLON.PointParticleEmitter = PointParticleEmitter;
  61219. })(BABYLON || (BABYLON = {}));
  61220. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  61221. var BABYLON;
  61222. (function (BABYLON) {
  61223. // Adds the parsers to the scene parsers.
  61224. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  61225. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  61226. if (!individualParser) {
  61227. return;
  61228. }
  61229. // Particles Systems
  61230. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61231. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61232. var parsedParticleSystem = parsedData.particleSystems[index];
  61233. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  61234. }
  61235. }
  61236. });
  61237. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  61238. if (parsedParticleSystem.activeParticleCount) {
  61239. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61240. return ps;
  61241. }
  61242. else {
  61243. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61244. return ps;
  61245. }
  61246. });
  61247. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  61248. if (uniformsNames === void 0) { uniformsNames = []; }
  61249. if (samplers === void 0) { samplers = []; }
  61250. if (defines === void 0) { defines = ""; }
  61251. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  61252. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  61253. if (defines.indexOf(" BILLBOARD") === -1) {
  61254. defines += "\n#define BILLBOARD\n";
  61255. }
  61256. if (samplers.indexOf("diffuseSampler") === -1) {
  61257. samplers.push("diffuseSampler");
  61258. }
  61259. return this.createEffect({
  61260. vertex: "particles",
  61261. fragmentElement: fragmentName
  61262. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  61263. };
  61264. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  61265. var results = new Array();
  61266. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61267. var particleSystem = this.getScene().particleSystems[index];
  61268. if (particleSystem.emitter === this) {
  61269. results.push(particleSystem);
  61270. }
  61271. }
  61272. return results;
  61273. };
  61274. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  61275. var results = new Array();
  61276. var descendants = this.getDescendants();
  61277. descendants.push(this);
  61278. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61279. var particleSystem = this.getScene().particleSystems[index];
  61280. var emitter = particleSystem.emitter;
  61281. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  61282. results.push(particleSystem);
  61283. }
  61284. }
  61285. return results;
  61286. };
  61287. })(BABYLON || (BABYLON = {}));
  61288. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  61289. var BABYLON;
  61290. (function (BABYLON) {
  61291. /**
  61292. * Type of sub emitter
  61293. */
  61294. var SubEmitterType;
  61295. (function (SubEmitterType) {
  61296. /**
  61297. * Attached to the particle over it's lifetime
  61298. */
  61299. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  61300. /**
  61301. * Created when the particle dies
  61302. */
  61303. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  61304. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  61305. /**
  61306. * Sub emitter class used to emit particles from an existing particle
  61307. */
  61308. var SubEmitter = /** @class */ (function () {
  61309. /**
  61310. * Creates a sub emitter
  61311. * @param particleSystem the particle system to be used by the sub emitter
  61312. */
  61313. function SubEmitter(
  61314. /**
  61315. * the particle system to be used by the sub emitter
  61316. */
  61317. particleSystem) {
  61318. this.particleSystem = particleSystem;
  61319. /**
  61320. * Type of the submitter (Default: END)
  61321. */
  61322. this.type = SubEmitterType.END;
  61323. /**
  61324. * 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)
  61325. * Note: This only is supported when using an emitter of type Mesh
  61326. */
  61327. this.inheritDirection = false;
  61328. /**
  61329. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  61330. */
  61331. this.inheritedVelocityAmount = 0;
  61332. }
  61333. /**
  61334. * Clones the sub emitter
  61335. * @returns the cloned sub emitter
  61336. */
  61337. SubEmitter.prototype.clone = function () {
  61338. // Clone particle system
  61339. var emitter = this.particleSystem.emitter;
  61340. if (!emitter) {
  61341. emitter = new BABYLON.Vector3();
  61342. }
  61343. else if (emitter instanceof BABYLON.Vector3) {
  61344. emitter = emitter.clone();
  61345. }
  61346. else if (emitter instanceof BABYLON.AbstractMesh) {
  61347. emitter = new BABYLON.Mesh("", emitter.getScene());
  61348. emitter.isVisible = false;
  61349. }
  61350. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  61351. // Clone properties
  61352. clone.type = this.type;
  61353. clone.inheritDirection = this.inheritDirection;
  61354. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61355. clone.particleSystem._disposeEmitterOnDispose = true;
  61356. clone.particleSystem.disposeOnStop = true;
  61357. return clone;
  61358. };
  61359. /**
  61360. * Serialize current object to a JSON object
  61361. * @returns the serialized object
  61362. */
  61363. SubEmitter.prototype.serialize = function () {
  61364. var serializationObject = {};
  61365. serializationObject.type = this.type;
  61366. serializationObject.inheritDirection = this.inheritDirection;
  61367. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61368. serializationObject.particleSystem = this.particleSystem.serialize();
  61369. return serializationObject;
  61370. };
  61371. /**
  61372. * Creates a new SubEmitter from a serialized JSON version
  61373. * @param serializationObject defines the JSON object to read from
  61374. * @param scene defines the hosting scene
  61375. * @param rootUrl defines the rootUrl for data loading
  61376. * @returns a new SubEmitter
  61377. */
  61378. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  61379. var system = serializationObject.particleSystem;
  61380. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  61381. subEmitter.type = serializationObject.type;
  61382. subEmitter.inheritDirection = serializationObject.inheritDirection;
  61383. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  61384. subEmitter.particleSystem._isSubEmitter = true;
  61385. return subEmitter;
  61386. };
  61387. /** Release associated resources */
  61388. SubEmitter.prototype.dispose = function () {
  61389. this.particleSystem.dispose();
  61390. };
  61391. return SubEmitter;
  61392. }());
  61393. BABYLON.SubEmitter = SubEmitter;
  61394. })(BABYLON || (BABYLON = {}));
  61395. //# sourceMappingURL=babylon.subEmitter.js.map
  61396. var BABYLON;
  61397. (function (BABYLON) {
  61398. /**
  61399. * 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.
  61400. *
  61401. * This returned material effects how the mesh will look based on the code in the shaders.
  61402. *
  61403. * @see http://doc.babylonjs.com/how_to/shader_material
  61404. */
  61405. var ShaderMaterial = /** @class */ (function (_super) {
  61406. __extends(ShaderMaterial, _super);
  61407. /**
  61408. * Instantiate a new shader material.
  61409. * 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.
  61410. * This returned material effects how the mesh will look based on the code in the shaders.
  61411. * @see http://doc.babylonjs.com/how_to/shader_material
  61412. * @param name Define the name of the material in the scene
  61413. * @param scene Define the scene the material belongs to
  61414. * @param shaderPath Defines the route to the shader code in one of three ways:
  61415. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  61416. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  61417. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  61418. * @param options Define the options used to create the shader
  61419. */
  61420. function ShaderMaterial(name, scene, shaderPath, options) {
  61421. if (options === void 0) { options = {}; }
  61422. var _this = _super.call(this, name, scene) || this;
  61423. _this._textures = {};
  61424. _this._textureArrays = {};
  61425. _this._floats = {};
  61426. _this._ints = {};
  61427. _this._floatsArrays = {};
  61428. _this._colors3 = {};
  61429. _this._colors3Arrays = {};
  61430. _this._colors4 = {};
  61431. _this._vectors2 = {};
  61432. _this._vectors3 = {};
  61433. _this._vectors4 = {};
  61434. _this._matrices = {};
  61435. _this._matrices3x3 = {};
  61436. _this._matrices2x2 = {};
  61437. _this._vectors2Arrays = {};
  61438. _this._vectors3Arrays = {};
  61439. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  61440. _this._shaderPath = shaderPath;
  61441. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  61442. return _this;
  61443. }
  61444. /**
  61445. * Gets the current class name of the material e.g. "ShaderMaterial"
  61446. * Mainly use in serialization.
  61447. * @returns the class name
  61448. */
  61449. ShaderMaterial.prototype.getClassName = function () {
  61450. return "ShaderMaterial";
  61451. };
  61452. /**
  61453. * Specifies if the material will require alpha blending
  61454. * @returns a boolean specifying if alpha blending is needed
  61455. */
  61456. ShaderMaterial.prototype.needAlphaBlending = function () {
  61457. return (this.alpha < 1.0);
  61458. };
  61459. /**
  61460. * Specifies if this material should be rendered in alpha test mode
  61461. * @returns a boolean specifying if an alpha test is needed.
  61462. */
  61463. ShaderMaterial.prototype.needAlphaTesting = function () {
  61464. return this._options.needAlphaTesting;
  61465. };
  61466. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  61467. if (this._options.uniforms.indexOf(uniformName) === -1) {
  61468. this._options.uniforms.push(uniformName);
  61469. }
  61470. };
  61471. /**
  61472. * Set a texture in the shader.
  61473. * @param name Define the name of the uniform samplers as defined in the shader
  61474. * @param texture Define the texture to bind to this sampler
  61475. * @return the material itself allowing "fluent" like uniform updates
  61476. */
  61477. ShaderMaterial.prototype.setTexture = function (name, texture) {
  61478. if (this._options.samplers.indexOf(name) === -1) {
  61479. this._options.samplers.push(name);
  61480. }
  61481. this._textures[name] = texture;
  61482. return this;
  61483. };
  61484. /**
  61485. * Set a texture array in the shader.
  61486. * @param name Define the name of the uniform sampler array as defined in the shader
  61487. * @param textures Define the list of textures to bind to this sampler
  61488. * @return the material itself allowing "fluent" like uniform updates
  61489. */
  61490. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  61491. if (this._options.samplers.indexOf(name) === -1) {
  61492. this._options.samplers.push(name);
  61493. }
  61494. this._checkUniform(name);
  61495. this._textureArrays[name] = textures;
  61496. return this;
  61497. };
  61498. /**
  61499. * Set a float in the shader.
  61500. * @param name Define the name of the uniform as defined in the shader
  61501. * @param value Define the value to give to the uniform
  61502. * @return the material itself allowing "fluent" like uniform updates
  61503. */
  61504. ShaderMaterial.prototype.setFloat = function (name, value) {
  61505. this._checkUniform(name);
  61506. this._floats[name] = value;
  61507. return this;
  61508. };
  61509. /**
  61510. * Set a int in the shader.
  61511. * @param name Define the name of the uniform as defined in the shader
  61512. * @param value Define the value to give to the uniform
  61513. * @return the material itself allowing "fluent" like uniform updates
  61514. */
  61515. ShaderMaterial.prototype.setInt = function (name, value) {
  61516. this._checkUniform(name);
  61517. this._ints[name] = value;
  61518. return this;
  61519. };
  61520. /**
  61521. * Set an array of floats in the shader.
  61522. * @param name Define the name of the uniform as defined in the shader
  61523. * @param value Define the value to give to the uniform
  61524. * @return the material itself allowing "fluent" like uniform updates
  61525. */
  61526. ShaderMaterial.prototype.setFloats = function (name, value) {
  61527. this._checkUniform(name);
  61528. this._floatsArrays[name] = value;
  61529. return this;
  61530. };
  61531. /**
  61532. * Set a vec3 in the shader from a Color3.
  61533. * @param name Define the name of the uniform as defined in the shader
  61534. * @param value Define the value to give to the uniform
  61535. * @return the material itself allowing "fluent" like uniform updates
  61536. */
  61537. ShaderMaterial.prototype.setColor3 = function (name, value) {
  61538. this._checkUniform(name);
  61539. this._colors3[name] = value;
  61540. return this;
  61541. };
  61542. /**
  61543. * Set a vec3 array in the shader from a Color3 array.
  61544. * @param name Define the name of the uniform as defined in the shader
  61545. * @param value Define the value to give to the uniform
  61546. * @return the material itself allowing "fluent" like uniform updates
  61547. */
  61548. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  61549. this._checkUniform(name);
  61550. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  61551. color.toArray(arr, arr.length);
  61552. return arr;
  61553. }, []);
  61554. return this;
  61555. };
  61556. /**
  61557. * Set a vec4 in the shader from a Color4.
  61558. * @param name Define the name of the uniform as defined in the shader
  61559. * @param value Define the value to give to the uniform
  61560. * @return the material itself allowing "fluent" like uniform updates
  61561. */
  61562. ShaderMaterial.prototype.setColor4 = function (name, value) {
  61563. this._checkUniform(name);
  61564. this._colors4[name] = value;
  61565. return this;
  61566. };
  61567. /**
  61568. * Set a vec2 in the shader from a Vector2.
  61569. * @param name Define the name of the uniform as defined in the shader
  61570. * @param value Define the value to give to the uniform
  61571. * @return the material itself allowing "fluent" like uniform updates
  61572. */
  61573. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61574. this._checkUniform(name);
  61575. this._vectors2[name] = value;
  61576. return this;
  61577. };
  61578. /**
  61579. * Set a vec3 in the shader from a Vector3.
  61580. * @param name Define the name of the uniform as defined in the shader
  61581. * @param value Define the value to give to the uniform
  61582. * @return the material itself allowing "fluent" like uniform updates
  61583. */
  61584. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61585. this._checkUniform(name);
  61586. this._vectors3[name] = value;
  61587. return this;
  61588. };
  61589. /**
  61590. * Set a vec4 in the shader from a Vector4.
  61591. * @param name Define the name of the uniform as defined in the shader
  61592. * @param value Define the value to give to the uniform
  61593. * @return the material itself allowing "fluent" like uniform updates
  61594. */
  61595. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61596. this._checkUniform(name);
  61597. this._vectors4[name] = value;
  61598. return this;
  61599. };
  61600. /**
  61601. * Set a mat4 in the shader from a Matrix.
  61602. * @param name Define the name of the uniform as defined in the shader
  61603. * @param value Define the value to give to the uniform
  61604. * @return the material itself allowing "fluent" like uniform updates
  61605. */
  61606. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61607. this._checkUniform(name);
  61608. this._matrices[name] = value;
  61609. return this;
  61610. };
  61611. /**
  61612. * Set a mat3 in the shader from a Float32Array.
  61613. * @param name Define the name of the uniform as defined in the shader
  61614. * @param value Define the value to give to the uniform
  61615. * @return the material itself allowing "fluent" like uniform updates
  61616. */
  61617. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61618. this._checkUniform(name);
  61619. this._matrices3x3[name] = value;
  61620. return this;
  61621. };
  61622. /**
  61623. * Set a mat2 in the shader from a Float32Array.
  61624. * @param name Define the name of the uniform as defined in the shader
  61625. * @param value Define the value to give to the uniform
  61626. * @return the material itself allowing "fluent" like uniform updates
  61627. */
  61628. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61629. this._checkUniform(name);
  61630. this._matrices2x2[name] = value;
  61631. return this;
  61632. };
  61633. /**
  61634. * Set a vec2 array in the shader from a number array.
  61635. * @param name Define the name of the uniform as defined in the shader
  61636. * @param value Define the value to give to the uniform
  61637. * @return the material itself allowing "fluent" like uniform updates
  61638. */
  61639. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61640. this._checkUniform(name);
  61641. this._vectors2Arrays[name] = value;
  61642. return this;
  61643. };
  61644. /**
  61645. * Set a vec3 array in the shader from a number array.
  61646. * @param name Define the name of the uniform as defined in the shader
  61647. * @param value Define the value to give to the uniform
  61648. * @return the material itself allowing "fluent" like uniform updates
  61649. */
  61650. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61651. this._checkUniform(name);
  61652. this._vectors3Arrays[name] = value;
  61653. return this;
  61654. };
  61655. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61656. if (!mesh) {
  61657. return true;
  61658. }
  61659. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61660. return false;
  61661. }
  61662. return false;
  61663. };
  61664. /**
  61665. * Checks if the material is ready to render the requested mesh
  61666. * @param mesh Define the mesh to render
  61667. * @param useInstances Define whether or not the material is used with instances
  61668. * @returns true if ready, otherwise false
  61669. */
  61670. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61671. var scene = this.getScene();
  61672. var engine = scene.getEngine();
  61673. if (!this.checkReadyOnEveryCall) {
  61674. if (this._renderId === scene.getRenderId()) {
  61675. if (this._checkCache(scene, mesh, useInstances)) {
  61676. return true;
  61677. }
  61678. }
  61679. }
  61680. // Instances
  61681. var defines = [];
  61682. var attribs = [];
  61683. var fallbacks = new BABYLON.EffectFallbacks();
  61684. for (var index = 0; index < this._options.defines.length; index++) {
  61685. defines.push(this._options.defines[index]);
  61686. }
  61687. for (var index = 0; index < this._options.attributes.length; index++) {
  61688. attribs.push(this._options.attributes[index]);
  61689. }
  61690. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61691. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61692. defines.push("#define VERTEXCOLOR");
  61693. }
  61694. if (useInstances) {
  61695. defines.push("#define INSTANCES");
  61696. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61697. }
  61698. // Bones
  61699. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61700. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61701. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61702. if (mesh.numBoneInfluencers > 4) {
  61703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61705. }
  61706. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61707. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61708. fallbacks.addCPUSkinningFallback(0, mesh);
  61709. if (this._options.uniforms.indexOf("mBones") === -1) {
  61710. this._options.uniforms.push("mBones");
  61711. }
  61712. }
  61713. else {
  61714. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61715. }
  61716. // Textures
  61717. for (var name in this._textures) {
  61718. if (!this._textures[name].isReady()) {
  61719. return false;
  61720. }
  61721. }
  61722. // Alpha test
  61723. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  61724. defines.push("#define ALPHATEST");
  61725. }
  61726. var previousEffect = this._effect;
  61727. var join = defines.join("\n");
  61728. this._effect = engine.createEffect(this._shaderPath, {
  61729. attributes: attribs,
  61730. uniformsNames: this._options.uniforms,
  61731. uniformBuffersNames: this._options.uniformBuffers,
  61732. samplers: this._options.samplers,
  61733. defines: join,
  61734. fallbacks: fallbacks,
  61735. onCompiled: this.onCompiled,
  61736. onError: this.onError
  61737. }, engine);
  61738. if (!this._effect.isReady()) {
  61739. return false;
  61740. }
  61741. if (previousEffect !== this._effect) {
  61742. scene.resetCachedMaterial();
  61743. }
  61744. this._renderId = scene.getRenderId();
  61745. return true;
  61746. };
  61747. /**
  61748. * Binds the world matrix to the material
  61749. * @param world defines the world transformation matrix
  61750. */
  61751. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61752. var scene = this.getScene();
  61753. if (!this._effect) {
  61754. return;
  61755. }
  61756. if (this._options.uniforms.indexOf("world") !== -1) {
  61757. this._effect.setMatrix("world", world);
  61758. }
  61759. if (this._options.uniforms.indexOf("worldView") !== -1) {
  61760. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  61761. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  61762. }
  61763. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  61764. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  61765. }
  61766. };
  61767. /**
  61768. * Binds the material to the mesh
  61769. * @param world defines the world transformation matrix
  61770. * @param mesh defines the mesh to bind the material to
  61771. */
  61772. ShaderMaterial.prototype.bind = function (world, mesh) {
  61773. // Std values
  61774. this.bindOnlyWorldMatrix(world);
  61775. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  61776. if (this._options.uniforms.indexOf("view") !== -1) {
  61777. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  61778. }
  61779. if (this._options.uniforms.indexOf("projection") !== -1) {
  61780. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  61781. }
  61782. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  61783. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  61784. }
  61785. // Bones
  61786. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61787. var name;
  61788. // Texture
  61789. for (name in this._textures) {
  61790. this._effect.setTexture(name, this._textures[name]);
  61791. }
  61792. // Texture arrays
  61793. for (name in this._textureArrays) {
  61794. this._effect.setTextureArray(name, this._textureArrays[name]);
  61795. }
  61796. // Int
  61797. for (name in this._ints) {
  61798. this._effect.setInt(name, this._ints[name]);
  61799. }
  61800. // Float
  61801. for (name in this._floats) {
  61802. this._effect.setFloat(name, this._floats[name]);
  61803. }
  61804. // Floats
  61805. for (name in this._floatsArrays) {
  61806. this._effect.setArray(name, this._floatsArrays[name]);
  61807. }
  61808. // Color3
  61809. for (name in this._colors3) {
  61810. this._effect.setColor3(name, this._colors3[name]);
  61811. }
  61812. for (name in this._colors3Arrays) {
  61813. this._effect.setArray3(name, this._colors3Arrays[name]);
  61814. }
  61815. // Color4
  61816. for (name in this._colors4) {
  61817. var color = this._colors4[name];
  61818. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  61819. }
  61820. // Vector2
  61821. for (name in this._vectors2) {
  61822. this._effect.setVector2(name, this._vectors2[name]);
  61823. }
  61824. // Vector3
  61825. for (name in this._vectors3) {
  61826. this._effect.setVector3(name, this._vectors3[name]);
  61827. }
  61828. // Vector4
  61829. for (name in this._vectors4) {
  61830. this._effect.setVector4(name, this._vectors4[name]);
  61831. }
  61832. // Matrix
  61833. for (name in this._matrices) {
  61834. this._effect.setMatrix(name, this._matrices[name]);
  61835. }
  61836. // Matrix 3x3
  61837. for (name in this._matrices3x3) {
  61838. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  61839. }
  61840. // Matrix 2x2
  61841. for (name in this._matrices2x2) {
  61842. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  61843. }
  61844. // Vector2Array
  61845. for (name in this._vectors2Arrays) {
  61846. this._effect.setArray2(name, this._vectors2Arrays[name]);
  61847. }
  61848. // Vector3Array
  61849. for (name in this._vectors3Arrays) {
  61850. this._effect.setArray3(name, this._vectors3Arrays[name]);
  61851. }
  61852. }
  61853. this._afterBind(mesh);
  61854. };
  61855. /**
  61856. * Gets the active textures from the material
  61857. * @returns an array of textures
  61858. */
  61859. ShaderMaterial.prototype.getActiveTextures = function () {
  61860. var activeTextures = _super.prototype.getActiveTextures.call(this);
  61861. for (var name in this._textures) {
  61862. activeTextures.push(this._textures[name]);
  61863. }
  61864. for (var name in this._textureArrays) {
  61865. var array = this._textureArrays[name];
  61866. for (var index = 0; index < array.length; index++) {
  61867. activeTextures.push(array[index]);
  61868. }
  61869. }
  61870. return activeTextures;
  61871. };
  61872. /**
  61873. * Specifies if the material uses a texture
  61874. * @param texture defines the texture to check against the material
  61875. * @returns a boolean specifying if the material uses the texture
  61876. */
  61877. ShaderMaterial.prototype.hasTexture = function (texture) {
  61878. if (_super.prototype.hasTexture.call(this, texture)) {
  61879. return true;
  61880. }
  61881. for (var name in this._textures) {
  61882. if (this._textures[name] === texture) {
  61883. return true;
  61884. }
  61885. }
  61886. for (var name in this._textureArrays) {
  61887. var array = this._textureArrays[name];
  61888. for (var index = 0; index < array.length; index++) {
  61889. if (array[index] === texture) {
  61890. return true;
  61891. }
  61892. }
  61893. }
  61894. return false;
  61895. };
  61896. /**
  61897. * Makes a duplicate of the material, and gives it a new name
  61898. * @param name defines the new name for the duplicated material
  61899. * @returns the cloned material
  61900. */
  61901. ShaderMaterial.prototype.clone = function (name) {
  61902. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  61903. return newShaderMaterial;
  61904. };
  61905. /**
  61906. * Disposes the material
  61907. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  61908. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  61909. */
  61910. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61911. if (forceDisposeTextures) {
  61912. var name;
  61913. for (name in this._textures) {
  61914. this._textures[name].dispose();
  61915. }
  61916. for (name in this._textureArrays) {
  61917. var array = this._textureArrays[name];
  61918. for (var index = 0; index < array.length; index++) {
  61919. array[index].dispose();
  61920. }
  61921. }
  61922. }
  61923. this._textures = {};
  61924. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61925. };
  61926. /**
  61927. * Serializes this material in a JSON representation
  61928. * @returns the serialized material object
  61929. */
  61930. ShaderMaterial.prototype.serialize = function () {
  61931. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61932. serializationObject.customType = "BABYLON.ShaderMaterial";
  61933. serializationObject.options = this._options;
  61934. serializationObject.shaderPath = this._shaderPath;
  61935. var name;
  61936. // Texture
  61937. serializationObject.textures = {};
  61938. for (name in this._textures) {
  61939. serializationObject.textures[name] = this._textures[name].serialize();
  61940. }
  61941. // Texture arrays
  61942. serializationObject.textureArrays = {};
  61943. for (name in this._textureArrays) {
  61944. serializationObject.textureArrays[name] = [];
  61945. var array = this._textureArrays[name];
  61946. for (var index = 0; index < array.length; index++) {
  61947. serializationObject.textureArrays[name].push(array[index].serialize());
  61948. }
  61949. }
  61950. // Float
  61951. serializationObject.floats = {};
  61952. for (name in this._floats) {
  61953. serializationObject.floats[name] = this._floats[name];
  61954. }
  61955. // Float s
  61956. serializationObject.FloatArrays = {};
  61957. for (name in this._floatsArrays) {
  61958. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61959. }
  61960. // Color3
  61961. serializationObject.colors3 = {};
  61962. for (name in this._colors3) {
  61963. serializationObject.colors3[name] = this._colors3[name].asArray();
  61964. }
  61965. // Color3 array
  61966. serializationObject.colors3Arrays = {};
  61967. for (name in this._colors3Arrays) {
  61968. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61969. }
  61970. // Color4
  61971. serializationObject.colors4 = {};
  61972. for (name in this._colors4) {
  61973. serializationObject.colors4[name] = this._colors4[name].asArray();
  61974. }
  61975. // Vector2
  61976. serializationObject.vectors2 = {};
  61977. for (name in this._vectors2) {
  61978. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  61979. }
  61980. // Vector3
  61981. serializationObject.vectors3 = {};
  61982. for (name in this._vectors3) {
  61983. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  61984. }
  61985. // Vector4
  61986. serializationObject.vectors4 = {};
  61987. for (name in this._vectors4) {
  61988. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  61989. }
  61990. // Matrix
  61991. serializationObject.matrices = {};
  61992. for (name in this._matrices) {
  61993. serializationObject.matrices[name] = this._matrices[name].asArray();
  61994. }
  61995. // Matrix 3x3
  61996. serializationObject.matrices3x3 = {};
  61997. for (name in this._matrices3x3) {
  61998. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  61999. }
  62000. // Matrix 2x2
  62001. serializationObject.matrices2x2 = {};
  62002. for (name in this._matrices2x2) {
  62003. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62004. }
  62005. // Vector2Array
  62006. serializationObject.vectors2Arrays = {};
  62007. for (name in this._vectors2Arrays) {
  62008. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62009. }
  62010. // Vector3Array
  62011. serializationObject.vectors3Arrays = {};
  62012. for (name in this._vectors3Arrays) {
  62013. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62014. }
  62015. return serializationObject;
  62016. };
  62017. /**
  62018. * Creates a shader material from parsed shader material data
  62019. * @param source defines the JSON represnetation of the material
  62020. * @param scene defines the hosting scene
  62021. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62022. * @returns a new material
  62023. */
  62024. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62025. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62026. var name;
  62027. // Texture
  62028. for (name in source.textures) {
  62029. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62030. }
  62031. // Texture arrays
  62032. for (name in source.textureArrays) {
  62033. var array = source.textureArrays[name];
  62034. var textureArray = new Array();
  62035. for (var index = 0; index < array.length; index++) {
  62036. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62037. }
  62038. material.setTextureArray(name, textureArray);
  62039. }
  62040. // Float
  62041. for (name in source.floats) {
  62042. material.setFloat(name, source.floats[name]);
  62043. }
  62044. // Float s
  62045. for (name in source.floatsArrays) {
  62046. material.setFloats(name, source.floatsArrays[name]);
  62047. }
  62048. // Color3
  62049. for (name in source.colors3) {
  62050. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62051. }
  62052. // Color3 arrays
  62053. for (name in source.colors3Arrays) {
  62054. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62055. if (i % 3 === 0) {
  62056. arr.push([num]);
  62057. }
  62058. else {
  62059. arr[arr.length - 1].push(num);
  62060. }
  62061. return arr;
  62062. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62063. material.setColor3Array(name, colors);
  62064. }
  62065. // Color4
  62066. for (name in source.colors4) {
  62067. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62068. }
  62069. // Vector2
  62070. for (name in source.vectors2) {
  62071. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62072. }
  62073. // Vector3
  62074. for (name in source.vectors3) {
  62075. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62076. }
  62077. // Vector4
  62078. for (name in source.vectors4) {
  62079. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62080. }
  62081. // Matrix
  62082. for (name in source.matrices) {
  62083. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62084. }
  62085. // Matrix 3x3
  62086. for (name in source.matrices3x3) {
  62087. material.setMatrix3x3(name, source.matrices3x3[name]);
  62088. }
  62089. // Matrix 2x2
  62090. for (name in source.matrices2x2) {
  62091. material.setMatrix2x2(name, source.matrices2x2[name]);
  62092. }
  62093. // Vector2Array
  62094. for (name in source.vectors2Arrays) {
  62095. material.setArray2(name, source.vectors2Arrays[name]);
  62096. }
  62097. // Vector3Array
  62098. for (name in source.vectors3Arrays) {
  62099. material.setArray3(name, source.vectors3Arrays[name]);
  62100. }
  62101. return material;
  62102. };
  62103. return ShaderMaterial;
  62104. }(BABYLON.Material));
  62105. BABYLON.ShaderMaterial = ShaderMaterial;
  62106. })(BABYLON || (BABYLON = {}));
  62107. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62108. var BABYLON;
  62109. (function (BABYLON) {
  62110. var GroundMesh = /** @class */ (function (_super) {
  62111. __extends(GroundMesh, _super);
  62112. function GroundMesh(name, scene) {
  62113. var _this = _super.call(this, name, scene) || this;
  62114. _this.generateOctree = false;
  62115. return _this;
  62116. }
  62117. GroundMesh.prototype.getClassName = function () {
  62118. return "GroundMesh";
  62119. };
  62120. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  62121. get: function () {
  62122. return Math.min(this._subdivisionsX, this._subdivisionsY);
  62123. },
  62124. enumerable: true,
  62125. configurable: true
  62126. });
  62127. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  62128. get: function () {
  62129. return this._subdivisionsX;
  62130. },
  62131. enumerable: true,
  62132. configurable: true
  62133. });
  62134. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  62135. get: function () {
  62136. return this._subdivisionsY;
  62137. },
  62138. enumerable: true,
  62139. configurable: true
  62140. });
  62141. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  62142. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  62143. this._subdivisionsX = chunksCount;
  62144. this._subdivisionsY = chunksCount;
  62145. this.subdivide(chunksCount);
  62146. // Call the octree system optimization if it is defined.
  62147. var thisAsAny = this;
  62148. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  62149. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  62150. }
  62151. };
  62152. /**
  62153. * Returns a height (y) value in the Worl system :
  62154. * the ground altitude at the coordinates (x, z) expressed in the World system.
  62155. * Returns the ground y position if (x, z) are outside the ground surface.
  62156. */
  62157. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  62158. var world = this.getWorldMatrix();
  62159. var invMat = BABYLON.Tmp.Matrix[5];
  62160. world.invertToRef(invMat);
  62161. var tmpVect = BABYLON.Tmp.Vector3[8];
  62162. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  62163. x = tmpVect.x;
  62164. z = tmpVect.z;
  62165. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62166. return this.position.y;
  62167. }
  62168. if (!this._heightQuads || this._heightQuads.length == 0) {
  62169. this._initHeightQuads();
  62170. this._computeHeightQuads();
  62171. }
  62172. var facet = this._getFacetAt(x, z);
  62173. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  62174. // return y in the World system
  62175. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  62176. return tmpVect.y;
  62177. };
  62178. /**
  62179. * Returns a normalized vector (Vector3) orthogonal to the ground
  62180. * at the ground coordinates (x, z) expressed in the World system.
  62181. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  62182. */
  62183. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  62184. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  62185. this.getNormalAtCoordinatesToRef(x, z, normal);
  62186. return normal;
  62187. };
  62188. /**
  62189. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  62190. * at the ground coordinates (x, z) expressed in the World system.
  62191. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  62192. * Returns the GroundMesh.
  62193. */
  62194. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  62195. var world = this.getWorldMatrix();
  62196. var tmpMat = BABYLON.Tmp.Matrix[5];
  62197. world.invertToRef(tmpMat);
  62198. var tmpVect = BABYLON.Tmp.Vector3[8];
  62199. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  62200. x = tmpVect.x;
  62201. z = tmpVect.z;
  62202. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62203. return this;
  62204. }
  62205. if (!this._heightQuads || this._heightQuads.length == 0) {
  62206. this._initHeightQuads();
  62207. this._computeHeightQuads();
  62208. }
  62209. var facet = this._getFacetAt(x, z);
  62210. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  62211. return this;
  62212. };
  62213. /**
  62214. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  62215. * if the ground has been updated.
  62216. * This can be used in the render loop.
  62217. * Returns the GroundMesh.
  62218. */
  62219. GroundMesh.prototype.updateCoordinateHeights = function () {
  62220. if (!this._heightQuads || this._heightQuads.length == 0) {
  62221. this._initHeightQuads();
  62222. }
  62223. this._computeHeightQuads();
  62224. return this;
  62225. };
  62226. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  62227. GroundMesh.prototype._getFacetAt = function (x, z) {
  62228. // retrieve col and row from x, z coordinates in the ground local system
  62229. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  62230. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  62231. var quad = this._heightQuads[row * this._subdivisionsX + col];
  62232. var facet;
  62233. if (z < quad.slope.x * x + quad.slope.y) {
  62234. facet = quad.facet1;
  62235. }
  62236. else {
  62237. facet = quad.facet2;
  62238. }
  62239. return facet;
  62240. };
  62241. // Creates and populates the heightMap array with "facet" elements :
  62242. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  62243. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62244. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62245. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62246. // Returns the GroundMesh.
  62247. GroundMesh.prototype._initHeightQuads = function () {
  62248. var subdivisionsX = this._subdivisionsX;
  62249. var subdivisionsY = this._subdivisionsY;
  62250. this._heightQuads = new Array();
  62251. for (var row = 0; row < subdivisionsY; row++) {
  62252. for (var col = 0; col < subdivisionsX; col++) {
  62253. 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) };
  62254. this._heightQuads[row * subdivisionsX + col] = quad;
  62255. }
  62256. }
  62257. return this;
  62258. };
  62259. // Compute each quad element values and update the the heightMap array :
  62260. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62261. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62262. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62263. // Returns the GroundMesh.
  62264. GroundMesh.prototype._computeHeightQuads = function () {
  62265. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62266. if (!positions) {
  62267. return this;
  62268. }
  62269. var v1 = BABYLON.Tmp.Vector3[3];
  62270. var v2 = BABYLON.Tmp.Vector3[2];
  62271. var v3 = BABYLON.Tmp.Vector3[1];
  62272. var v4 = BABYLON.Tmp.Vector3[0];
  62273. var v1v2 = BABYLON.Tmp.Vector3[4];
  62274. var v1v3 = BABYLON.Tmp.Vector3[5];
  62275. var v1v4 = BABYLON.Tmp.Vector3[6];
  62276. var norm1 = BABYLON.Tmp.Vector3[7];
  62277. var norm2 = BABYLON.Tmp.Vector3[8];
  62278. var i = 0;
  62279. var j = 0;
  62280. var k = 0;
  62281. var cd = 0; // 2D slope coefficient : z = cd * x + h
  62282. var h = 0;
  62283. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  62284. var d2 = 0;
  62285. var subdivisionsX = this._subdivisionsX;
  62286. var subdivisionsY = this._subdivisionsY;
  62287. for (var row = 0; row < subdivisionsY; row++) {
  62288. for (var col = 0; col < subdivisionsX; col++) {
  62289. i = col * 3;
  62290. j = row * (subdivisionsX + 1) * 3;
  62291. k = (row + 1) * (subdivisionsX + 1) * 3;
  62292. v1.x = positions[j + i];
  62293. v1.y = positions[j + i + 1];
  62294. v1.z = positions[j + i + 2];
  62295. v2.x = positions[j + i + 3];
  62296. v2.y = positions[j + i + 4];
  62297. v2.z = positions[j + i + 5];
  62298. v3.x = positions[k + i];
  62299. v3.y = positions[k + i + 1];
  62300. v3.z = positions[k + i + 2];
  62301. v4.x = positions[k + i + 3];
  62302. v4.y = positions[k + i + 4];
  62303. v4.z = positions[k + i + 5];
  62304. // 2D slope V1V4
  62305. cd = (v4.z - v1.z) / (v4.x - v1.x);
  62306. h = v1.z - cd * v1.x; // v1 belongs to the slope
  62307. // facet equations :
  62308. // we compute each facet normal vector
  62309. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  62310. // we compute the value d by applying the equation to v1 which belongs to the plane
  62311. // then we store the facet equation in a Vector4
  62312. v2.subtractToRef(v1, v1v2);
  62313. v3.subtractToRef(v1, v1v3);
  62314. v4.subtractToRef(v1, v1v4);
  62315. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  62316. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  62317. norm1.normalize();
  62318. norm2.normalize();
  62319. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  62320. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  62321. var quad = this._heightQuads[row * subdivisionsX + col];
  62322. quad.slope.copyFromFloats(cd, h);
  62323. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  62324. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  62325. }
  62326. }
  62327. return this;
  62328. };
  62329. GroundMesh.prototype.serialize = function (serializationObject) {
  62330. _super.prototype.serialize.call(this, serializationObject);
  62331. serializationObject.subdivisionsX = this._subdivisionsX;
  62332. serializationObject.subdivisionsY = this._subdivisionsY;
  62333. serializationObject.minX = this._minX;
  62334. serializationObject.maxX = this._maxX;
  62335. serializationObject.minZ = this._minZ;
  62336. serializationObject.maxZ = this._maxZ;
  62337. serializationObject.width = this._width;
  62338. serializationObject.height = this._height;
  62339. };
  62340. GroundMesh.Parse = function (parsedMesh, scene) {
  62341. var result = new GroundMesh(parsedMesh.name, scene);
  62342. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  62343. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  62344. result._minX = parsedMesh.minX;
  62345. result._maxX = parsedMesh.maxX;
  62346. result._minZ = parsedMesh.minZ;
  62347. result._maxZ = parsedMesh.maxZ;
  62348. result._width = parsedMesh.width;
  62349. result._height = parsedMesh.height;
  62350. return result;
  62351. };
  62352. return GroundMesh;
  62353. }(BABYLON.Mesh));
  62354. BABYLON.GroundMesh = GroundMesh;
  62355. })(BABYLON || (BABYLON = {}));
  62356. //# sourceMappingURL=babylon.groundMesh.js.map
  62357. var BABYLON;
  62358. (function (BABYLON) {
  62359. /**
  62360. * Creates an instance based on a source mesh.
  62361. */
  62362. var InstancedMesh = /** @class */ (function (_super) {
  62363. __extends(InstancedMesh, _super);
  62364. function InstancedMesh(name, source) {
  62365. var _this = _super.call(this, name, source.getScene()) || this;
  62366. source.instances.push(_this);
  62367. _this._sourceMesh = source;
  62368. _this.position.copyFrom(source.position);
  62369. _this.rotation.copyFrom(source.rotation);
  62370. _this.scaling.copyFrom(source.scaling);
  62371. if (source.rotationQuaternion) {
  62372. _this.rotationQuaternion = source.rotationQuaternion.clone();
  62373. }
  62374. _this.infiniteDistance = source.infiniteDistance;
  62375. _this.setPivotMatrix(source.getPivotMatrix());
  62376. _this.refreshBoundingInfo();
  62377. _this._syncSubMeshes();
  62378. return _this;
  62379. }
  62380. /**
  62381. * Returns the string "InstancedMesh".
  62382. */
  62383. InstancedMesh.prototype.getClassName = function () {
  62384. return "InstancedMesh";
  62385. };
  62386. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  62387. // Methods
  62388. get: function () {
  62389. return this._sourceMesh.receiveShadows;
  62390. },
  62391. enumerable: true,
  62392. configurable: true
  62393. });
  62394. Object.defineProperty(InstancedMesh.prototype, "material", {
  62395. get: function () {
  62396. return this._sourceMesh.material;
  62397. },
  62398. enumerable: true,
  62399. configurable: true
  62400. });
  62401. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  62402. get: function () {
  62403. return this._sourceMesh.visibility;
  62404. },
  62405. enumerable: true,
  62406. configurable: true
  62407. });
  62408. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  62409. get: function () {
  62410. return this._sourceMesh.skeleton;
  62411. },
  62412. enumerable: true,
  62413. configurable: true
  62414. });
  62415. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  62416. get: function () {
  62417. return this._sourceMesh.renderingGroupId;
  62418. },
  62419. set: function (value) {
  62420. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  62421. return;
  62422. }
  62423. //no-op with warning
  62424. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  62425. },
  62426. enumerable: true,
  62427. configurable: true
  62428. });
  62429. /**
  62430. * Returns the total number of vertices (integer).
  62431. */
  62432. InstancedMesh.prototype.getTotalVertices = function () {
  62433. return this._sourceMesh.getTotalVertices();
  62434. };
  62435. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  62436. get: function () {
  62437. return this._sourceMesh;
  62438. },
  62439. enumerable: true,
  62440. configurable: true
  62441. });
  62442. /**
  62443. * Is this node ready to be used/rendered
  62444. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  62445. * @return {boolean} is it ready
  62446. */
  62447. InstancedMesh.prototype.isReady = function (completeCheck) {
  62448. if (completeCheck === void 0) { completeCheck = false; }
  62449. return this._sourceMesh.isReady(completeCheck, true);
  62450. };
  62451. /**
  62452. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  62453. */
  62454. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  62455. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  62456. };
  62457. /**
  62458. * Sets the vertex data of the mesh geometry for the requested `kind`.
  62459. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  62460. * The `data` are either a numeric array either a Float32Array.
  62461. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  62462. * 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).
  62463. * Note that a new underlying VertexBuffer object is created each call.
  62464. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  62465. *
  62466. * Possible `kind` values :
  62467. * - BABYLON.VertexBuffer.PositionKind
  62468. * - BABYLON.VertexBuffer.UVKind
  62469. * - BABYLON.VertexBuffer.UV2Kind
  62470. * - BABYLON.VertexBuffer.UV3Kind
  62471. * - BABYLON.VertexBuffer.UV4Kind
  62472. * - BABYLON.VertexBuffer.UV5Kind
  62473. * - BABYLON.VertexBuffer.UV6Kind
  62474. * - BABYLON.VertexBuffer.ColorKind
  62475. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62476. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62477. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62478. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62479. *
  62480. * Returns the Mesh.
  62481. */
  62482. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  62483. if (this.sourceMesh) {
  62484. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  62485. }
  62486. return this.sourceMesh;
  62487. };
  62488. /**
  62489. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  62490. * If the mesh has no geometry, it is simply returned as it is.
  62491. * The `data` are either a numeric array either a Float32Array.
  62492. * No new underlying VertexBuffer object is created.
  62493. * 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.
  62494. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  62495. *
  62496. * Possible `kind` values :
  62497. * - BABYLON.VertexBuffer.PositionKind
  62498. * - BABYLON.VertexBuffer.UVKind
  62499. * - BABYLON.VertexBuffer.UV2Kind
  62500. * - BABYLON.VertexBuffer.UV3Kind
  62501. * - BABYLON.VertexBuffer.UV4Kind
  62502. * - BABYLON.VertexBuffer.UV5Kind
  62503. * - BABYLON.VertexBuffer.UV6Kind
  62504. * - BABYLON.VertexBuffer.ColorKind
  62505. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62506. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62507. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62508. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62509. *
  62510. * Returns the Mesh.
  62511. */
  62512. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  62513. if (this.sourceMesh) {
  62514. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  62515. }
  62516. return this.sourceMesh;
  62517. };
  62518. /**
  62519. * Sets the mesh indices.
  62520. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  62521. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  62522. * This method creates a new index buffer each call.
  62523. * Returns the Mesh.
  62524. */
  62525. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  62526. if (totalVertices === void 0) { totalVertices = null; }
  62527. if (this.sourceMesh) {
  62528. this.sourceMesh.setIndices(indices, totalVertices);
  62529. }
  62530. return this.sourceMesh;
  62531. };
  62532. /**
  62533. * Boolean : True if the mesh owns the requested kind of data.
  62534. */
  62535. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  62536. return this._sourceMesh.isVerticesDataPresent(kind);
  62537. };
  62538. /**
  62539. * Returns an array of indices (IndicesArray).
  62540. */
  62541. InstancedMesh.prototype.getIndices = function () {
  62542. return this._sourceMesh.getIndices();
  62543. };
  62544. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  62545. get: function () {
  62546. return this._sourceMesh._positions;
  62547. },
  62548. enumerable: true,
  62549. configurable: true
  62550. });
  62551. /**
  62552. * Sets a new updated BoundingInfo to the mesh.
  62553. * Returns the mesh.
  62554. */
  62555. InstancedMesh.prototype.refreshBoundingInfo = function () {
  62556. var meshBB = this._sourceMesh.getBoundingInfo();
  62557. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  62558. this._updateBoundingInfo();
  62559. return this;
  62560. };
  62561. /** @hidden */
  62562. InstancedMesh.prototype._preActivate = function () {
  62563. if (this._currentLOD) {
  62564. this._currentLOD._preActivate();
  62565. }
  62566. return this;
  62567. };
  62568. /** @hidden */
  62569. InstancedMesh.prototype._activate = function (renderId) {
  62570. if (this._currentLOD) {
  62571. this._currentLOD._registerInstanceForRenderId(this, renderId);
  62572. }
  62573. return this;
  62574. };
  62575. /**
  62576. * Returns the current associated LOD AbstractMesh.
  62577. */
  62578. InstancedMesh.prototype.getLOD = function (camera) {
  62579. if (!camera) {
  62580. return this;
  62581. }
  62582. var boundingInfo = this.getBoundingInfo();
  62583. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  62584. if (this._currentLOD === this.sourceMesh) {
  62585. return this;
  62586. }
  62587. return this._currentLOD;
  62588. };
  62589. /** @hidden */
  62590. InstancedMesh.prototype._syncSubMeshes = function () {
  62591. this.releaseSubMeshes();
  62592. if (this._sourceMesh.subMeshes) {
  62593. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  62594. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  62595. }
  62596. }
  62597. return this;
  62598. };
  62599. /** @hidden */
  62600. InstancedMesh.prototype._generatePointsArray = function () {
  62601. return this._sourceMesh._generatePointsArray();
  62602. };
  62603. /**
  62604. * Creates a new InstancedMesh from the current mesh.
  62605. * - name (string) : the cloned mesh name
  62606. * - newParent (optional Node) : the optional Node to parent the clone to.
  62607. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  62608. *
  62609. * Returns the clone.
  62610. */
  62611. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62612. var result = this._sourceMesh.createInstance(name);
  62613. // Deep copy
  62614. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  62615. // Bounding info
  62616. this.refreshBoundingInfo();
  62617. // Parent
  62618. if (newParent) {
  62619. result.parent = newParent;
  62620. }
  62621. if (!doNotCloneChildren) {
  62622. // Children
  62623. for (var index = 0; index < this.getScene().meshes.length; index++) {
  62624. var mesh = this.getScene().meshes[index];
  62625. if (mesh.parent === this) {
  62626. mesh.clone(mesh.name, result);
  62627. }
  62628. }
  62629. }
  62630. result.computeWorldMatrix(true);
  62631. return result;
  62632. };
  62633. /**
  62634. * Disposes the InstancedMesh.
  62635. * Returns nothing.
  62636. */
  62637. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  62638. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  62639. // Remove from mesh
  62640. var index = this._sourceMesh.instances.indexOf(this);
  62641. this._sourceMesh.instances.splice(index, 1);
  62642. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  62643. };
  62644. return InstancedMesh;
  62645. }(BABYLON.AbstractMesh));
  62646. BABYLON.InstancedMesh = InstancedMesh;
  62647. })(BABYLON || (BABYLON = {}));
  62648. //# sourceMappingURL=babylon.instancedMesh.js.map
  62649. var BABYLON;
  62650. (function (BABYLON) {
  62651. var LinesMesh = /** @class */ (function (_super) {
  62652. __extends(LinesMesh, _super);
  62653. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  62654. if (scene === void 0) { scene = null; }
  62655. if (parent === void 0) { parent = null; }
  62656. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  62657. _this.useVertexColor = useVertexColor;
  62658. _this.useVertexAlpha = useVertexAlpha;
  62659. _this.color = new BABYLON.Color3(1, 1, 1);
  62660. _this.alpha = 1;
  62661. if (source) {
  62662. _this.color = source.color.clone();
  62663. _this.alpha = source.alpha;
  62664. _this.useVertexColor = source.useVertexColor;
  62665. _this.useVertexAlpha = source.useVertexAlpha;
  62666. }
  62667. _this._intersectionThreshold = 0.1;
  62668. var defines = [];
  62669. var options = {
  62670. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62671. uniforms: ["world", "viewProjection"],
  62672. needAlphaBlending: true,
  62673. defines: defines
  62674. };
  62675. if (useVertexAlpha === false) {
  62676. options.needAlphaBlending = false;
  62677. }
  62678. if (!useVertexColor) {
  62679. options.uniforms.push("color");
  62680. }
  62681. else {
  62682. options.defines.push("#define VERTEXCOLOR");
  62683. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62684. }
  62685. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62686. return _this;
  62687. }
  62688. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62689. /**
  62690. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62691. * This margin is expressed in world space coordinates, so its value may vary.
  62692. * Default value is 0.1
  62693. * @returns the intersection Threshold value.
  62694. */
  62695. get: function () {
  62696. return this._intersectionThreshold;
  62697. },
  62698. /**
  62699. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62700. * This margin is expressed in world space coordinates, so its value may vary.
  62701. * @param value the new threshold to apply
  62702. */
  62703. set: function (value) {
  62704. if (this._intersectionThreshold === value) {
  62705. return;
  62706. }
  62707. this._intersectionThreshold = value;
  62708. if (this.geometry) {
  62709. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  62710. }
  62711. },
  62712. enumerable: true,
  62713. configurable: true
  62714. });
  62715. /**
  62716. * Returns the string "LineMesh"
  62717. */
  62718. LinesMesh.prototype.getClassName = function () {
  62719. return "LinesMesh";
  62720. };
  62721. Object.defineProperty(LinesMesh.prototype, "material", {
  62722. /**
  62723. * @hidden
  62724. */
  62725. get: function () {
  62726. return this._colorShader;
  62727. },
  62728. /**
  62729. * @hidden
  62730. */
  62731. set: function (value) {
  62732. // Do nothing
  62733. },
  62734. enumerable: true,
  62735. configurable: true
  62736. });
  62737. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  62738. /**
  62739. * @hidden
  62740. */
  62741. get: function () {
  62742. return false;
  62743. },
  62744. enumerable: true,
  62745. configurable: true
  62746. });
  62747. /** @hidden */
  62748. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  62749. if (!this._geometry) {
  62750. return this;
  62751. }
  62752. // VBOs
  62753. this._geometry._bind(this._colorShader.getEffect());
  62754. // Color
  62755. if (!this.useVertexColor) {
  62756. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  62757. }
  62758. return this;
  62759. };
  62760. /** @hidden */
  62761. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  62762. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  62763. return this;
  62764. }
  62765. var engine = this.getScene().getEngine();
  62766. // Draw order
  62767. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  62768. return this;
  62769. };
  62770. LinesMesh.prototype.dispose = function (doNotRecurse) {
  62771. this._colorShader.dispose();
  62772. _super.prototype.dispose.call(this, doNotRecurse);
  62773. };
  62774. /**
  62775. * Returns a new LineMesh object cloned from the current one.
  62776. */
  62777. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62778. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  62779. };
  62780. return LinesMesh;
  62781. }(BABYLON.Mesh));
  62782. BABYLON.LinesMesh = LinesMesh;
  62783. })(BABYLON || (BABYLON = {}));
  62784. //# sourceMappingURL=babylon.linesMesh.js.map
  62785. var BABYLON;
  62786. (function (BABYLON) {
  62787. /**
  62788. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62789. * The underlying implementation relies on an associative array to ensure the best performances.
  62790. * The value can be anything including 'null' but except 'undefined'
  62791. */
  62792. var StringDictionary = /** @class */ (function () {
  62793. function StringDictionary() {
  62794. this._count = 0;
  62795. this._data = {};
  62796. }
  62797. /**
  62798. * This will clear this dictionary and copy the content from the 'source' one.
  62799. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62800. * @param source the dictionary to take the content from and copy to this dictionary
  62801. */
  62802. StringDictionary.prototype.copyFrom = function (source) {
  62803. var _this = this;
  62804. this.clear();
  62805. source.forEach(function (t, v) { return _this.add(t, v); });
  62806. };
  62807. /**
  62808. * Get a value based from its key
  62809. * @param key the given key to get the matching value from
  62810. * @return the value if found, otherwise undefined is returned
  62811. */
  62812. StringDictionary.prototype.get = function (key) {
  62813. var val = this._data[key];
  62814. if (val !== undefined) {
  62815. return val;
  62816. }
  62817. return undefined;
  62818. };
  62819. /**
  62820. * Get a value from its key or add it if it doesn't exist.
  62821. * This method will ensure you that a given key/data will be present in the dictionary.
  62822. * @param key the given key to get the matching value from
  62823. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62824. * The factory will only be invoked if there's no data for the given key.
  62825. * @return the value corresponding to the key.
  62826. */
  62827. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62828. var val = this.get(key);
  62829. if (val !== undefined) {
  62830. return val;
  62831. }
  62832. val = factory(key);
  62833. if (val) {
  62834. this.add(key, val);
  62835. }
  62836. return val;
  62837. };
  62838. /**
  62839. * Get a value from its key if present in the dictionary otherwise add it
  62840. * @param key the key to get the value from
  62841. * @param val if there's no such key/value pair in the dictionary add it with this value
  62842. * @return the value corresponding to the key
  62843. */
  62844. StringDictionary.prototype.getOrAdd = function (key, val) {
  62845. var curVal = this.get(key);
  62846. if (curVal !== undefined) {
  62847. return curVal;
  62848. }
  62849. this.add(key, val);
  62850. return val;
  62851. };
  62852. /**
  62853. * Check if there's a given key in the dictionary
  62854. * @param key the key to check for
  62855. * @return true if the key is present, false otherwise
  62856. */
  62857. StringDictionary.prototype.contains = function (key) {
  62858. return this._data[key] !== undefined;
  62859. };
  62860. /**
  62861. * Add a new key and its corresponding value
  62862. * @param key the key to add
  62863. * @param value the value corresponding to the key
  62864. * @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
  62865. */
  62866. StringDictionary.prototype.add = function (key, value) {
  62867. if (this._data[key] !== undefined) {
  62868. return false;
  62869. }
  62870. this._data[key] = value;
  62871. ++this._count;
  62872. return true;
  62873. };
  62874. StringDictionary.prototype.set = function (key, value) {
  62875. if (this._data[key] === undefined) {
  62876. return false;
  62877. }
  62878. this._data[key] = value;
  62879. return true;
  62880. };
  62881. /**
  62882. * Get the element of the given key and remove it from the dictionary
  62883. * @param key
  62884. */
  62885. StringDictionary.prototype.getAndRemove = function (key) {
  62886. var val = this.get(key);
  62887. if (val !== undefined) {
  62888. delete this._data[key];
  62889. --this._count;
  62890. return val;
  62891. }
  62892. return null;
  62893. };
  62894. /**
  62895. * Remove a key/value from the dictionary.
  62896. * @param key the key to remove
  62897. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62898. */
  62899. StringDictionary.prototype.remove = function (key) {
  62900. if (this.contains(key)) {
  62901. delete this._data[key];
  62902. --this._count;
  62903. return true;
  62904. }
  62905. return false;
  62906. };
  62907. /**
  62908. * Clear the whole content of the dictionary
  62909. */
  62910. StringDictionary.prototype.clear = function () {
  62911. this._data = {};
  62912. this._count = 0;
  62913. };
  62914. Object.defineProperty(StringDictionary.prototype, "count", {
  62915. get: function () {
  62916. return this._count;
  62917. },
  62918. enumerable: true,
  62919. configurable: true
  62920. });
  62921. /**
  62922. * Execute a callback on each key/val of the dictionary.
  62923. * Note that you can remove any element in this dictionary in the callback implementation
  62924. * @param callback the callback to execute on a given key/value pair
  62925. */
  62926. StringDictionary.prototype.forEach = function (callback) {
  62927. for (var cur in this._data) {
  62928. var val = this._data[cur];
  62929. callback(cur, val);
  62930. }
  62931. };
  62932. /**
  62933. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62934. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62935. * Note that you can remove any element in this dictionary in the callback implementation
  62936. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62937. */
  62938. StringDictionary.prototype.first = function (callback) {
  62939. for (var cur in this._data) {
  62940. var val = this._data[cur];
  62941. var res = callback(cur, val);
  62942. if (res) {
  62943. return res;
  62944. }
  62945. }
  62946. return null;
  62947. };
  62948. return StringDictionary;
  62949. }());
  62950. BABYLON.StringDictionary = StringDictionary;
  62951. })(BABYLON || (BABYLON = {}));
  62952. //# sourceMappingURL=babylon.stringDictionary.js.map
  62953. var BABYLON;
  62954. (function (BABYLON) {
  62955. var Debug;
  62956. (function (Debug) {
  62957. /**
  62958. * Class used to render a debug view of a given skeleton
  62959. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62960. */
  62961. var SkeletonViewer = /** @class */ (function () {
  62962. /**
  62963. * Creates a new SkeletonViewer
  62964. * @param skeleton defines the skeleton to render
  62965. * @param mesh defines the mesh attached to the skeleton
  62966. * @param scene defines the hosting scene
  62967. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62968. * @param renderingGroupId defines the rendering group id to use with the viewer
  62969. */
  62970. function SkeletonViewer(
  62971. /** defines the skeleton to render */
  62972. skeleton,
  62973. /** defines the mesh attached to the skeleton */
  62974. mesh, scene,
  62975. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  62976. autoUpdateBonesMatrices,
  62977. /** defines the rendering group id to use with the viewer */
  62978. renderingGroupId) {
  62979. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62980. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62981. this.skeleton = skeleton;
  62982. this.mesh = mesh;
  62983. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62984. this.renderingGroupId = renderingGroupId;
  62985. /** Gets or sets the color used to render the skeleton */
  62986. this.color = BABYLON.Color3.White();
  62987. this._debugLines = new Array();
  62988. this._isEnabled = false;
  62989. this._scene = scene;
  62990. this.update();
  62991. this._renderFunction = this.update.bind(this);
  62992. }
  62993. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62994. get: function () {
  62995. return this._isEnabled;
  62996. },
  62997. /** Gets or sets a boolean indicating if the viewer is enabled */
  62998. set: function (value) {
  62999. if (this._isEnabled === value) {
  63000. return;
  63001. }
  63002. this._isEnabled = value;
  63003. if (value) {
  63004. this._scene.registerBeforeRender(this._renderFunction);
  63005. }
  63006. else {
  63007. this._scene.unregisterBeforeRender(this._renderFunction);
  63008. }
  63009. },
  63010. enumerable: true,
  63011. configurable: true
  63012. });
  63013. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63014. if (x === void 0) { x = 0; }
  63015. if (y === void 0) { y = 0; }
  63016. if (z === void 0) { z = 0; }
  63017. var tmat = BABYLON.Tmp.Matrix[0];
  63018. var parentBone = bone.getParent();
  63019. tmat.copyFrom(bone.getLocalMatrix());
  63020. if (x !== 0 || y !== 0 || z !== 0) {
  63021. var tmat2 = BABYLON.Tmp.Matrix[1];
  63022. BABYLON.Matrix.IdentityToRef(tmat2);
  63023. tmat2.m[12] = x;
  63024. tmat2.m[13] = y;
  63025. tmat2.m[14] = z;
  63026. tmat2.multiplyToRef(tmat, tmat);
  63027. }
  63028. if (parentBone) {
  63029. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63030. }
  63031. tmat.multiplyToRef(meshMat, tmat);
  63032. position.x = tmat.m[12];
  63033. position.y = tmat.m[13];
  63034. position.z = tmat.m[14];
  63035. };
  63036. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63037. var len = bones.length;
  63038. var meshPos = this.mesh.position;
  63039. for (var i = 0; i < len; i++) {
  63040. var bone = bones[i];
  63041. var points = this._debugLines[i];
  63042. if (!points) {
  63043. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63044. this._debugLines[i] = points;
  63045. }
  63046. this._getBonePosition(points[0], bone, meshMat);
  63047. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63048. points[0].subtractInPlace(meshPos);
  63049. points[1].subtractInPlace(meshPos);
  63050. }
  63051. };
  63052. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63053. var len = bones.length;
  63054. var boneNum = 0;
  63055. var meshPos = this.mesh.position;
  63056. for (var i = len - 1; i >= 0; i--) {
  63057. var childBone = bones[i];
  63058. var parentBone = childBone.getParent();
  63059. if (!parentBone) {
  63060. continue;
  63061. }
  63062. var points = this._debugLines[boneNum];
  63063. if (!points) {
  63064. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63065. this._debugLines[boneNum] = points;
  63066. }
  63067. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63068. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63069. points[0].subtractInPlace(meshPos);
  63070. points[1].subtractInPlace(meshPos);
  63071. boneNum++;
  63072. }
  63073. };
  63074. /** Update the viewer to sync with current skeleton state */
  63075. SkeletonViewer.prototype.update = function () {
  63076. if (this.autoUpdateBonesMatrices) {
  63077. this.skeleton.computeAbsoluteTransforms();
  63078. }
  63079. if (this.skeleton.bones[0].length === undefined) {
  63080. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63081. }
  63082. else {
  63083. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63084. }
  63085. if (!this._debugMesh) {
  63086. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  63087. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63088. }
  63089. else {
  63090. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63091. }
  63092. this._debugMesh.position.copyFrom(this.mesh.position);
  63093. this._debugMesh.color = this.color;
  63094. };
  63095. /** Release associated resources */
  63096. SkeletonViewer.prototype.dispose = function () {
  63097. if (this._debugMesh) {
  63098. this.isEnabled = false;
  63099. this._debugMesh.dispose();
  63100. this._debugMesh = null;
  63101. }
  63102. };
  63103. return SkeletonViewer;
  63104. }());
  63105. Debug.SkeletonViewer = SkeletonViewer;
  63106. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63107. })(BABYLON || (BABYLON = {}));
  63108. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63109. /**
  63110. * Module Debug contains the (visual) components to debug a scene correctly
  63111. */
  63112. var BABYLON;
  63113. (function (BABYLON) {
  63114. var Debug;
  63115. (function (Debug) {
  63116. /**
  63117. * The Axes viewer will show 3 axes in a specific point in space
  63118. */
  63119. var AxesViewer = /** @class */ (function () {
  63120. /**
  63121. * Creates a new AxesViewer
  63122. * @param scene defines the hosting scene
  63123. * @param scaleLines defines a number used to scale line length (1 by default)
  63124. */
  63125. function AxesViewer(scene, scaleLines) {
  63126. if (scaleLines === void 0) { scaleLines = 1; }
  63127. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63128. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63129. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63130. /**
  63131. * Gets or sets a number used to scale line length
  63132. */
  63133. this.scaleLines = 1;
  63134. this.scaleLines = scaleLines;
  63135. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63136. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63137. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63138. this._xmesh.renderingGroupId = 2;
  63139. this._ymesh.renderingGroupId = 2;
  63140. this._zmesh.renderingGroupId = 2;
  63141. this._xmesh.material.checkReadyOnlyOnce = true;
  63142. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63143. this._ymesh.material.checkReadyOnlyOnce = true;
  63144. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63145. this._zmesh.material.checkReadyOnlyOnce = true;
  63146. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63147. this.scene = scene;
  63148. }
  63149. /**
  63150. * Force the viewer to update
  63151. * @param position defines the position of the viewer
  63152. * @param xaxis defines the x axis of the viewer
  63153. * @param yaxis defines the y axis of the viewer
  63154. * @param zaxis defines the z axis of the viewer
  63155. */
  63156. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63157. var scaleLines = this.scaleLines;
  63158. if (this._xmesh) {
  63159. this._xmesh.position.copyFrom(position);
  63160. }
  63161. if (this._ymesh) {
  63162. this._ymesh.position.copyFrom(position);
  63163. }
  63164. if (this._zmesh) {
  63165. this._zmesh.position.copyFrom(position);
  63166. }
  63167. var point2 = this._xline[1];
  63168. point2.x = xaxis.x * scaleLines;
  63169. point2.y = xaxis.y * scaleLines;
  63170. point2.z = xaxis.z * scaleLines;
  63171. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  63172. point2 = this._yline[1];
  63173. point2.x = yaxis.x * scaleLines;
  63174. point2.y = yaxis.y * scaleLines;
  63175. point2.z = yaxis.z * scaleLines;
  63176. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  63177. point2 = this._zline[1];
  63178. point2.x = zaxis.x * scaleLines;
  63179. point2.y = zaxis.y * scaleLines;
  63180. point2.z = zaxis.z * scaleLines;
  63181. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  63182. };
  63183. /** Releases resources */
  63184. AxesViewer.prototype.dispose = function () {
  63185. if (this._xmesh) {
  63186. this._xmesh.dispose();
  63187. }
  63188. if (this._ymesh) {
  63189. this._ymesh.dispose();
  63190. }
  63191. if (this._zmesh) {
  63192. this._zmesh.dispose();
  63193. }
  63194. this._xmesh = null;
  63195. this._ymesh = null;
  63196. this._zmesh = null;
  63197. this.scene = null;
  63198. };
  63199. return AxesViewer;
  63200. }());
  63201. Debug.AxesViewer = AxesViewer;
  63202. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63203. })(BABYLON || (BABYLON = {}));
  63204. //# sourceMappingURL=babylon.axesViewer.js.map
  63205. var BABYLON;
  63206. (function (BABYLON) {
  63207. var Debug;
  63208. (function (Debug) {
  63209. /**
  63210. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  63211. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  63212. */
  63213. var BoneAxesViewer = /** @class */ (function (_super) {
  63214. __extends(BoneAxesViewer, _super);
  63215. /**
  63216. * Creates a new BoneAxesViewer
  63217. * @param scene defines the hosting scene
  63218. * @param bone defines the target bone
  63219. * @param mesh defines the target mesh
  63220. * @param scaleLines defines a scaling factor for line length (1 by default)
  63221. */
  63222. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63223. if (scaleLines === void 0) { scaleLines = 1; }
  63224. var _this = _super.call(this, scene, scaleLines) || this;
  63225. /** Gets current position */
  63226. _this.pos = BABYLON.Vector3.Zero();
  63227. /** Gets direction of X axis */
  63228. _this.xaxis = BABYLON.Vector3.Zero();
  63229. /** Gets direction of Y axis */
  63230. _this.yaxis = BABYLON.Vector3.Zero();
  63231. /** Gets direction of Z axis */
  63232. _this.zaxis = BABYLON.Vector3.Zero();
  63233. _this.mesh = mesh;
  63234. _this.bone = bone;
  63235. return _this;
  63236. }
  63237. /**
  63238. * Force the viewer to update
  63239. */
  63240. BoneAxesViewer.prototype.update = function () {
  63241. if (!this.mesh || !this.bone) {
  63242. return;
  63243. }
  63244. var bone = this.bone;
  63245. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63246. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63247. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63248. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63249. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63250. };
  63251. /** Releases resources */
  63252. BoneAxesViewer.prototype.dispose = function () {
  63253. if (this.mesh) {
  63254. this.mesh = null;
  63255. this.bone = null;
  63256. _super.prototype.dispose.call(this);
  63257. }
  63258. };
  63259. return BoneAxesViewer;
  63260. }(Debug.AxesViewer));
  63261. Debug.BoneAxesViewer = BoneAxesViewer;
  63262. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63263. })(BABYLON || (BABYLON = {}));
  63264. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63265. var BABYLON;
  63266. (function (BABYLON) {
  63267. /**
  63268. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63269. * in order to better appreciate the issue one might have.
  63270. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63271. */
  63272. var RayHelper = /** @class */ (function () {
  63273. /**
  63274. * Instantiate a new ray helper.
  63275. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63276. * in order to better appreciate the issue one might have.
  63277. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63278. * @param ray Defines the ray we are currently tryin to visualize
  63279. */
  63280. function RayHelper(ray) {
  63281. this.ray = ray;
  63282. }
  63283. /**
  63284. * Helper function to create a colored helper in a scene in one line.
  63285. * @param ray Defines the ray we are currently tryin to visualize
  63286. * @param scene Defines the scene the ray is used in
  63287. * @param color Defines the color we want to see the ray in
  63288. * @returns The newly created ray helper.
  63289. */
  63290. RayHelper.CreateAndShow = function (ray, scene, color) {
  63291. var helper = new RayHelper(ray);
  63292. helper.show(scene, color);
  63293. return helper;
  63294. };
  63295. /**
  63296. * Shows the ray we are willing to debug.
  63297. * @param scene Defines the scene the ray needs to be rendered in
  63298. * @param color Defines the color the ray needs to be rendered in
  63299. */
  63300. RayHelper.prototype.show = function (scene, color) {
  63301. if (!this._renderFunction && this.ray) {
  63302. var ray = this.ray;
  63303. this._renderFunction = this._render.bind(this);
  63304. this._scene = scene;
  63305. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63306. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63307. if (this._renderFunction) {
  63308. this._scene.registerBeforeRender(this._renderFunction);
  63309. }
  63310. }
  63311. if (color && this._renderLine) {
  63312. this._renderLine.color.copyFrom(color);
  63313. }
  63314. };
  63315. /**
  63316. * Hides the ray we are debugging.
  63317. */
  63318. RayHelper.prototype.hide = function () {
  63319. if (this._renderFunction && this._scene) {
  63320. this._scene.unregisterBeforeRender(this._renderFunction);
  63321. this._scene = null;
  63322. this._renderFunction = null;
  63323. if (this._renderLine) {
  63324. this._renderLine.dispose();
  63325. this._renderLine = null;
  63326. }
  63327. this._renderPoints = [];
  63328. }
  63329. };
  63330. RayHelper.prototype._render = function () {
  63331. var ray = this.ray;
  63332. if (!ray) {
  63333. return;
  63334. }
  63335. var point = this._renderPoints[1];
  63336. var len = Math.min(ray.length, 1000000);
  63337. point.copyFrom(ray.direction);
  63338. point.scaleInPlace(len);
  63339. point.addInPlace(ray.origin);
  63340. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63341. };
  63342. /**
  63343. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  63344. * @param mesh Defines the mesh we want the helper attached to
  63345. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  63346. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  63347. * @param length Defines the length of the ray
  63348. */
  63349. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63350. this._attachedToMesh = mesh;
  63351. var ray = this.ray;
  63352. if (!ray) {
  63353. return;
  63354. }
  63355. if (!ray.direction) {
  63356. ray.direction = BABYLON.Vector3.Zero();
  63357. }
  63358. if (!ray.origin) {
  63359. ray.origin = BABYLON.Vector3.Zero();
  63360. }
  63361. if (length) {
  63362. ray.length = length;
  63363. }
  63364. if (!meshSpaceOrigin) {
  63365. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63366. }
  63367. if (!meshSpaceDirection) {
  63368. // -1 so that this will work with Mesh.lookAt
  63369. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63370. }
  63371. if (!this._meshSpaceDirection) {
  63372. this._meshSpaceDirection = meshSpaceDirection.clone();
  63373. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63374. }
  63375. else {
  63376. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63377. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63378. }
  63379. if (!this._updateToMeshFunction) {
  63380. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63381. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63382. }
  63383. this._updateToMesh();
  63384. };
  63385. /**
  63386. * Detach the ray helper from the mesh it has previously been attached to.
  63387. */
  63388. RayHelper.prototype.detachFromMesh = function () {
  63389. if (this._attachedToMesh) {
  63390. if (this._updateToMeshFunction) {
  63391. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63392. }
  63393. this._attachedToMesh = null;
  63394. this._updateToMeshFunction = null;
  63395. }
  63396. };
  63397. RayHelper.prototype._updateToMesh = function () {
  63398. var ray = this.ray;
  63399. if (!this._attachedToMesh || !ray) {
  63400. return;
  63401. }
  63402. if (this._attachedToMesh._isDisposed) {
  63403. this.detachFromMesh();
  63404. return;
  63405. }
  63406. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63407. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63408. };
  63409. /**
  63410. * Dispose the helper and release its associated resources.
  63411. */
  63412. RayHelper.prototype.dispose = function () {
  63413. this.hide();
  63414. this.detachFromMesh();
  63415. this.ray = null;
  63416. };
  63417. return RayHelper;
  63418. }());
  63419. BABYLON.RayHelper = RayHelper;
  63420. })(BABYLON || (BABYLON = {}));
  63421. //# sourceMappingURL=babylon.rayHelper.js.map
  63422. var BABYLON;
  63423. (function (BABYLON) {
  63424. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  63425. get: function () {
  63426. if (!this._debugLayer) {
  63427. this._debugLayer = new DebugLayer(this);
  63428. }
  63429. return this._debugLayer;
  63430. },
  63431. enumerable: true,
  63432. configurable: true
  63433. });
  63434. /**
  63435. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63436. * what is happening in your scene
  63437. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63438. */
  63439. var DebugLayer = /** @class */ (function () {
  63440. /**
  63441. * Instantiates a new debug layer.
  63442. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63443. * what is happening in your scene
  63444. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63445. * @param scene Defines the scene to inspect
  63446. */
  63447. function DebugLayer(scene) {
  63448. var _this = this;
  63449. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63450. /**
  63451. * Observable triggered when a property is changed through the inspector.
  63452. */
  63453. this.onPropertyChangedObservable = new BABYLON.Observable();
  63454. this._scene = scene;
  63455. this._scene.onDisposeObservable.add(function () {
  63456. // Debug layer
  63457. if (_this._scene._debugLayer) {
  63458. _this._scene._debugLayer.hide();
  63459. }
  63460. });
  63461. }
  63462. /** Creates the inspector window. */
  63463. DebugLayer.prototype._createInspector = function (config) {
  63464. if (config === void 0) { config = {}; }
  63465. var popup = config.popup || false;
  63466. var initialTab = config.initialTab || 0;
  63467. var parentElement = config.parentElement || null;
  63468. if (!this._inspector) {
  63469. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63470. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63471. } // else nothing to do as instance is already created
  63472. };
  63473. /**
  63474. * Get if the inspector is visible or not.
  63475. * @returns true if visible otherwise, false
  63476. */
  63477. DebugLayer.prototype.isVisible = function () {
  63478. if (!this._inspector) {
  63479. return false;
  63480. }
  63481. return true;
  63482. };
  63483. /**
  63484. * Hide the inspector and close its window.
  63485. */
  63486. DebugLayer.prototype.hide = function () {
  63487. if (this._inspector) {
  63488. try {
  63489. this._inspector.dispose();
  63490. }
  63491. catch (e) {
  63492. // If the inspector has been removed directly from the inspector tool
  63493. }
  63494. this.onPropertyChangedObservable.clear();
  63495. this._inspector = null;
  63496. }
  63497. };
  63498. /**
  63499. *
  63500. * Launch the debugLayer.
  63501. *
  63502. * initialTab:
  63503. * | Value | Tab Name |
  63504. * | --- | --- |
  63505. * | 0 | Scene |
  63506. * | 1 | Console |
  63507. * | 2 | Stats |
  63508. * | 3 | Textures |
  63509. * | 4 | Mesh |
  63510. * | 5 | Light |
  63511. * | 6 | Material |
  63512. * | 7 | GLTF |
  63513. * | 8 | GUI |
  63514. * | 9 | Physics |
  63515. * | 10 | Camera |
  63516. * | 11 | Audio |
  63517. *
  63518. * @param config Define the configuration of the inspector
  63519. */
  63520. DebugLayer.prototype.show = function (config) {
  63521. if (config === void 0) { config = {}; }
  63522. if (typeof this.BJSINSPECTOR == 'undefined') {
  63523. // Load inspector and add it to the DOM
  63524. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63525. }
  63526. else {
  63527. // Otherwise creates the inspector
  63528. this._createInspector(config);
  63529. }
  63530. };
  63531. /**
  63532. * Gets the active tab
  63533. * @return the index of the active tab or -1 if the inspector is hidden
  63534. */
  63535. DebugLayer.prototype.getActiveTab = function () {
  63536. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  63537. };
  63538. /**
  63539. * Define the url to get the inspector script from.
  63540. * By default it uses the babylonjs CDN.
  63541. * @ignoreNaming
  63542. */
  63543. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63544. return DebugLayer;
  63545. }());
  63546. BABYLON.DebugLayer = DebugLayer;
  63547. })(BABYLON || (BABYLON = {}));
  63548. //# sourceMappingURL=babylon.debugLayer.js.map
  63549. var BABYLON;
  63550. (function (BABYLON) {
  63551. var Debug;
  63552. (function (Debug) {
  63553. /**
  63554. * Used to show the physics impostor around the specific mesh
  63555. */
  63556. var PhysicsViewer = /** @class */ (function () {
  63557. /**
  63558. * Creates a new PhysicsViewer
  63559. * @param scene defines the hosting scene
  63560. */
  63561. function PhysicsViewer(scene) {
  63562. /** @hidden */
  63563. this._impostors = [];
  63564. /** @hidden */
  63565. this._meshes = [];
  63566. /** @hidden */
  63567. this._numMeshes = 0;
  63568. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63569. var physicEngine = this._scene.getPhysicsEngine();
  63570. if (physicEngine) {
  63571. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  63572. }
  63573. }
  63574. /** @hidden */
  63575. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63576. var plugin = this._physicsEnginePlugin;
  63577. for (var i = 0; i < this._numMeshes; i++) {
  63578. var impostor = this._impostors[i];
  63579. if (!impostor) {
  63580. continue;
  63581. }
  63582. if (impostor.isDisposed) {
  63583. this.hideImpostor(this._impostors[i--]);
  63584. }
  63585. else {
  63586. var mesh = this._meshes[i];
  63587. if (mesh && plugin) {
  63588. plugin.syncMeshWithImpostor(mesh, impostor);
  63589. }
  63590. }
  63591. }
  63592. };
  63593. /**
  63594. * Renders a specified physic impostor
  63595. * @param impostor defines the impostor to render
  63596. */
  63597. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63598. if (!this._scene) {
  63599. return;
  63600. }
  63601. for (var i = 0; i < this._numMeshes; i++) {
  63602. if (this._impostors[i] == impostor) {
  63603. return;
  63604. }
  63605. }
  63606. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63607. if (debugMesh) {
  63608. this._impostors[this._numMeshes] = impostor;
  63609. this._meshes[this._numMeshes] = debugMesh;
  63610. if (this._numMeshes === 0) {
  63611. this._renderFunction = this._updateDebugMeshes.bind(this);
  63612. this._scene.registerBeforeRender(this._renderFunction);
  63613. }
  63614. this._numMeshes++;
  63615. }
  63616. };
  63617. /**
  63618. * Hides a specified physic impostor
  63619. * @param impostor defines the impostor to hide
  63620. */
  63621. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63622. if (!impostor || !this._scene) {
  63623. return;
  63624. }
  63625. var removed = false;
  63626. for (var i = 0; i < this._numMeshes; i++) {
  63627. if (this._impostors[i] == impostor) {
  63628. var mesh = this._meshes[i];
  63629. if (!mesh) {
  63630. continue;
  63631. }
  63632. this._scene.removeMesh(mesh);
  63633. mesh.dispose();
  63634. this._numMeshes--;
  63635. if (this._numMeshes > 0) {
  63636. this._meshes[i] = this._meshes[this._numMeshes];
  63637. this._impostors[i] = this._impostors[this._numMeshes];
  63638. this._meshes[this._numMeshes] = null;
  63639. this._impostors[this._numMeshes] = null;
  63640. }
  63641. else {
  63642. this._meshes[0] = null;
  63643. this._impostors[0] = null;
  63644. }
  63645. removed = true;
  63646. break;
  63647. }
  63648. }
  63649. if (removed && this._numMeshes === 0) {
  63650. this._scene.unregisterBeforeRender(this._renderFunction);
  63651. }
  63652. };
  63653. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63654. if (!this._debugMaterial) {
  63655. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63656. this._debugMaterial.wireframe = true;
  63657. }
  63658. return this._debugMaterial;
  63659. };
  63660. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63661. if (!this._debugBoxMesh) {
  63662. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63663. this._debugBoxMesh.renderingGroupId = 1;
  63664. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63665. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63666. scene.removeMesh(this._debugBoxMesh);
  63667. }
  63668. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63669. };
  63670. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63671. if (!this._debugSphereMesh) {
  63672. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63673. this._debugSphereMesh.renderingGroupId = 1;
  63674. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63675. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63676. scene.removeMesh(this._debugSphereMesh);
  63677. }
  63678. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63679. };
  63680. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63681. var mesh = null;
  63682. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63683. mesh = this._getDebugBoxMesh(scene);
  63684. impostor.getBoxSizeToRef(mesh.scaling);
  63685. }
  63686. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63687. mesh = this._getDebugSphereMesh(scene);
  63688. var radius = impostor.getRadius();
  63689. mesh.scaling.x = radius * 2;
  63690. mesh.scaling.y = radius * 2;
  63691. mesh.scaling.z = radius * 2;
  63692. }
  63693. return mesh;
  63694. };
  63695. /** Releases all resources */
  63696. PhysicsViewer.prototype.dispose = function () {
  63697. for (var i = 0; i < this._numMeshes; i++) {
  63698. this.hideImpostor(this._impostors[i]);
  63699. }
  63700. if (this._debugBoxMesh) {
  63701. this._debugBoxMesh.dispose();
  63702. }
  63703. if (this._debugSphereMesh) {
  63704. this._debugSphereMesh.dispose();
  63705. }
  63706. if (this._debugMaterial) {
  63707. this._debugMaterial.dispose();
  63708. }
  63709. this._impostors.length = 0;
  63710. this._scene = null;
  63711. this._physicsEnginePlugin = null;
  63712. };
  63713. return PhysicsViewer;
  63714. }());
  63715. Debug.PhysicsViewer = PhysicsViewer;
  63716. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63717. })(BABYLON || (BABYLON = {}));
  63718. //# sourceMappingURL=babylon.physicsViewer.js.map
  63719. var BABYLON;
  63720. (function (BABYLON) {
  63721. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  63722. get: function () {
  63723. return this._forceShowBoundingBoxes || false;
  63724. },
  63725. set: function (value) {
  63726. this._forceShowBoundingBoxes = value;
  63727. // Lazyly creates a BB renderer if needed.
  63728. if (value) {
  63729. this.getBoundingBoxRenderer();
  63730. }
  63731. },
  63732. enumerable: true,
  63733. configurable: true
  63734. });
  63735. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  63736. if (!this._boundingBoxRenderer) {
  63737. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  63738. }
  63739. return this._boundingBoxRenderer;
  63740. };
  63741. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  63742. get: function () {
  63743. return this._showBoundingBox || false;
  63744. },
  63745. set: function (value) {
  63746. this._showBoundingBox = value;
  63747. // Lazyly creates a BB renderer if needed.
  63748. if (value) {
  63749. this.getScene().getBoundingBoxRenderer();
  63750. }
  63751. },
  63752. enumerable: true,
  63753. configurable: true
  63754. });
  63755. /**
  63756. * Component responsible of rendering the bounding box of the meshes in a scene.
  63757. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  63758. */
  63759. var BoundingBoxRenderer = /** @class */ (function () {
  63760. /**
  63761. * Instantiates a new bounding box renderer in a scene.
  63762. * @param scene the scene the renderer renders in
  63763. */
  63764. function BoundingBoxRenderer(scene) {
  63765. /**
  63766. * The component name helpfull to identify the component in the list of scene components.
  63767. */
  63768. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  63769. /**
  63770. * Color of the bounding box lines placed in front of an object
  63771. */
  63772. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63773. /**
  63774. * Color of the bounding box lines placed behind an object
  63775. */
  63776. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63777. /**
  63778. * Defines if the renderer should show the back lines or not
  63779. */
  63780. this.showBackLines = true;
  63781. /**
  63782. * @hidden
  63783. */
  63784. this.renderList = new BABYLON.SmartArray(32);
  63785. this._vertexBuffers = {};
  63786. this.scene = scene;
  63787. scene._addComponent(this);
  63788. }
  63789. /**
  63790. * Registers the component in a given scene
  63791. */
  63792. BoundingBoxRenderer.prototype.register = function () {
  63793. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  63794. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  63795. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  63796. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  63797. };
  63798. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  63799. if (mesh.showSubMeshesBoundingBox) {
  63800. var boundingInfo = subMesh.getBoundingInfo();
  63801. if (boundingInfo !== null && boundingInfo !== undefined) {
  63802. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63803. this.renderList.push(boundingInfo.boundingBox);
  63804. }
  63805. }
  63806. };
  63807. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  63808. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  63809. var boundingInfo = sourceMesh.getBoundingInfo();
  63810. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63811. this.renderList.push(boundingInfo.boundingBox);
  63812. }
  63813. };
  63814. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63815. if (this._colorShader) {
  63816. return;
  63817. }
  63818. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  63819. attributes: [BABYLON.VertexBuffer.PositionKind],
  63820. uniforms: ["world", "viewProjection", "color"]
  63821. });
  63822. var engine = this.scene.getEngine();
  63823. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63824. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63825. this._createIndexBuffer();
  63826. };
  63827. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  63828. var engine = this.scene.getEngine();
  63829. 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]);
  63830. };
  63831. /**
  63832. * Rebuilds the elements related to this component in case of
  63833. * context lost for instance.
  63834. */
  63835. BoundingBoxRenderer.prototype.rebuild = function () {
  63836. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63837. if (vb) {
  63838. vb._rebuild();
  63839. }
  63840. this._createIndexBuffer();
  63841. };
  63842. /**
  63843. * @hidden
  63844. */
  63845. BoundingBoxRenderer.prototype.reset = function () {
  63846. this.renderList.reset();
  63847. };
  63848. /**
  63849. * Render the bounding boxes of a specific rendering group
  63850. * @param renderingGroupId defines the rendering group to render
  63851. */
  63852. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  63853. if (this.renderList.length === 0) {
  63854. return;
  63855. }
  63856. this._prepareRessources();
  63857. if (!this._colorShader.isReady()) {
  63858. return;
  63859. }
  63860. var engine = this.scene.getEngine();
  63861. engine.setDepthWrite(false);
  63862. this._colorShader._preBind();
  63863. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63864. var boundingBox = this.renderList.data[boundingBoxIndex];
  63865. if (boundingBox._tag !== renderingGroupId) {
  63866. continue;
  63867. }
  63868. var min = boundingBox.minimum;
  63869. var max = boundingBox.maximum;
  63870. var diff = max.subtract(min);
  63871. var median = min.add(diff.scale(0.5));
  63872. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63873. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63874. .multiply(boundingBox.getWorldMatrix());
  63875. // VBOs
  63876. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63877. if (this.showBackLines) {
  63878. // Back
  63879. engine.setDepthFunctionToGreaterOrEqual();
  63880. this.scene.resetCachedMaterial();
  63881. this._colorShader.setColor4("color", this.backColor.toColor4());
  63882. this._colorShader.bind(worldMatrix);
  63883. // Draw order
  63884. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63885. }
  63886. // Front
  63887. engine.setDepthFunctionToLess();
  63888. this.scene.resetCachedMaterial();
  63889. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63890. this._colorShader.bind(worldMatrix);
  63891. // Draw order
  63892. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63893. }
  63894. this._colorShader.unbind();
  63895. engine.setDepthFunctionToLessOrEqual();
  63896. engine.setDepthWrite(true);
  63897. };
  63898. /**
  63899. * In case of occlusion queries, we can render the occlusion bounding box through this method
  63900. * @param mesh Define the mesh to render the occlusion bounding box for
  63901. */
  63902. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63903. this._prepareRessources();
  63904. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  63905. return;
  63906. }
  63907. var engine = this.scene.getEngine();
  63908. engine.setDepthWrite(false);
  63909. engine.setColorWrite(false);
  63910. this._colorShader._preBind();
  63911. var boundingBox = mesh._boundingInfo.boundingBox;
  63912. var min = boundingBox.minimum;
  63913. var max = boundingBox.maximum;
  63914. var diff = max.subtract(min);
  63915. var median = min.add(diff.scale(0.5));
  63916. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63917. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63918. .multiply(boundingBox.getWorldMatrix());
  63919. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63920. engine.setDepthFunctionToLess();
  63921. this.scene.resetCachedMaterial();
  63922. this._colorShader.bind(worldMatrix);
  63923. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63924. this._colorShader.unbind();
  63925. engine.setDepthFunctionToLessOrEqual();
  63926. engine.setDepthWrite(true);
  63927. engine.setColorWrite(true);
  63928. };
  63929. /**
  63930. * Dispose and release the resources attached to this renderer.
  63931. */
  63932. BoundingBoxRenderer.prototype.dispose = function () {
  63933. if (!this._colorShader) {
  63934. return;
  63935. }
  63936. this.renderList.dispose();
  63937. this._colorShader.dispose();
  63938. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63939. if (buffer) {
  63940. buffer.dispose();
  63941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63942. }
  63943. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63944. };
  63945. return BoundingBoxRenderer;
  63946. }());
  63947. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63948. })(BABYLON || (BABYLON = {}));
  63949. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63950. var BABYLON;
  63951. (function (BABYLON) {
  63952. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63953. return this._gl.createTransformFeedback();
  63954. };
  63955. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63956. this._gl.deleteTransformFeedback(value);
  63957. };
  63958. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63959. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63960. };
  63961. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63962. if (usePoints === void 0) { usePoints = true; }
  63963. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63964. };
  63965. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63966. this._gl.endTransformFeedback();
  63967. };
  63968. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63969. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63970. };
  63971. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63972. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  63973. };
  63974. })(BABYLON || (BABYLON = {}));
  63975. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  63976. var BABYLON;
  63977. (function (BABYLON) {
  63978. /**
  63979. * This represents a GPU particle system in Babylon
  63980. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  63981. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  63982. */
  63983. var GPUParticleSystem = /** @class */ (function (_super) {
  63984. __extends(GPUParticleSystem, _super);
  63985. /**
  63986. * Instantiates a GPU particle system.
  63987. * 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.
  63988. * @param name The name of the particle system
  63989. * @param options The options used to create the system
  63990. * @param scene The scene the particle system belongs to
  63991. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  63992. */
  63993. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  63994. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  63995. var _this = _super.call(this, name) || this;
  63996. /**
  63997. * The layer mask we are rendering the particles through.
  63998. */
  63999. _this.layerMask = 0x0FFFFFFF;
  64000. _this._accumulatedCount = 0;
  64001. _this._targetIndex = 0;
  64002. _this._currentRenderId = -1;
  64003. _this._started = false;
  64004. _this._stopped = false;
  64005. _this._timeDelta = 0;
  64006. _this._attributesStrideSize = 21;
  64007. _this._actualFrame = 0;
  64008. _this._rawTextureWidth = 256;
  64009. /**
  64010. * An event triggered when the system is disposed.
  64011. */
  64012. _this.onDisposeObservable = new BABYLON.Observable();
  64013. /**
  64014. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64015. * to override the particles.
  64016. */
  64017. _this.forceDepthWrite = false;
  64018. _this._preWarmDone = false;
  64019. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64020. // Setup the default processing configuration to the scene.
  64021. _this._attachImageProcessingConfiguration(null);
  64022. _this._engine = _this._scene.getEngine();
  64023. if (!options.randomTextureSize) {
  64024. delete options.randomTextureSize;
  64025. }
  64026. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64027. var optionsAsNumber = options;
  64028. if (isFinite(optionsAsNumber)) {
  64029. fullOptions.capacity = optionsAsNumber;
  64030. }
  64031. _this._capacity = fullOptions.capacity;
  64032. _this._activeCount = fullOptions.capacity;
  64033. _this._currentActiveCount = 0;
  64034. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  64035. _this._scene.particleSystems.push(_this);
  64036. _this._updateEffectOptions = {
  64037. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  64038. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  64039. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  64040. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  64041. uniformBuffersNames: [],
  64042. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  64043. defines: "",
  64044. fallbacks: null,
  64045. onCompiled: null,
  64046. onError: null,
  64047. indexParameters: null,
  64048. maxSimultaneousLights: 0,
  64049. transformFeedbackVaryings: []
  64050. };
  64051. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  64052. // Random data
  64053. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  64054. var d = [];
  64055. for (var i = 0; i < maxTextureSize; ++i) {
  64056. d.push(Math.random());
  64057. d.push(Math.random());
  64058. d.push(Math.random());
  64059. d.push(Math.random());
  64060. }
  64061. _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);
  64062. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64063. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64064. d = [];
  64065. for (var i = 0; i < maxTextureSize; ++i) {
  64066. d.push(Math.random());
  64067. d.push(Math.random());
  64068. d.push(Math.random());
  64069. d.push(Math.random());
  64070. }
  64071. _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);
  64072. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64073. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64074. _this._randomTextureSize = maxTextureSize;
  64075. return _this;
  64076. }
  64077. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  64078. /**
  64079. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  64080. */
  64081. get: function () {
  64082. if (!BABYLON.Engine.LastCreatedEngine) {
  64083. return false;
  64084. }
  64085. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  64086. },
  64087. enumerable: true,
  64088. configurable: true
  64089. });
  64090. /**
  64091. * Gets the maximum number of particles active at the same time.
  64092. * @returns The max number of active particles.
  64093. */
  64094. GPUParticleSystem.prototype.getCapacity = function () {
  64095. return this._capacity;
  64096. };
  64097. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  64098. /**
  64099. * Gets or set the number of active particles
  64100. */
  64101. get: function () {
  64102. return this._activeCount;
  64103. },
  64104. set: function (value) {
  64105. this._activeCount = Math.min(value, this._capacity);
  64106. },
  64107. enumerable: true,
  64108. configurable: true
  64109. });
  64110. /**
  64111. * Is this system ready to be used/rendered
  64112. * @return true if the system is ready
  64113. */
  64114. GPUParticleSystem.prototype.isReady = function () {
  64115. if (!this._updateEffect) {
  64116. this._recreateUpdateEffect();
  64117. this._recreateRenderEffect();
  64118. return false;
  64119. }
  64120. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  64121. return false;
  64122. }
  64123. return true;
  64124. };
  64125. /**
  64126. * Gets if the system has been started. (Note: this will still be true after stop is called)
  64127. * @returns True if it has been started, otherwise false.
  64128. */
  64129. GPUParticleSystem.prototype.isStarted = function () {
  64130. return this._started;
  64131. };
  64132. /**
  64133. * Starts the particle system and begins to emit
  64134. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  64135. */
  64136. GPUParticleSystem.prototype.start = function (delay) {
  64137. var _this = this;
  64138. if (delay === void 0) { delay = this.startDelay; }
  64139. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  64140. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  64141. }
  64142. if (delay) {
  64143. setTimeout(function () {
  64144. _this.start(0);
  64145. }, delay);
  64146. return;
  64147. }
  64148. this._started = true;
  64149. this._stopped = false;
  64150. this._preWarmDone = false;
  64151. // Animations
  64152. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  64153. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  64154. }
  64155. };
  64156. /**
  64157. * Stops the particle system.
  64158. */
  64159. GPUParticleSystem.prototype.stop = function () {
  64160. this._stopped = true;
  64161. };
  64162. /**
  64163. * Remove all active particles
  64164. */
  64165. GPUParticleSystem.prototype.reset = function () {
  64166. this._releaseBuffers();
  64167. this._releaseVAOs();
  64168. this._currentActiveCount = 0;
  64169. this._targetIndex = 0;
  64170. };
  64171. /**
  64172. * Returns the string "GPUParticleSystem"
  64173. * @returns a string containing the class name
  64174. */
  64175. GPUParticleSystem.prototype.getClassName = function () {
  64176. return "GPUParticleSystem";
  64177. };
  64178. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  64179. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  64180. this._releaseBuffers();
  64181. return this;
  64182. };
  64183. /**
  64184. * Adds a new color gradient
  64185. * @param gradient defines the gradient to use (between 0 and 1)
  64186. * @param color1 defines the color to affect to the specified gradient
  64187. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  64188. * @returns the current particle system
  64189. */
  64190. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  64191. if (!this._colorGradients) {
  64192. this._colorGradients = [];
  64193. }
  64194. var colorGradient = new BABYLON.ColorGradient();
  64195. colorGradient.gradient = gradient;
  64196. colorGradient.color1 = color1;
  64197. this._colorGradients.push(colorGradient);
  64198. this._colorGradients.sort(function (a, b) {
  64199. if (a.gradient < b.gradient) {
  64200. return -1;
  64201. }
  64202. else if (a.gradient > b.gradient) {
  64203. return 1;
  64204. }
  64205. return 0;
  64206. });
  64207. if (this._colorGradientsTexture) {
  64208. this._colorGradientsTexture.dispose();
  64209. this._colorGradientsTexture = null;
  64210. }
  64211. this._releaseBuffers();
  64212. return this;
  64213. };
  64214. /**
  64215. * Remove a specific color gradient
  64216. * @param gradient defines the gradient to remove
  64217. * @returns the current particle system
  64218. */
  64219. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  64220. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  64221. this._colorGradientsTexture = null;
  64222. return this;
  64223. };
  64224. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  64225. var valueGradient = new BABYLON.FactorGradient();
  64226. valueGradient.gradient = gradient;
  64227. valueGradient.factor1 = factor;
  64228. factorGradients.push(valueGradient);
  64229. factorGradients.sort(function (a, b) {
  64230. if (a.gradient < b.gradient) {
  64231. return -1;
  64232. }
  64233. else if (a.gradient > b.gradient) {
  64234. return 1;
  64235. }
  64236. return 0;
  64237. });
  64238. this._releaseBuffers();
  64239. };
  64240. /**
  64241. * Adds a new size gradient
  64242. * @param gradient defines the gradient to use (between 0 and 1)
  64243. * @param factor defines the size factor to affect to the specified gradient
  64244. * @returns the current particle system
  64245. */
  64246. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  64247. if (!this._sizeGradients) {
  64248. this._sizeGradients = [];
  64249. }
  64250. this._addFactorGradient(this._sizeGradients, gradient, factor);
  64251. if (this._sizeGradientsTexture) {
  64252. this._sizeGradientsTexture.dispose();
  64253. this._sizeGradientsTexture = null;
  64254. }
  64255. this._releaseBuffers();
  64256. return this;
  64257. };
  64258. /**
  64259. * Remove a specific size gradient
  64260. * @param gradient defines the gradient to remove
  64261. * @returns the current particle system
  64262. */
  64263. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  64264. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  64265. this._sizeGradientsTexture = null;
  64266. return this;
  64267. };
  64268. /**
  64269. * Adds a new angular speed gradient
  64270. * @param gradient defines the gradient to use (between 0 and 1)
  64271. * @param factor defines the angular speed to affect to the specified gradient
  64272. * @returns the current particle system
  64273. */
  64274. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  64275. if (!this._angularSpeedGradients) {
  64276. this._angularSpeedGradients = [];
  64277. }
  64278. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  64279. if (this._angularSpeedGradientsTexture) {
  64280. this._angularSpeedGradientsTexture.dispose();
  64281. this._angularSpeedGradientsTexture = null;
  64282. }
  64283. this._releaseBuffers();
  64284. return this;
  64285. };
  64286. /**
  64287. * Remove a specific angular speed gradient
  64288. * @param gradient defines the gradient to remove
  64289. * @returns the current particle system
  64290. */
  64291. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  64292. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  64293. this._angularSpeedGradientsTexture = null;
  64294. return this;
  64295. };
  64296. /**
  64297. * Adds a new velocity gradient
  64298. * @param gradient defines the gradient to use (between 0 and 1)
  64299. * @param factor defines the velocity to affect to the specified gradient
  64300. * @returns the current particle system
  64301. */
  64302. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  64303. if (!this._velocityGradients) {
  64304. this._velocityGradients = [];
  64305. }
  64306. this._addFactorGradient(this._velocityGradients, gradient, factor);
  64307. if (this._velocityGradientsTexture) {
  64308. this._velocityGradientsTexture.dispose();
  64309. this._velocityGradientsTexture = null;
  64310. }
  64311. this._releaseBuffers();
  64312. return this;
  64313. };
  64314. /**
  64315. * Remove a specific velocity gradient
  64316. * @param gradient defines the gradient to remove
  64317. * @returns the current particle system
  64318. */
  64319. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  64320. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  64321. this._velocityGradientsTexture = null;
  64322. return this;
  64323. };
  64324. /**
  64325. * Adds a new limit velocity gradient
  64326. * @param gradient defines the gradient to use (between 0 and 1)
  64327. * @param factor defines the limit velocity value to affect to the specified gradient
  64328. * @returns the current particle system
  64329. */
  64330. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  64331. if (!this._limitVelocityGradients) {
  64332. this._limitVelocityGradients = [];
  64333. }
  64334. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  64335. if (this._limitVelocityGradientsTexture) {
  64336. this._limitVelocityGradientsTexture.dispose();
  64337. this._limitVelocityGradientsTexture = null;
  64338. }
  64339. this._releaseBuffers();
  64340. return this;
  64341. };
  64342. /**
  64343. * Remove a specific limit velocity gradient
  64344. * @param gradient defines the gradient to remove
  64345. * @returns the current particle system
  64346. */
  64347. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  64348. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  64349. this._limitVelocityGradientsTexture = null;
  64350. return this;
  64351. };
  64352. /**
  64353. * Adds a new drag gradient
  64354. * @param gradient defines the gradient to use (between 0 and 1)
  64355. * @param factor defines the drag value to affect to the specified gradient
  64356. * @returns the current particle system
  64357. */
  64358. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  64359. if (!this._dragGradients) {
  64360. this._dragGradients = [];
  64361. }
  64362. this._addFactorGradient(this._dragGradients, gradient, factor);
  64363. if (this._dragGradientsTexture) {
  64364. this._dragGradientsTexture.dispose();
  64365. this._dragGradientsTexture = null;
  64366. }
  64367. this._releaseBuffers();
  64368. return this;
  64369. };
  64370. /**
  64371. * Remove a specific drag gradient
  64372. * @param gradient defines the gradient to remove
  64373. * @returns the current particle system
  64374. */
  64375. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  64376. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  64377. this._dragGradientsTexture = null;
  64378. return this;
  64379. };
  64380. /**
  64381. * Not supported by GPUParticleSystem
  64382. * @param gradient defines the gradient to use (between 0 and 1)
  64383. * @param factor defines the emit rate value to affect to the specified gradient
  64384. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64385. * @returns the current particle system
  64386. */
  64387. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  64388. // Do nothing as emit rate is not supported by GPUParticleSystem
  64389. return this;
  64390. };
  64391. /**
  64392. * Not supported by GPUParticleSystem
  64393. * @param gradient defines the gradient to remove
  64394. * @returns the current particle system
  64395. */
  64396. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  64397. // Do nothing as emit rate is not supported by GPUParticleSystem
  64398. return this;
  64399. };
  64400. /**
  64401. * Not supported by GPUParticleSystem
  64402. * @param gradient defines the gradient to use (between 0 and 1)
  64403. * @param factor defines the start size value to affect to the specified gradient
  64404. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64405. * @returns the current particle system
  64406. */
  64407. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  64408. // Do nothing as start size is not supported by GPUParticleSystem
  64409. return this;
  64410. };
  64411. /**
  64412. * Not supported by GPUParticleSystem
  64413. * @param gradient defines the gradient to remove
  64414. * @returns the current particle system
  64415. */
  64416. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  64417. // Do nothing as start size is not supported by GPUParticleSystem
  64418. return this;
  64419. };
  64420. /**
  64421. * Not supported by GPUParticleSystem
  64422. * @param gradient defines the gradient to use (between 0 and 1)
  64423. * @param min defines the color remap minimal range
  64424. * @param max defines the color remap maximal range
  64425. * @returns the current particle system
  64426. */
  64427. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  64428. // Do nothing as start size is not supported by GPUParticleSystem
  64429. return this;
  64430. };
  64431. /**
  64432. * Not supported by GPUParticleSystem
  64433. * @param gradient defines the gradient to remove
  64434. * @returns the current particle system
  64435. */
  64436. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  64437. // Do nothing as start size is not supported by GPUParticleSystem
  64438. return this;
  64439. };
  64440. /**
  64441. * Not supported by GPUParticleSystem
  64442. * @param gradient defines the gradient to use (between 0 and 1)
  64443. * @param min defines the alpha remap minimal range
  64444. * @param max defines the alpha remap maximal range
  64445. * @returns the current particle system
  64446. */
  64447. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  64448. // Do nothing as start size is not supported by GPUParticleSystem
  64449. return this;
  64450. };
  64451. /**
  64452. * Not supported by GPUParticleSystem
  64453. * @param gradient defines the gradient to remove
  64454. * @returns the current particle system
  64455. */
  64456. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  64457. // Do nothing as start size is not supported by GPUParticleSystem
  64458. return this;
  64459. };
  64460. /**
  64461. * Not supported by GPUParticleSystem
  64462. * @param gradient defines the gradient to use (between 0 and 1)
  64463. * @param color defines the color to affect to the specified gradient
  64464. * @returns the current particle system
  64465. */
  64466. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  64467. //Not supported by GPUParticleSystem
  64468. return this;
  64469. };
  64470. /**
  64471. * Not supported by GPUParticleSystem
  64472. * @param gradient defines the gradient to remove
  64473. * @returns the current particle system
  64474. */
  64475. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  64476. //Not supported by GPUParticleSystem
  64477. return this;
  64478. };
  64479. /**
  64480. * Not supported by GPUParticleSystem
  64481. * @returns the list of ramp gradients
  64482. */
  64483. GPUParticleSystem.prototype.getRampGradients = function () {
  64484. return null;
  64485. };
  64486. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  64487. /**
  64488. * Not supported by GPUParticleSystem
  64489. * Gets or sets a boolean indicating that ramp gradients must be used
  64490. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  64491. */
  64492. get: function () {
  64493. //Not supported by GPUParticleSystem
  64494. return false;
  64495. },
  64496. set: function (value) {
  64497. //Not supported by GPUParticleSystem
  64498. },
  64499. enumerable: true,
  64500. configurable: true
  64501. });
  64502. /**
  64503. * Not supported by GPUParticleSystem
  64504. * @param gradient defines the gradient to use (between 0 and 1)
  64505. * @param factor defines the life time factor to affect to the specified gradient
  64506. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64507. * @returns the current particle system
  64508. */
  64509. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  64510. //Not supported by GPUParticleSystem
  64511. return this;
  64512. };
  64513. /**
  64514. * Not supported by GPUParticleSystem
  64515. * @param gradient defines the gradient to remove
  64516. * @returns the current particle system
  64517. */
  64518. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  64519. //Not supported by GPUParticleSystem
  64520. return this;
  64521. };
  64522. GPUParticleSystem.prototype._reset = function () {
  64523. this._releaseBuffers();
  64524. };
  64525. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  64526. var updateVertexBuffers = {};
  64527. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  64528. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  64529. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  64530. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  64531. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  64532. var offset = 12;
  64533. if (!this._colorGradientsTexture) {
  64534. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  64535. offset += 4;
  64536. }
  64537. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  64538. offset += 3;
  64539. if (!this._isBillboardBased) {
  64540. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  64541. offset += 3;
  64542. }
  64543. if (this._angularSpeedGradientsTexture) {
  64544. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  64545. offset += 1;
  64546. }
  64547. else {
  64548. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  64549. offset += 2;
  64550. }
  64551. if (this._isAnimationSheetEnabled) {
  64552. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  64553. offset += 1;
  64554. if (this.spriteRandomStartCell) {
  64555. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  64556. offset += 1;
  64557. }
  64558. }
  64559. if (this.noiseTexture) {
  64560. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  64561. offset += 3;
  64562. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  64563. offset += 3;
  64564. }
  64565. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  64566. this._engine.bindArrayBuffer(null);
  64567. return vao;
  64568. };
  64569. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  64570. var renderVertexBuffers = {};
  64571. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  64572. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  64573. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  64574. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  64575. var offset = 12;
  64576. if (!this._colorGradientsTexture) {
  64577. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  64578. offset += 4;
  64579. }
  64580. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  64581. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  64582. }
  64583. offset += 3; // Direction
  64584. if (!this._isBillboardBased) {
  64585. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  64586. offset += 3;
  64587. }
  64588. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  64589. if (this._angularSpeedGradientsTexture) {
  64590. offset++;
  64591. }
  64592. else {
  64593. offset += 2;
  64594. }
  64595. if (this._isAnimationSheetEnabled) {
  64596. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  64597. offset += 1;
  64598. if (this.spriteRandomStartCell) {
  64599. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  64600. offset += 1;
  64601. }
  64602. }
  64603. if (this.noiseTexture) {
  64604. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  64605. offset += 3;
  64606. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  64607. offset += 3;
  64608. }
  64609. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  64610. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  64611. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  64612. this._engine.bindArrayBuffer(null);
  64613. return vao;
  64614. };
  64615. GPUParticleSystem.prototype._initialize = function (force) {
  64616. if (force === void 0) { force = false; }
  64617. if (this._buffer0 && !force) {
  64618. return;
  64619. }
  64620. var engine = this._scene.getEngine();
  64621. var data = new Array();
  64622. if (!this.isBillboardBased) {
  64623. this._attributesStrideSize += 3;
  64624. }
  64625. if (this._colorGradientsTexture) {
  64626. this._attributesStrideSize -= 4;
  64627. }
  64628. if (this._angularSpeedGradientsTexture) {
  64629. this._attributesStrideSize -= 1;
  64630. }
  64631. if (this._isAnimationSheetEnabled) {
  64632. this._attributesStrideSize += 1;
  64633. if (this.spriteRandomStartCell) {
  64634. this._attributesStrideSize += 1;
  64635. }
  64636. }
  64637. if (this.noiseTexture) {
  64638. this._attributesStrideSize += 6;
  64639. }
  64640. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  64641. // position
  64642. data.push(0.0);
  64643. data.push(0.0);
  64644. data.push(0.0);
  64645. // Age and life
  64646. data.push(0.0); // create the particle as a dead one to create a new one at start
  64647. data.push(0.0);
  64648. // Seed
  64649. data.push(Math.random());
  64650. data.push(Math.random());
  64651. data.push(Math.random());
  64652. data.push(Math.random());
  64653. // Size
  64654. data.push(0.0);
  64655. data.push(0.0);
  64656. data.push(0.0);
  64657. if (!this._colorGradientsTexture) {
  64658. // color
  64659. data.push(0.0);
  64660. data.push(0.0);
  64661. data.push(0.0);
  64662. data.push(0.0);
  64663. }
  64664. // direction
  64665. data.push(0.0);
  64666. data.push(0.0);
  64667. data.push(0.0);
  64668. if (!this.isBillboardBased) {
  64669. // initialDirection
  64670. data.push(0.0);
  64671. data.push(0.0);
  64672. data.push(0.0);
  64673. }
  64674. // angle
  64675. data.push(0.0);
  64676. if (!this._angularSpeedGradientsTexture) {
  64677. data.push(0.0);
  64678. }
  64679. if (this._isAnimationSheetEnabled) {
  64680. data.push(0.0);
  64681. if (this.spriteRandomStartCell) {
  64682. data.push(0.0);
  64683. }
  64684. }
  64685. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64686. data.push(Math.random());
  64687. data.push(Math.random());
  64688. data.push(Math.random());
  64689. data.push(Math.random());
  64690. data.push(Math.random());
  64691. data.push(Math.random());
  64692. }
  64693. }
  64694. // Sprite data
  64695. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64696. -0.5, 0.5, 0, 1,
  64697. -0.5, -0.5, 0, 0,
  64698. 0.5, -0.5, 1, 0]);
  64699. // Buffers
  64700. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64701. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64702. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64703. // Update VAO
  64704. this._updateVAO = [];
  64705. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64706. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64707. // Render VAO
  64708. this._renderVAO = [];
  64709. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  64710. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  64711. // Links
  64712. this._sourceBuffer = this._buffer0;
  64713. this._targetBuffer = this._buffer1;
  64714. };
  64715. /** @hidden */
  64716. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  64717. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  64718. if (this._isBillboardBased) {
  64719. defines += "\n#define BILLBOARD";
  64720. }
  64721. if (this._colorGradientsTexture) {
  64722. defines += "\n#define COLORGRADIENTS";
  64723. }
  64724. if (this._sizeGradientsTexture) {
  64725. defines += "\n#define SIZEGRADIENTS";
  64726. }
  64727. if (this._angularSpeedGradientsTexture) {
  64728. defines += "\n#define ANGULARSPEEDGRADIENTS";
  64729. }
  64730. if (this._velocityGradientsTexture) {
  64731. defines += "\n#define VELOCITYGRADIENTS";
  64732. }
  64733. if (this._limitVelocityGradientsTexture) {
  64734. defines += "\n#define LIMITVELOCITYGRADIENTS";
  64735. }
  64736. if (this._dragGradientsTexture) {
  64737. defines += "\n#define DRAGGRADIENTS";
  64738. }
  64739. if (this.isAnimationSheetEnabled) {
  64740. defines += "\n#define ANIMATESHEET";
  64741. if (this.spriteRandomStartCell) {
  64742. defines += "\n#define ANIMATESHEETRANDOMSTART";
  64743. }
  64744. }
  64745. if (this.noiseTexture) {
  64746. defines += "\n#define NOISE";
  64747. }
  64748. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  64749. return;
  64750. }
  64751. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  64752. if (!this._colorGradientsTexture) {
  64753. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  64754. }
  64755. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  64756. if (!this._isBillboardBased) {
  64757. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  64758. }
  64759. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  64760. if (this.isAnimationSheetEnabled) {
  64761. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  64762. if (this.spriteRandomStartCell) {
  64763. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  64764. }
  64765. }
  64766. if (this.noiseTexture) {
  64767. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  64768. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  64769. }
  64770. this._updateEffectOptions.defines = defines;
  64771. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  64772. };
  64773. /** @hidden */
  64774. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  64775. var defines = "";
  64776. if (this._scene.clipPlane) {
  64777. defines = "\n#define CLIPPLANE";
  64778. }
  64779. if (this._scene.clipPlane2) {
  64780. defines = "\n#define CLIPPLANE2";
  64781. }
  64782. if (this._scene.clipPlane3) {
  64783. defines = "\n#define CLIPPLANE3";
  64784. }
  64785. if (this._scene.clipPlane4) {
  64786. defines = "\n#define CLIPPLANE4";
  64787. }
  64788. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  64789. defines = "\n#define BLENDMULTIPLYMODE";
  64790. }
  64791. if (this._isBillboardBased) {
  64792. defines += "\n#define BILLBOARD";
  64793. switch (this.billboardMode) {
  64794. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  64795. defines += "\n#define BILLBOARDY";
  64796. break;
  64797. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  64798. defines += "\n#define BILLBOARDSTRETCHED";
  64799. break;
  64800. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  64801. default:
  64802. break;
  64803. }
  64804. }
  64805. if (this._colorGradientsTexture) {
  64806. defines += "\n#define COLORGRADIENTS";
  64807. }
  64808. if (this.isAnimationSheetEnabled) {
  64809. defines += "\n#define ANIMATESHEET";
  64810. }
  64811. if (this._imageProcessingConfiguration) {
  64812. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  64813. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  64814. }
  64815. if (this._renderEffect && this._renderEffect.defines === defines) {
  64816. return;
  64817. }
  64818. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  64819. var samplers = ["textureSampler", "colorGradientSampler"];
  64820. if (BABYLON.ImageProcessingConfiguration) {
  64821. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  64822. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  64823. }
  64824. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  64825. };
  64826. /**
  64827. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  64828. * @param preWarm defines if we are in the pre-warmimg phase
  64829. */
  64830. GPUParticleSystem.prototype.animate = function (preWarm) {
  64831. if (preWarm === void 0) { preWarm = false; }
  64832. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  64833. this._actualFrame += this._timeDelta;
  64834. if (!this._stopped) {
  64835. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  64836. this.stop();
  64837. }
  64838. }
  64839. };
  64840. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  64841. var texture = this[textureName];
  64842. if (!factorGradients || !factorGradients.length || texture) {
  64843. return;
  64844. }
  64845. var data = new Float32Array(this._rawTextureWidth);
  64846. for (var x = 0; x < this._rawTextureWidth; x++) {
  64847. var ratio = x / this._rawTextureWidth;
  64848. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  64849. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  64850. });
  64851. }
  64852. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64853. };
  64854. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  64855. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  64856. };
  64857. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  64858. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  64859. };
  64860. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  64861. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  64862. };
  64863. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  64864. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  64865. };
  64866. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  64867. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  64868. };
  64869. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  64870. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  64871. return;
  64872. }
  64873. var data = new Uint8Array(this._rawTextureWidth * 4);
  64874. var tmpColor = BABYLON.Tmp.Color4[0];
  64875. for (var x = 0; x < this._rawTextureWidth; x++) {
  64876. var ratio = x / this._rawTextureWidth;
  64877. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  64878. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  64879. data[x * 4] = tmpColor.r * 255;
  64880. data[x * 4 + 1] = tmpColor.g * 255;
  64881. data[x * 4 + 2] = tmpColor.b * 255;
  64882. data[x * 4 + 3] = tmpColor.a * 255;
  64883. });
  64884. }
  64885. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64886. };
  64887. /**
  64888. * Renders the particle system in its current state
  64889. * @param preWarm defines if the system should only update the particles but not render them
  64890. * @returns the current number of particles
  64891. */
  64892. GPUParticleSystem.prototype.render = function (preWarm) {
  64893. if (preWarm === void 0) { preWarm = false; }
  64894. if (!this._started) {
  64895. return 0;
  64896. }
  64897. this._createColorGradientTexture();
  64898. this._createSizeGradientTexture();
  64899. this._createAngularSpeedGradientTexture();
  64900. this._createVelocityGradientTexture();
  64901. this._createLimitVelocityGradientTexture();
  64902. this._createDragGradientTexture();
  64903. this._recreateUpdateEffect();
  64904. this._recreateRenderEffect();
  64905. if (!this.isReady()) {
  64906. return 0;
  64907. }
  64908. if (!preWarm) {
  64909. if (!this._preWarmDone && this.preWarmCycles) {
  64910. for (var index = 0; index < this.preWarmCycles; index++) {
  64911. this.animate(true);
  64912. this.render(true);
  64913. }
  64914. this._preWarmDone = true;
  64915. }
  64916. if (this._currentRenderId === this._scene.getRenderId()) {
  64917. return 0;
  64918. }
  64919. this._currentRenderId = this._scene.getRenderId();
  64920. }
  64921. // Get everything ready to render
  64922. this._initialize();
  64923. this._accumulatedCount += this.emitRate * this._timeDelta;
  64924. if (this._accumulatedCount > 1) {
  64925. var intPart = this._accumulatedCount | 0;
  64926. this._accumulatedCount -= intPart;
  64927. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64928. }
  64929. if (!this._currentActiveCount) {
  64930. return 0;
  64931. }
  64932. // Enable update effect
  64933. this._engine.enableEffect(this._updateEffect);
  64934. this._engine.setState(false);
  64935. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64936. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64937. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64938. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64939. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64940. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64941. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64942. if (!this._colorGradientsTexture) {
  64943. this._updateEffect.setDirectColor4("color1", this.color1);
  64944. this._updateEffect.setDirectColor4("color2", this.color2);
  64945. }
  64946. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64947. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64948. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64949. this._updateEffect.setVector3("gravity", this.gravity);
  64950. if (this._sizeGradientsTexture) {
  64951. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64952. }
  64953. if (this._angularSpeedGradientsTexture) {
  64954. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64955. }
  64956. if (this._velocityGradientsTexture) {
  64957. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64958. }
  64959. if (this._limitVelocityGradientsTexture) {
  64960. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64961. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64962. }
  64963. if (this._dragGradientsTexture) {
  64964. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64965. }
  64966. if (this.particleEmitterType) {
  64967. this.particleEmitterType.applyToShader(this._updateEffect);
  64968. }
  64969. if (this._isAnimationSheetEnabled) {
  64970. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64971. }
  64972. if (this.noiseTexture) {
  64973. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  64974. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  64975. }
  64976. var emitterWM;
  64977. if (this.emitter.position) {
  64978. var emitterMesh = this.emitter;
  64979. emitterWM = emitterMesh.getWorldMatrix();
  64980. }
  64981. else {
  64982. var emitterPosition = this.emitter;
  64983. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  64984. }
  64985. this._updateEffect.setMatrix("emitterWM", emitterWM);
  64986. // Bind source VAO
  64987. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  64988. // Update
  64989. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  64990. this._engine.setRasterizerState(false);
  64991. this._engine.beginTransformFeedback(true);
  64992. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  64993. this._engine.endTransformFeedback();
  64994. this._engine.setRasterizerState(true);
  64995. this._engine.bindTransformFeedbackBuffer(null);
  64996. if (!preWarm) {
  64997. // Enable render effect
  64998. this._engine.enableEffect(this._renderEffect);
  64999. var viewMatrix = this._scene.getViewMatrix();
  65000. this._renderEffect.setMatrix("view", viewMatrix);
  65001. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65002. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65003. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65004. if (this._colorGradientsTexture) {
  65005. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65006. }
  65007. else {
  65008. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65009. }
  65010. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65011. var baseSize = this.particleTexture.getBaseSize();
  65012. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65013. }
  65014. if (this._isBillboardBased) {
  65015. var camera = this._scene.activeCamera;
  65016. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65017. }
  65018. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65019. var invView = viewMatrix.clone();
  65020. invView.invert();
  65021. this._renderEffect.setMatrix("invView", invView);
  65022. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65023. }
  65024. // image processing
  65025. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65026. this._imageProcessingConfiguration.bind(this._renderEffect);
  65027. }
  65028. // Draw order
  65029. switch (this.blendMode) {
  65030. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65031. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65032. break;
  65033. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65034. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  65035. break;
  65036. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  65037. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65038. break;
  65039. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  65040. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  65041. break;
  65042. }
  65043. if (this.forceDepthWrite) {
  65044. this._engine.setDepthWrite(true);
  65045. }
  65046. // Bind source VAO
  65047. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  65048. // Render
  65049. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  65050. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65051. }
  65052. // Switch VAOs
  65053. this._targetIndex++;
  65054. if (this._targetIndex === 2) {
  65055. this._targetIndex = 0;
  65056. }
  65057. // Switch buffers
  65058. var tmpBuffer = this._sourceBuffer;
  65059. this._sourceBuffer = this._targetBuffer;
  65060. this._targetBuffer = tmpBuffer;
  65061. return this._currentActiveCount;
  65062. };
  65063. /**
  65064. * Rebuilds the particle system
  65065. */
  65066. GPUParticleSystem.prototype.rebuild = function () {
  65067. this._initialize(true);
  65068. };
  65069. GPUParticleSystem.prototype._releaseBuffers = function () {
  65070. if (this._buffer0) {
  65071. this._buffer0.dispose();
  65072. this._buffer0 = null;
  65073. }
  65074. if (this._buffer1) {
  65075. this._buffer1.dispose();
  65076. this._buffer1 = null;
  65077. }
  65078. if (this._spriteBuffer) {
  65079. this._spriteBuffer.dispose();
  65080. this._spriteBuffer = null;
  65081. }
  65082. };
  65083. GPUParticleSystem.prototype._releaseVAOs = function () {
  65084. if (!this._updateVAO) {
  65085. return;
  65086. }
  65087. for (var index = 0; index < this._updateVAO.length; index++) {
  65088. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  65089. }
  65090. this._updateVAO = [];
  65091. for (var index = 0; index < this._renderVAO.length; index++) {
  65092. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  65093. }
  65094. this._renderVAO = [];
  65095. };
  65096. /**
  65097. * Disposes the particle system and free the associated resources
  65098. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  65099. */
  65100. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  65101. if (disposeTexture === void 0) { disposeTexture = true; }
  65102. var index = this._scene.particleSystems.indexOf(this);
  65103. if (index > -1) {
  65104. this._scene.particleSystems.splice(index, 1);
  65105. }
  65106. this._releaseBuffers();
  65107. this._releaseVAOs();
  65108. if (this._colorGradientsTexture) {
  65109. this._colorGradientsTexture.dispose();
  65110. this._colorGradientsTexture = null;
  65111. }
  65112. if (this._sizeGradientsTexture) {
  65113. this._sizeGradientsTexture.dispose();
  65114. this._sizeGradientsTexture = null;
  65115. }
  65116. if (this._angularSpeedGradientsTexture) {
  65117. this._angularSpeedGradientsTexture.dispose();
  65118. this._angularSpeedGradientsTexture = null;
  65119. }
  65120. if (this._velocityGradientsTexture) {
  65121. this._velocityGradientsTexture.dispose();
  65122. this._velocityGradientsTexture = null;
  65123. }
  65124. if (this._limitVelocityGradientsTexture) {
  65125. this._limitVelocityGradientsTexture.dispose();
  65126. this._limitVelocityGradientsTexture = null;
  65127. }
  65128. if (this._dragGradientsTexture) {
  65129. this._dragGradientsTexture.dispose();
  65130. this._dragGradientsTexture = null;
  65131. }
  65132. if (this._randomTexture) {
  65133. this._randomTexture.dispose();
  65134. this._randomTexture = null;
  65135. }
  65136. if (this._randomTexture2) {
  65137. this._randomTexture2.dispose();
  65138. this._randomTexture2 = null;
  65139. }
  65140. if (disposeTexture && this.particleTexture) {
  65141. this.particleTexture.dispose();
  65142. this.particleTexture = null;
  65143. }
  65144. if (disposeTexture && this.noiseTexture) {
  65145. this.noiseTexture.dispose();
  65146. this.noiseTexture = null;
  65147. }
  65148. // Callback
  65149. this.onDisposeObservable.notifyObservers(this);
  65150. this.onDisposeObservable.clear();
  65151. };
  65152. /**
  65153. * Clones the particle system.
  65154. * @param name The name of the cloned object
  65155. * @param newEmitter The new emitter to use
  65156. * @returns the cloned particle system
  65157. */
  65158. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  65159. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  65160. BABYLON.Tools.DeepCopy(this, result);
  65161. if (newEmitter === undefined) {
  65162. newEmitter = this.emitter;
  65163. }
  65164. result.emitter = newEmitter;
  65165. if (this.particleTexture) {
  65166. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  65167. }
  65168. return result;
  65169. };
  65170. /**
  65171. * Serializes the particle system to a JSON object.
  65172. * @returns the JSON object
  65173. */
  65174. GPUParticleSystem.prototype.serialize = function () {
  65175. var serializationObject = {};
  65176. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  65177. serializationObject.activeParticleCount = this.activeParticleCount;
  65178. return serializationObject;
  65179. };
  65180. /**
  65181. * Parses a JSON object to create a GPU particle system.
  65182. * @param parsedParticleSystem The JSON object to parse
  65183. * @param scene The scene to create the particle system in
  65184. * @param rootUrl The root url to use to load external dependencies like texture
  65185. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  65186. * @returns the parsed GPU particle system
  65187. */
  65188. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  65189. if (doNotStart === void 0) { doNotStart = false; }
  65190. var name = parsedParticleSystem.name;
  65191. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  65192. if (parsedParticleSystem.activeParticleCount) {
  65193. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  65194. }
  65195. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  65196. // Auto start
  65197. if (parsedParticleSystem.preventAutoStart) {
  65198. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  65199. }
  65200. if (!doNotStart && !particleSystem.preventAutoStart) {
  65201. particleSystem.start();
  65202. }
  65203. return particleSystem;
  65204. };
  65205. return GPUParticleSystem;
  65206. }(BABYLON.BaseParticleSystem));
  65207. BABYLON.GPUParticleSystem = GPUParticleSystem;
  65208. })(BABYLON || (BABYLON = {}));
  65209. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  65210. var BABYLON;
  65211. (function (BABYLON) {
  65212. /**
  65213. * Represents one particle of a solid particle system.
  65214. */
  65215. var SolidParticle = /** @class */ (function () {
  65216. /**
  65217. * Creates a Solid Particle object.
  65218. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  65219. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  65220. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  65221. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  65222. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  65223. * @param shapeId (integer) is the model shape identifier in the SPS.
  65224. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  65225. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  65226. */
  65227. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  65228. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  65229. /**
  65230. * particle global index
  65231. */
  65232. this.idx = 0;
  65233. /**
  65234. * The color of the particle
  65235. */
  65236. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65237. /**
  65238. * The world space position of the particle.
  65239. */
  65240. this.position = BABYLON.Vector3.Zero();
  65241. /**
  65242. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  65243. */
  65244. this.rotation = BABYLON.Vector3.Zero();
  65245. /**
  65246. * The scaling of the particle.
  65247. */
  65248. this.scaling = BABYLON.Vector3.One();
  65249. /**
  65250. * The uvs of the particle.
  65251. */
  65252. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  65253. /**
  65254. * The current speed of the particle.
  65255. */
  65256. this.velocity = BABYLON.Vector3.Zero();
  65257. /**
  65258. * The pivot point in the particle local space.
  65259. */
  65260. this.pivot = BABYLON.Vector3.Zero();
  65261. /**
  65262. * Must the particle be translated from its pivot point in its local space ?
  65263. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  65264. * Default : false
  65265. */
  65266. this.translateFromPivot = false;
  65267. /**
  65268. * Is the particle active or not ?
  65269. */
  65270. this.alive = true;
  65271. /**
  65272. * Is the particle visible or not ?
  65273. */
  65274. this.isVisible = true;
  65275. /**
  65276. * Index of this particle in the global "positions" array (Internal use)
  65277. * @hidden
  65278. */
  65279. this._pos = 0;
  65280. /**
  65281. * @hidden Index of this particle in the global "indices" array (Internal use)
  65282. */
  65283. this._ind = 0;
  65284. /**
  65285. * ModelShape id of this particle
  65286. */
  65287. this.shapeId = 0;
  65288. /**
  65289. * Index of the particle in its shape id (Internal use)
  65290. */
  65291. this.idxInShape = 0;
  65292. /**
  65293. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  65294. */
  65295. this._stillInvisible = false;
  65296. /**
  65297. * @hidden Last computed particle rotation matrix
  65298. */
  65299. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  65300. /**
  65301. * Parent particle Id, if any.
  65302. * Default null.
  65303. */
  65304. this.parentId = null;
  65305. /**
  65306. * @hidden Internal global position in the SPS.
  65307. */
  65308. this._globalPosition = BABYLON.Vector3.Zero();
  65309. this.idx = particleIndex;
  65310. this._pos = positionIndex;
  65311. this._ind = indiceIndex;
  65312. this._model = model;
  65313. this.shapeId = shapeId;
  65314. this.idxInShape = idxInShape;
  65315. this._sps = sps;
  65316. if (modelBoundingInfo) {
  65317. this._modelBoundingInfo = modelBoundingInfo;
  65318. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  65319. }
  65320. }
  65321. Object.defineProperty(SolidParticle.prototype, "scale", {
  65322. /**
  65323. * Legacy support, changed scale to scaling
  65324. */
  65325. get: function () {
  65326. return this.scaling;
  65327. },
  65328. /**
  65329. * Legacy support, changed scale to scaling
  65330. */
  65331. set: function (scale) {
  65332. this.scaling = scale;
  65333. },
  65334. enumerable: true,
  65335. configurable: true
  65336. });
  65337. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  65338. /**
  65339. * Legacy support, changed quaternion to rotationQuaternion
  65340. */
  65341. get: function () {
  65342. return this.rotationQuaternion;
  65343. },
  65344. /**
  65345. * Legacy support, changed quaternion to rotationQuaternion
  65346. */
  65347. set: function (q) {
  65348. this.rotationQuaternion = q;
  65349. },
  65350. enumerable: true,
  65351. configurable: true
  65352. });
  65353. /**
  65354. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  65355. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  65356. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  65357. * @returns true if it intersects
  65358. */
  65359. SolidParticle.prototype.intersectsMesh = function (target) {
  65360. if (!this._boundingInfo || !target._boundingInfo) {
  65361. return false;
  65362. }
  65363. if (this._sps._bSphereOnly) {
  65364. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  65365. }
  65366. return this._boundingInfo.intersects(target._boundingInfo, false);
  65367. };
  65368. return SolidParticle;
  65369. }());
  65370. BABYLON.SolidParticle = SolidParticle;
  65371. /**
  65372. * Represents the shape of the model used by one particle of a solid particle system.
  65373. * SPS internal tool, don't use it manually.
  65374. */
  65375. var ModelShape = /** @class */ (function () {
  65376. /**
  65377. * 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.
  65378. * SPS internal tool, don't use it manually.
  65379. * @hidden
  65380. */
  65381. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  65382. /**
  65383. * length of the shape in the model indices array (internal use)
  65384. * @hidden
  65385. */
  65386. this._indicesLength = 0;
  65387. this.shapeID = id;
  65388. this._shape = shape;
  65389. this._indicesLength = indicesLength;
  65390. this._shapeUV = shapeUV;
  65391. this._positionFunction = posFunction;
  65392. this._vertexFunction = vtxFunction;
  65393. }
  65394. return ModelShape;
  65395. }());
  65396. BABYLON.ModelShape = ModelShape;
  65397. /**
  65398. * Represents a Depth Sorted Particle in the solid particle system.
  65399. */
  65400. var DepthSortedParticle = /** @class */ (function () {
  65401. function DepthSortedParticle() {
  65402. /**
  65403. * Index of the particle in the "indices" array
  65404. */
  65405. this.ind = 0;
  65406. /**
  65407. * Length of the particle shape in the "indices" array
  65408. */
  65409. this.indicesLength = 0;
  65410. /**
  65411. * Squared distance from the particle to the camera
  65412. */
  65413. this.sqDistance = 0.0;
  65414. }
  65415. return DepthSortedParticle;
  65416. }());
  65417. BABYLON.DepthSortedParticle = DepthSortedParticle;
  65418. })(BABYLON || (BABYLON = {}));
  65419. //# sourceMappingURL=babylon.solidParticle.js.map
  65420. var BABYLON;
  65421. (function (BABYLON) {
  65422. /**
  65423. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  65424. *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.
  65425. * The SPS is also a particle system. It provides some methods to manage the particles.
  65426. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  65427. *
  65428. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  65429. */
  65430. var SolidParticleSystem = /** @class */ (function () {
  65431. /**
  65432. * Creates a SPS (Solid Particle System) object.
  65433. * @param name (String) is the SPS name, this will be the underlying mesh name.
  65434. * @param scene (Scene) is the scene in which the SPS is added.
  65435. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  65436. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  65437. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  65438. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  65439. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  65440. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  65441. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  65442. */
  65443. function SolidParticleSystem(name, scene, options) {
  65444. /**
  65445. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  65446. * Example : var p = SPS.particles[i];
  65447. */
  65448. this.particles = new Array();
  65449. /**
  65450. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  65451. */
  65452. this.nbParticles = 0;
  65453. /**
  65454. * If the particles must ever face the camera (default false). Useful for planar particles.
  65455. */
  65456. this.billboard = false;
  65457. /**
  65458. * Recompute normals when adding a shape
  65459. */
  65460. this.recomputeNormals = true;
  65461. /**
  65462. * This a counter ofr your own usage. It's not set by any SPS functions.
  65463. */
  65464. this.counter = 0;
  65465. /**
  65466. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  65467. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  65468. */
  65469. this.vars = {};
  65470. /**
  65471. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  65472. * @hidden
  65473. */
  65474. this._bSphereOnly = false;
  65475. /**
  65476. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  65477. * @hidden
  65478. */
  65479. this._bSphereRadiusFactor = 1.0;
  65480. this._positions = new Array();
  65481. this._indices = new Array();
  65482. this._normals = new Array();
  65483. this._colors = new Array();
  65484. this._uvs = new Array();
  65485. this._index = 0; // indices index
  65486. this._updatable = true;
  65487. this._pickable = false;
  65488. this._isVisibilityBoxLocked = false;
  65489. this._alwaysVisible = false;
  65490. this._depthSort = false;
  65491. this._shapeCounter = 0;
  65492. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  65493. this._color = new BABYLON.Color4(0, 0, 0, 0);
  65494. this._computeParticleColor = true;
  65495. this._computeParticleTexture = true;
  65496. this._computeParticleRotation = true;
  65497. this._computeParticleVertex = false;
  65498. this._computeBoundingBox = false;
  65499. this._depthSortParticles = true;
  65500. this._cam_axisZ = BABYLON.Vector3.Zero();
  65501. this._cam_axisY = BABYLON.Vector3.Zero();
  65502. this._cam_axisX = BABYLON.Vector3.Zero();
  65503. this._axisZ = BABYLON.Axis.Z;
  65504. this._camDir = BABYLON.Vector3.Zero();
  65505. this._camInvertedPosition = BABYLON.Vector3.Zero();
  65506. this._rotMatrix = new BABYLON.Matrix();
  65507. this._invertMatrix = new BABYLON.Matrix();
  65508. this._rotated = BABYLON.Vector3.Zero();
  65509. this._quaternion = new BABYLON.Quaternion();
  65510. this._vertex = BABYLON.Vector3.Zero();
  65511. this._normal = BABYLON.Vector3.Zero();
  65512. this._yaw = 0.0;
  65513. this._pitch = 0.0;
  65514. this._roll = 0.0;
  65515. this._halfroll = 0.0;
  65516. this._halfpitch = 0.0;
  65517. this._halfyaw = 0.0;
  65518. this._sinRoll = 0.0;
  65519. this._cosRoll = 0.0;
  65520. this._sinPitch = 0.0;
  65521. this._cosPitch = 0.0;
  65522. this._sinYaw = 0.0;
  65523. this._cosYaw = 0.0;
  65524. this._mustUnrotateFixedNormals = false;
  65525. this._minimum = BABYLON.Vector3.Zero();
  65526. this._maximum = BABYLON.Vector3.Zero();
  65527. this._minBbox = BABYLON.Vector3.Zero();
  65528. this._maxBbox = BABYLON.Vector3.Zero();
  65529. this._particlesIntersect = false;
  65530. this._depthSortFunction = function (p1, p2) {
  65531. return (p2.sqDistance - p1.sqDistance);
  65532. };
  65533. this._needs32Bits = false;
  65534. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  65535. this._scaledPivot = BABYLON.Vector3.Zero();
  65536. this._particleHasParent = false;
  65537. this.name = name;
  65538. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65539. this._camera = scene.activeCamera;
  65540. this._pickable = options ? options.isPickable : false;
  65541. this._depthSort = options ? options.enableDepthSort : false;
  65542. this._particlesIntersect = options ? options.particleIntersection : false;
  65543. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  65544. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  65545. if (options && options.updatable !== undefined) {
  65546. this._updatable = options.updatable;
  65547. }
  65548. else {
  65549. this._updatable = true;
  65550. }
  65551. if (this._pickable) {
  65552. this.pickedParticles = [];
  65553. }
  65554. if (this._depthSort) {
  65555. this.depthSortedParticles = [];
  65556. }
  65557. }
  65558. /**
  65559. * Builds the SPS underlying mesh. Returns a standard Mesh.
  65560. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  65561. * @returns the created mesh
  65562. */
  65563. SolidParticleSystem.prototype.buildMesh = function () {
  65564. if (this.nbParticles === 0) {
  65565. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  65566. this.addShape(triangle, 1);
  65567. triangle.dispose();
  65568. }
  65569. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  65570. this._positions32 = new Float32Array(this._positions);
  65571. this._uvs32 = new Float32Array(this._uvs);
  65572. this._colors32 = new Float32Array(this._colors);
  65573. if (this.recomputeNormals) {
  65574. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  65575. }
  65576. this._normals32 = new Float32Array(this._normals);
  65577. this._fixedNormal32 = new Float32Array(this._normals);
  65578. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  65579. this._unrotateFixedNormals();
  65580. }
  65581. var vertexData = new BABYLON.VertexData();
  65582. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  65583. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  65584. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  65585. if (this._uvs32.length > 0) {
  65586. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  65587. }
  65588. if (this._colors32.length > 0) {
  65589. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  65590. }
  65591. var mesh = new BABYLON.Mesh(this.name, this._scene);
  65592. vertexData.applyToMesh(mesh, this._updatable);
  65593. this.mesh = mesh;
  65594. this.mesh.isPickable = this._pickable;
  65595. // free memory
  65596. if (!this._depthSort) {
  65597. this._indices = null;
  65598. }
  65599. this._positions = null;
  65600. this._normals = null;
  65601. this._uvs = null;
  65602. this._colors = null;
  65603. if (!this._updatable) {
  65604. this.particles.length = 0;
  65605. }
  65606. return mesh;
  65607. };
  65608. /**
  65609. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  65610. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  65611. * Thus the particles generated from `digest()` have their property `position` set yet.
  65612. * @param mesh ( Mesh ) is the mesh to be digested
  65613. * @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
  65614. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  65615. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  65616. * @returns the current SPS
  65617. */
  65618. SolidParticleSystem.prototype.digest = function (mesh, options) {
  65619. var size = (options && options.facetNb) || 1;
  65620. var number = (options && options.number) || 0;
  65621. var delta = (options && options.delta) || 0;
  65622. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65623. var meshInd = mesh.getIndices();
  65624. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65625. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65626. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65627. var f = 0; // facet counter
  65628. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  65629. // compute size from number
  65630. if (number) {
  65631. number = (number > totalFacets) ? totalFacets : number;
  65632. size = Math.round(totalFacets / number);
  65633. delta = 0;
  65634. }
  65635. else {
  65636. size = (size > totalFacets) ? totalFacets : size;
  65637. }
  65638. var facetPos = []; // submesh positions
  65639. var facetInd = []; // submesh indices
  65640. var facetUV = []; // submesh UV
  65641. var facetCol = []; // submesh colors
  65642. var barycenter = BABYLON.Vector3.Zero();
  65643. var sizeO = size;
  65644. while (f < totalFacets) {
  65645. size = sizeO + Math.floor((1 + delta) * Math.random());
  65646. if (f > totalFacets - size) {
  65647. size = totalFacets - f;
  65648. }
  65649. // reset temp arrays
  65650. facetPos.length = 0;
  65651. facetInd.length = 0;
  65652. facetUV.length = 0;
  65653. facetCol.length = 0;
  65654. // iterate over "size" facets
  65655. var fi = 0;
  65656. for (var j = f * 3; j < (f + size) * 3; j++) {
  65657. facetInd.push(fi);
  65658. var i = meshInd[j];
  65659. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65660. if (meshUV) {
  65661. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65662. }
  65663. if (meshCol) {
  65664. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65665. }
  65666. fi++;
  65667. }
  65668. // create a model shape for each single particle
  65669. var idx = this.nbParticles;
  65670. var shape = this._posToShape(facetPos);
  65671. var shapeUV = this._uvsToShapeUV(facetUV);
  65672. // compute the barycenter of the shape
  65673. var v;
  65674. for (v = 0; v < shape.length; v++) {
  65675. barycenter.addInPlace(shape[v]);
  65676. }
  65677. barycenter.scaleInPlace(1 / shape.length);
  65678. // shift the shape from its barycenter to the origin
  65679. for (v = 0; v < shape.length; v++) {
  65680. shape[v].subtractInPlace(barycenter);
  65681. }
  65682. var bInfo;
  65683. if (this._particlesIntersect) {
  65684. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65685. }
  65686. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65687. // add the particle in the SPS
  65688. var currentPos = this._positions.length;
  65689. var currentInd = this._indices.length;
  65690. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65691. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65692. // initialize the particle position
  65693. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65694. this._index += shape.length;
  65695. idx++;
  65696. this.nbParticles++;
  65697. this._shapeCounter++;
  65698. f += size;
  65699. }
  65700. return this;
  65701. };
  65702. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65703. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65704. var index = 0;
  65705. var idx = 0;
  65706. for (var p = 0; p < this.particles.length; p++) {
  65707. this._particle = this.particles[p];
  65708. this._shape = this._particle._model._shape;
  65709. if (this._particle.rotationQuaternion) {
  65710. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65711. }
  65712. else {
  65713. this._yaw = this._particle.rotation.y;
  65714. this._pitch = this._particle.rotation.x;
  65715. this._roll = this._particle.rotation.z;
  65716. this._quaternionRotationYPR();
  65717. }
  65718. this._quaternionToRotationMatrix();
  65719. this._rotMatrix.invertToRef(this._invertMatrix);
  65720. for (var pt = 0; pt < this._shape.length; pt++) {
  65721. idx = index + pt * 3;
  65722. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  65723. this._fixedNormal32[idx] = this._normal.x;
  65724. this._fixedNormal32[idx + 1] = this._normal.y;
  65725. this._fixedNormal32[idx + 2] = this._normal.z;
  65726. }
  65727. index = idx + 3;
  65728. }
  65729. };
  65730. //reset copy
  65731. SolidParticleSystem.prototype._resetCopy = function () {
  65732. this._copy.position.x = 0;
  65733. this._copy.position.y = 0;
  65734. this._copy.position.z = 0;
  65735. this._copy.rotation.x = 0;
  65736. this._copy.rotation.y = 0;
  65737. this._copy.rotation.z = 0;
  65738. this._copy.rotationQuaternion = null;
  65739. this._copy.scaling.x = 1.0;
  65740. this._copy.scaling.y = 1.0;
  65741. this._copy.scaling.z = 1.0;
  65742. this._copy.uvs.x = 0;
  65743. this._copy.uvs.y = 0;
  65744. this._copy.uvs.z = 1.0;
  65745. this._copy.uvs.w = 1.0;
  65746. this._copy.color = null;
  65747. this._copy.translateFromPivot = false;
  65748. };
  65749. // _meshBuilder : inserts the shape model in the global SPS mesh
  65750. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  65751. var i;
  65752. var u = 0;
  65753. var c = 0;
  65754. var n = 0;
  65755. this._resetCopy();
  65756. if (options && options.positionFunction) { // call to custom positionFunction
  65757. options.positionFunction(this._copy, idx, idxInShape);
  65758. this._mustUnrotateFixedNormals = true;
  65759. }
  65760. if (this._copy.rotationQuaternion) {
  65761. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65762. }
  65763. else {
  65764. this._yaw = this._copy.rotation.y;
  65765. this._pitch = this._copy.rotation.x;
  65766. this._roll = this._copy.rotation.z;
  65767. this._quaternionRotationYPR();
  65768. }
  65769. this._quaternionToRotationMatrix();
  65770. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  65771. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  65772. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  65773. if (this._copy.translateFromPivot) {
  65774. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65775. }
  65776. else {
  65777. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65778. }
  65779. for (i = 0; i < shape.length; i++) {
  65780. this._vertex.x = shape[i].x;
  65781. this._vertex.y = shape[i].y;
  65782. this._vertex.z = shape[i].z;
  65783. if (options && options.vertexFunction) {
  65784. options.vertexFunction(this._copy, this._vertex, i);
  65785. }
  65786. this._vertex.x *= this._copy.scaling.x;
  65787. this._vertex.y *= this._copy.scaling.y;
  65788. this._vertex.z *= this._copy.scaling.z;
  65789. this._vertex.x -= this._scaledPivot.x;
  65790. this._vertex.y -= this._scaledPivot.y;
  65791. this._vertex.z -= this._scaledPivot.z;
  65792. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65793. this._rotated.addInPlace(this._pivotBackTranslation);
  65794. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  65795. if (meshUV) {
  65796. 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);
  65797. u += 2;
  65798. }
  65799. if (this._copy.color) {
  65800. this._color = this._copy.color;
  65801. }
  65802. else if (meshCol && meshCol[c] !== undefined) {
  65803. this._color.r = meshCol[c];
  65804. this._color.g = meshCol[c + 1];
  65805. this._color.b = meshCol[c + 2];
  65806. this._color.a = meshCol[c + 3];
  65807. }
  65808. else {
  65809. this._color.r = 1.0;
  65810. this._color.g = 1.0;
  65811. this._color.b = 1.0;
  65812. this._color.a = 1.0;
  65813. }
  65814. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  65815. c += 4;
  65816. if (!this.recomputeNormals && meshNor) {
  65817. this._normal.x = meshNor[n];
  65818. this._normal.y = meshNor[n + 1];
  65819. this._normal.z = meshNor[n + 2];
  65820. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  65821. normals.push(this._normal.x, this._normal.y, this._normal.z);
  65822. n += 3;
  65823. }
  65824. }
  65825. for (i = 0; i < meshInd.length; i++) {
  65826. var current_ind = p + meshInd[i];
  65827. indices.push(current_ind);
  65828. if (current_ind > 65535) {
  65829. this._needs32Bits = true;
  65830. }
  65831. }
  65832. if (this._pickable) {
  65833. var nbfaces = meshInd.length / 3;
  65834. for (i = 0; i < nbfaces; i++) {
  65835. this.pickedParticles.push({ idx: idx, faceId: i });
  65836. }
  65837. }
  65838. if (this._depthSort) {
  65839. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  65840. }
  65841. return this._copy;
  65842. };
  65843. // returns a shape array from positions array
  65844. SolidParticleSystem.prototype._posToShape = function (positions) {
  65845. var shape = [];
  65846. for (var i = 0; i < positions.length; i += 3) {
  65847. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  65848. }
  65849. return shape;
  65850. };
  65851. // returns a shapeUV array from a Vector4 uvs
  65852. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  65853. var shapeUV = [];
  65854. if (uvs) {
  65855. for (var i = 0; i < uvs.length; i++)
  65856. shapeUV.push(uvs[i]);
  65857. }
  65858. return shapeUV;
  65859. };
  65860. // adds a new particle object in the particles array
  65861. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  65862. if (bInfo === void 0) { bInfo = null; }
  65863. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  65864. this.particles.push(sp);
  65865. return sp;
  65866. };
  65867. /**
  65868. * Adds some particles to the SPS from the model shape. Returns the shape id.
  65869. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  65870. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  65871. * @param nb (positive integer) the number of particles to be created from this model
  65872. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  65873. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  65874. * @returns the number of shapes in the system
  65875. */
  65876. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  65877. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65878. var meshInd = mesh.getIndices();
  65879. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65880. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65881. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65882. var bbInfo;
  65883. if (this._particlesIntersect) {
  65884. bbInfo = mesh.getBoundingInfo();
  65885. }
  65886. var shape = this._posToShape(meshPos);
  65887. var shapeUV = this._uvsToShapeUV(meshUV);
  65888. var posfunc = options ? options.positionFunction : null;
  65889. var vtxfunc = options ? options.vertexFunction : null;
  65890. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  65891. // particles
  65892. var sp;
  65893. var currentCopy;
  65894. var idx = this.nbParticles;
  65895. for (var i = 0; i < nb; i++) {
  65896. var currentPos = this._positions.length;
  65897. var currentInd = this._indices.length;
  65898. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  65899. if (this._updatable) {
  65900. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  65901. sp.position.copyFrom(currentCopy.position);
  65902. sp.rotation.copyFrom(currentCopy.rotation);
  65903. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  65904. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  65905. }
  65906. if (currentCopy.color && sp.color) {
  65907. sp.color.copyFrom(currentCopy.color);
  65908. }
  65909. sp.scaling.copyFrom(currentCopy.scaling);
  65910. sp.uvs.copyFrom(currentCopy.uvs);
  65911. }
  65912. this._index += shape.length;
  65913. idx++;
  65914. }
  65915. this.nbParticles += nb;
  65916. this._shapeCounter++;
  65917. return this._shapeCounter - 1;
  65918. };
  65919. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65920. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65921. this._resetCopy();
  65922. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65923. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65924. }
  65925. if (this._copy.rotationQuaternion) {
  65926. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65927. }
  65928. else {
  65929. this._yaw = this._copy.rotation.y;
  65930. this._pitch = this._copy.rotation.x;
  65931. this._roll = this._copy.rotation.z;
  65932. this._quaternionRotationYPR();
  65933. }
  65934. this._quaternionToRotationMatrix();
  65935. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65936. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65937. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65938. if (this._copy.translateFromPivot) {
  65939. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65940. }
  65941. else {
  65942. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65943. }
  65944. this._shape = particle._model._shape;
  65945. for (var pt = 0; pt < this._shape.length; pt++) {
  65946. this._vertex.x = this._shape[pt].x;
  65947. this._vertex.y = this._shape[pt].y;
  65948. this._vertex.z = this._shape[pt].z;
  65949. if (particle._model._vertexFunction) {
  65950. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65951. }
  65952. this._vertex.x *= this._copy.scaling.x;
  65953. this._vertex.y *= this._copy.scaling.y;
  65954. this._vertex.z *= this._copy.scaling.z;
  65955. this._vertex.x -= this._scaledPivot.x;
  65956. this._vertex.y -= this._scaledPivot.y;
  65957. this._vertex.z -= this._scaledPivot.z;
  65958. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65959. this._rotated.addInPlace(this._pivotBackTranslation);
  65960. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65961. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65962. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65963. }
  65964. particle.position.x = 0.0;
  65965. particle.position.y = 0.0;
  65966. particle.position.z = 0.0;
  65967. particle.rotation.x = 0.0;
  65968. particle.rotation.y = 0.0;
  65969. particle.rotation.z = 0.0;
  65970. particle.rotationQuaternion = null;
  65971. particle.scaling.x = 1.0;
  65972. particle.scaling.y = 1.0;
  65973. particle.scaling.z = 1.0;
  65974. particle.uvs.x = 0.0;
  65975. particle.uvs.y = 0.0;
  65976. particle.uvs.z = 1.0;
  65977. particle.uvs.w = 1.0;
  65978. particle.pivot.x = 0.0;
  65979. particle.pivot.y = 0.0;
  65980. particle.pivot.z = 0.0;
  65981. particle.translateFromPivot = false;
  65982. particle.parentId = null;
  65983. };
  65984. /**
  65985. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  65986. * @returns the SPS.
  65987. */
  65988. SolidParticleSystem.prototype.rebuildMesh = function () {
  65989. for (var p = 0; p < this.particles.length; p++) {
  65990. this._rebuildParticle(this.particles[p]);
  65991. }
  65992. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65993. return this;
  65994. };
  65995. /**
  65996. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  65997. * This method calls `updateParticle()` for each particle of the SPS.
  65998. * For an animated SPS, it is usually called within the render loop.
  65999. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66000. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66001. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66002. * @returns the SPS.
  66003. */
  66004. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66005. if (start === void 0) { start = 0; }
  66006. if (end === void 0) { end = this.nbParticles - 1; }
  66007. if (update === void 0) { update = true; }
  66008. if (!this._updatable) {
  66009. return this;
  66010. }
  66011. // custom beforeUpdate
  66012. this.beforeUpdateParticles(start, end, update);
  66013. this._cam_axisX.x = 1.0;
  66014. this._cam_axisX.y = 0.0;
  66015. this._cam_axisX.z = 0.0;
  66016. this._cam_axisY.x = 0.0;
  66017. this._cam_axisY.y = 1.0;
  66018. this._cam_axisY.z = 0.0;
  66019. this._cam_axisZ.x = 0.0;
  66020. this._cam_axisZ.y = 0.0;
  66021. this._cam_axisZ.z = 1.0;
  66022. // cases when the World Matrix is to be computed first
  66023. if (this.billboard || this._depthSort) {
  66024. this.mesh.computeWorldMatrix(true);
  66025. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66026. }
  66027. // if the particles will always face the camera
  66028. if (this.billboard) {
  66029. // compute the camera position and un-rotate it by the current mesh rotation
  66030. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66031. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66032. this._cam_axisZ.normalize();
  66033. // same for camera up vector extracted from the cam view matrix
  66034. var view = this._camera.getViewMatrix(true);
  66035. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  66036. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  66037. this._cam_axisY.normalize();
  66038. this._cam_axisX.normalize();
  66039. }
  66040. // if depthSort, compute the camera global position in the mesh local system
  66041. if (this._depthSort) {
  66042. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  66043. }
  66044. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  66045. var idx = 0; // current position index in the global array positions32
  66046. var index = 0; // position start index in the global array positions32 of the current particle
  66047. var colidx = 0; // current color index in the global array colors32
  66048. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  66049. var uvidx = 0; // current uv index in the global array uvs32
  66050. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  66051. var pt = 0; // current index in the particle model shape
  66052. if (this.mesh.isFacetDataEnabled) {
  66053. this._computeBoundingBox = true;
  66054. }
  66055. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  66056. if (this._computeBoundingBox) {
  66057. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  66058. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  66059. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  66060. }
  66061. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  66062. if (this.mesh._boundingInfo) {
  66063. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  66064. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  66065. }
  66066. }
  66067. }
  66068. // particle loop
  66069. index = this.particles[start]._pos;
  66070. var vpos = (index / 3) | 0;
  66071. colorIndex = vpos * 4;
  66072. uvIndex = vpos * 2;
  66073. for (var p = start; p <= end; p++) {
  66074. this._particle = this.particles[p];
  66075. this._shape = this._particle._model._shape;
  66076. this._shapeUV = this._particle._model._shapeUV;
  66077. // call to custom user function to update the particle properties
  66078. this.updateParticle(this._particle);
  66079. // camera-particle distance for depth sorting
  66080. if (this._depthSort && this._depthSortParticles) {
  66081. var dsp = this.depthSortedParticles[p];
  66082. dsp.ind = this._particle._ind;
  66083. dsp.indicesLength = this._particle._model._indicesLength;
  66084. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  66085. }
  66086. // skip the computations for inactive or already invisible particles
  66087. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  66088. // increment indexes for the next particle
  66089. pt = this._shape.length;
  66090. index += pt * 3;
  66091. colorIndex += pt * 4;
  66092. uvIndex += pt * 2;
  66093. continue;
  66094. }
  66095. if (this._particle.isVisible) {
  66096. this._particle._stillInvisible = false; // un-mark permanent invisibility
  66097. this._particleHasParent = (this._particle.parentId !== null);
  66098. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66099. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66100. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66101. // particle rotation matrix
  66102. if (this.billboard) {
  66103. this._particle.rotation.x = 0.0;
  66104. this._particle.rotation.y = 0.0;
  66105. }
  66106. if (this._computeParticleRotation || this.billboard) {
  66107. if (this._particle.rotationQuaternion) {
  66108. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66109. }
  66110. else {
  66111. this._yaw = this._particle.rotation.y;
  66112. this._pitch = this._particle.rotation.x;
  66113. this._roll = this._particle.rotation.z;
  66114. this._quaternionRotationYPR();
  66115. }
  66116. this._quaternionToRotationMatrix();
  66117. }
  66118. if (this._particleHasParent) {
  66119. this._parent = this.particles[this._particle.parentId];
  66120. 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];
  66121. 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];
  66122. 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];
  66123. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  66124. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  66125. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  66126. if (this._computeParticleRotation || this.billboard) {
  66127. 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];
  66128. 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];
  66129. 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];
  66130. 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];
  66131. 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];
  66132. 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];
  66133. 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];
  66134. 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];
  66135. 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];
  66136. }
  66137. }
  66138. else {
  66139. this._particle._globalPosition.x = this._particle.position.x;
  66140. this._particle._globalPosition.y = this._particle.position.y;
  66141. this._particle._globalPosition.z = this._particle.position.z;
  66142. if (this._computeParticleRotation || this.billboard) {
  66143. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  66144. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  66145. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  66146. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  66147. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  66148. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  66149. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  66150. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  66151. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  66152. }
  66153. }
  66154. if (this._particle.translateFromPivot) {
  66155. this._pivotBackTranslation.x = 0.0;
  66156. this._pivotBackTranslation.y = 0.0;
  66157. this._pivotBackTranslation.z = 0.0;
  66158. }
  66159. else {
  66160. this._pivotBackTranslation.x = this._scaledPivot.x;
  66161. this._pivotBackTranslation.y = this._scaledPivot.y;
  66162. this._pivotBackTranslation.z = this._scaledPivot.z;
  66163. }
  66164. // particle vertex loop
  66165. for (pt = 0; pt < this._shape.length; pt++) {
  66166. idx = index + pt * 3;
  66167. colidx = colorIndex + pt * 4;
  66168. uvidx = uvIndex + pt * 2;
  66169. this._vertex.x = this._shape[pt].x;
  66170. this._vertex.y = this._shape[pt].y;
  66171. this._vertex.z = this._shape[pt].z;
  66172. if (this._computeParticleVertex) {
  66173. this.updateParticleVertex(this._particle, this._vertex, pt);
  66174. }
  66175. // positions
  66176. this._vertex.x *= this._particle.scaling.x;
  66177. this._vertex.y *= this._particle.scaling.y;
  66178. this._vertex.z *= this._particle.scaling.z;
  66179. this._vertex.x -= this._scaledPivot.x;
  66180. this._vertex.y -= this._scaledPivot.y;
  66181. this._vertex.z -= this._scaledPivot.z;
  66182. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66183. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66184. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66185. this._rotated.x += this._pivotBackTranslation.x;
  66186. this._rotated.y += this._pivotBackTranslation.y;
  66187. this._rotated.z += this._pivotBackTranslation.z;
  66188. 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;
  66189. 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;
  66190. 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;
  66191. if (this._computeBoundingBox) {
  66192. if (this._positions32[idx] < this._minimum.x) {
  66193. this._minimum.x = this._positions32[idx];
  66194. }
  66195. if (this._positions32[idx] > this._maximum.x) {
  66196. this._maximum.x = this._positions32[idx];
  66197. }
  66198. if (this._positions32[idx + 1] < this._minimum.y) {
  66199. this._minimum.y = this._positions32[idx + 1];
  66200. }
  66201. if (this._positions32[idx + 1] > this._maximum.y) {
  66202. this._maximum.y = this._positions32[idx + 1];
  66203. }
  66204. if (this._positions32[idx + 2] < this._minimum.z) {
  66205. this._minimum.z = this._positions32[idx + 2];
  66206. }
  66207. if (this._positions32[idx + 2] > this._maximum.z) {
  66208. this._maximum.z = this._positions32[idx + 2];
  66209. }
  66210. }
  66211. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  66212. if (!this._computeParticleVertex) {
  66213. this._normal.x = this._fixedNormal32[idx];
  66214. this._normal.y = this._fixedNormal32[idx + 1];
  66215. this._normal.z = this._fixedNormal32[idx + 2];
  66216. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  66217. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  66218. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  66219. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  66220. 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;
  66221. 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;
  66222. }
  66223. if (this._computeParticleColor && this._particle.color) {
  66224. this._colors32[colidx] = this._particle.color.r;
  66225. this._colors32[colidx + 1] = this._particle.color.g;
  66226. this._colors32[colidx + 2] = this._particle.color.b;
  66227. this._colors32[colidx + 3] = this._particle.color.a;
  66228. }
  66229. if (this._computeParticleTexture) {
  66230. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66231. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66232. }
  66233. }
  66234. }
  66235. // particle just set invisible : scaled to zero and positioned at the origin
  66236. else {
  66237. this._particle._stillInvisible = true; // mark the particle as invisible
  66238. for (pt = 0; pt < this._shape.length; pt++) {
  66239. idx = index + pt * 3;
  66240. colidx = colorIndex + pt * 4;
  66241. uvidx = uvIndex + pt * 2;
  66242. this._positions32[idx] = 0.0;
  66243. this._positions32[idx + 1] = 0.0;
  66244. this._positions32[idx + 2] = 0.0;
  66245. this._normals32[idx] = 0.0;
  66246. this._normals32[idx + 1] = 0.0;
  66247. this._normals32[idx + 2] = 0.0;
  66248. if (this._computeParticleColor && this._particle.color) {
  66249. this._colors32[colidx] = this._particle.color.r;
  66250. this._colors32[colidx + 1] = this._particle.color.g;
  66251. this._colors32[colidx + 2] = this._particle.color.b;
  66252. this._colors32[colidx + 3] = this._particle.color.a;
  66253. }
  66254. if (this._computeParticleTexture) {
  66255. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66256. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66257. }
  66258. }
  66259. }
  66260. // if the particle intersections must be computed : update the bbInfo
  66261. if (this._particlesIntersect) {
  66262. var bInfo = this._particle._boundingInfo;
  66263. var bBox = bInfo.boundingBox;
  66264. var bSphere = bInfo.boundingSphere;
  66265. if (!this._bSphereOnly) {
  66266. // place, scale and rotate the particle bbox within the SPS local system, then update it
  66267. for (var b = 0; b < bBox.vectors.length; b++) {
  66268. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  66269. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  66270. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  66271. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66272. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66273. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66274. 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;
  66275. 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;
  66276. 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;
  66277. }
  66278. bBox._update(this.mesh._worldMatrix);
  66279. }
  66280. // place and scale the particle bouding sphere in the SPS local system, then update it
  66281. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  66282. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  66283. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  66284. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  66285. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  66286. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  66287. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  66288. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  66289. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  66290. 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));
  66291. bSphere._update(this.mesh._worldMatrix);
  66292. }
  66293. // increment indexes for the next particle
  66294. index = idx + 3;
  66295. colorIndex = colidx + 4;
  66296. uvIndex = uvidx + 2;
  66297. }
  66298. // if the VBO must be updated
  66299. if (update) {
  66300. if (this._computeParticleColor) {
  66301. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  66302. }
  66303. if (this._computeParticleTexture) {
  66304. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  66305. }
  66306. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66307. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  66308. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  66309. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  66310. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  66311. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  66312. for (var i = 0; i < this._normals32.length; i++) {
  66313. this._fixedNormal32[i] = this._normals32[i];
  66314. }
  66315. }
  66316. if (!this.mesh.areNormalsFrozen) {
  66317. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  66318. }
  66319. }
  66320. if (this._depthSort && this._depthSortParticles) {
  66321. this.depthSortedParticles.sort(this._depthSortFunction);
  66322. var dspl = this.depthSortedParticles.length;
  66323. var sorted = 0;
  66324. var lind = 0;
  66325. var sind = 0;
  66326. var sid = 0;
  66327. for (sorted = 0; sorted < dspl; sorted++) {
  66328. lind = this.depthSortedParticles[sorted].indicesLength;
  66329. sind = this.depthSortedParticles[sorted].ind;
  66330. for (var i = 0; i < lind; i++) {
  66331. this._indices32[sid] = this._indices[sind + i];
  66332. sid++;
  66333. }
  66334. }
  66335. this.mesh.updateIndices(this._indices32);
  66336. }
  66337. }
  66338. if (this._computeBoundingBox) {
  66339. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  66340. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  66341. }
  66342. this.afterUpdateParticles(start, end, update);
  66343. return this;
  66344. };
  66345. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  66346. this._halfroll = this._roll * 0.5;
  66347. this._halfpitch = this._pitch * 0.5;
  66348. this._halfyaw = this._yaw * 0.5;
  66349. this._sinRoll = Math.sin(this._halfroll);
  66350. this._cosRoll = Math.cos(this._halfroll);
  66351. this._sinPitch = Math.sin(this._halfpitch);
  66352. this._cosPitch = Math.cos(this._halfpitch);
  66353. this._sinYaw = Math.sin(this._halfyaw);
  66354. this._cosYaw = Math.cos(this._halfyaw);
  66355. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  66356. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  66357. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  66358. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  66359. };
  66360. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  66361. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  66362. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  66363. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  66364. this._rotMatrix.m[3] = 0;
  66365. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  66366. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  66367. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  66368. this._rotMatrix.m[7] = 0;
  66369. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  66370. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  66371. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  66372. this._rotMatrix.m[11] = 0;
  66373. this._rotMatrix.m[12] = 0;
  66374. this._rotMatrix.m[13] = 0;
  66375. this._rotMatrix.m[14] = 0;
  66376. this._rotMatrix.m[15] = 1.0;
  66377. };
  66378. /**
  66379. * Disposes the SPS.
  66380. */
  66381. SolidParticleSystem.prototype.dispose = function () {
  66382. this.mesh.dispose();
  66383. this.vars = null;
  66384. // drop references to internal big arrays for the GC
  66385. this._positions = null;
  66386. this._indices = null;
  66387. this._normals = null;
  66388. this._uvs = null;
  66389. this._colors = null;
  66390. this._indices32 = null;
  66391. this._positions32 = null;
  66392. this._normals32 = null;
  66393. this._fixedNormal32 = null;
  66394. this._uvs32 = null;
  66395. this._colors32 = null;
  66396. this.pickedParticles = null;
  66397. };
  66398. /**
  66399. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  66400. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66401. * @returns the SPS.
  66402. */
  66403. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  66404. if (!this._isVisibilityBoxLocked) {
  66405. this.mesh.refreshBoundingInfo();
  66406. }
  66407. return this;
  66408. };
  66409. /**
  66410. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  66411. * @param size the size (float) of the visibility box
  66412. * note : this doesn't lock the SPS mesh bounding box.
  66413. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66414. */
  66415. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  66416. var vis = size / 2;
  66417. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  66418. };
  66419. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  66420. /**
  66421. * Gets whether the SPS as always visible or not
  66422. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66423. */
  66424. get: function () {
  66425. return this._alwaysVisible;
  66426. },
  66427. /**
  66428. * Sets the SPS as always visible or not
  66429. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66430. */
  66431. set: function (val) {
  66432. this._alwaysVisible = val;
  66433. this.mesh.alwaysSelectAsActiveMesh = val;
  66434. },
  66435. enumerable: true,
  66436. configurable: true
  66437. });
  66438. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  66439. /**
  66440. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66441. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66442. */
  66443. get: function () {
  66444. return this._isVisibilityBoxLocked;
  66445. },
  66446. /**
  66447. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66448. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66449. */
  66450. set: function (val) {
  66451. this._isVisibilityBoxLocked = val;
  66452. var boundingInfo = this.mesh.getBoundingInfo();
  66453. boundingInfo.isLocked = val;
  66454. },
  66455. enumerable: true,
  66456. configurable: true
  66457. });
  66458. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  66459. /**
  66460. * Gets if `setParticles()` computes the particle rotations or not.
  66461. * Default value : true. The SPS is faster when it's set to false.
  66462. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66463. */
  66464. get: function () {
  66465. return this._computeParticleRotation;
  66466. },
  66467. /**
  66468. * Tells to `setParticles()` to compute the particle rotations or not.
  66469. * Default value : true. The SPS is faster when it's set to false.
  66470. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66471. */
  66472. set: function (val) {
  66473. this._computeParticleRotation = val;
  66474. },
  66475. enumerable: true,
  66476. configurable: true
  66477. });
  66478. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  66479. /**
  66480. * Gets if `setParticles()` computes the particle colors or not.
  66481. * Default value : true. The SPS is faster when it's set to false.
  66482. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66483. */
  66484. get: function () {
  66485. return this._computeParticleColor;
  66486. },
  66487. /**
  66488. * Tells to `setParticles()` to compute the particle colors or not.
  66489. * Default value : true. The SPS is faster when it's set to false.
  66490. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66491. */
  66492. set: function (val) {
  66493. this._computeParticleColor = val;
  66494. },
  66495. enumerable: true,
  66496. configurable: true
  66497. });
  66498. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  66499. /**
  66500. * Gets if `setParticles()` computes the particle textures or not.
  66501. * Default value : true. The SPS is faster when it's set to false.
  66502. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  66503. */
  66504. get: function () {
  66505. return this._computeParticleTexture;
  66506. },
  66507. set: function (val) {
  66508. this._computeParticleTexture = val;
  66509. },
  66510. enumerable: true,
  66511. configurable: true
  66512. });
  66513. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  66514. /**
  66515. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  66516. * Default value : false. The SPS is faster when it's set to false.
  66517. * Note : the particle custom vertex positions aren't stored values.
  66518. */
  66519. get: function () {
  66520. return this._computeParticleVertex;
  66521. },
  66522. /**
  66523. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  66524. * Default value : false. The SPS is faster when it's set to false.
  66525. * Note : the particle custom vertex positions aren't stored values.
  66526. */
  66527. set: function (val) {
  66528. this._computeParticleVertex = val;
  66529. },
  66530. enumerable: true,
  66531. configurable: true
  66532. });
  66533. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  66534. /**
  66535. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  66536. */
  66537. get: function () {
  66538. return this._computeBoundingBox;
  66539. },
  66540. /**
  66541. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  66542. */
  66543. set: function (val) {
  66544. this._computeBoundingBox = val;
  66545. },
  66546. enumerable: true,
  66547. configurable: true
  66548. });
  66549. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  66550. /**
  66551. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  66552. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66553. * Default : `true`
  66554. */
  66555. get: function () {
  66556. return this._depthSortParticles;
  66557. },
  66558. /**
  66559. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  66560. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66561. * Default : `true`
  66562. */
  66563. set: function (val) {
  66564. this._depthSortParticles = val;
  66565. },
  66566. enumerable: true,
  66567. configurable: true
  66568. });
  66569. // =======================================================================
  66570. // Particle behavior logic
  66571. // these following methods may be overwritten by the user to fit his needs
  66572. /**
  66573. * This function does nothing. It may be overwritten to set all the particle first values.
  66574. * The SPS doesn't call this function, you may have to call it by your own.
  66575. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66576. */
  66577. SolidParticleSystem.prototype.initParticles = function () {
  66578. };
  66579. /**
  66580. * This function does nothing. It may be overwritten to recycle a particle.
  66581. * The SPS doesn't call this function, you may have to call it by your own.
  66582. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66583. * @param particle The particle to recycle
  66584. * @returns the recycled particle
  66585. */
  66586. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  66587. return particle;
  66588. };
  66589. /**
  66590. * Updates a particle : this function should be overwritten by the user.
  66591. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  66592. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66593. * @example : just set a particle position or velocity and recycle conditions
  66594. * @param particle The particle to update
  66595. * @returns the updated particle
  66596. */
  66597. SolidParticleSystem.prototype.updateParticle = function (particle) {
  66598. return particle;
  66599. };
  66600. /**
  66601. * Updates a vertex of a particle : it can be overwritten by the user.
  66602. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  66603. * @param particle the current particle
  66604. * @param vertex the current index of the current particle
  66605. * @param pt the index of the current vertex in the particle shape
  66606. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  66607. * @example : just set a vertex particle position
  66608. * @returns the updated vertex
  66609. */
  66610. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  66611. return vertex;
  66612. };
  66613. /**
  66614. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  66615. * This does nothing and may be overwritten by the user.
  66616. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66617. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66618. * @param update the boolean update value actually passed to setParticles()
  66619. */
  66620. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  66621. };
  66622. /**
  66623. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  66624. * This will be passed three parameters.
  66625. * This does nothing and may be overwritten by the user.
  66626. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66627. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66628. * @param update the boolean update value actually passed to setParticles()
  66629. */
  66630. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  66631. };
  66632. return SolidParticleSystem;
  66633. }());
  66634. BABYLON.SolidParticleSystem = SolidParticleSystem;
  66635. })(BABYLON || (BABYLON = {}));
  66636. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  66637. var BABYLON;
  66638. (function (BABYLON) {
  66639. /**
  66640. * Class containing static functions to help procedurally build meshes
  66641. */
  66642. var MeshBuilder = /** @class */ (function () {
  66643. function MeshBuilder() {
  66644. }
  66645. MeshBuilder.updateSideOrientation = function (orientation) {
  66646. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  66647. return BABYLON.Mesh.DOUBLESIDE;
  66648. }
  66649. if (orientation === undefined || orientation === null) {
  66650. return BABYLON.Mesh.FRONTSIDE;
  66651. }
  66652. return orientation;
  66653. };
  66654. /**
  66655. * Creates a box mesh
  66656. * * The parameter `size` sets the size (float) of each box side (default 1)
  66657. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  66658. * * 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)
  66659. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66660. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66661. * * 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
  66662. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66663. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66664. * @param name defines the name of the mesh
  66665. * @param options defines the options used to create the mesh
  66666. * @param scene defines the hosting scene
  66667. * @returns the box mesh
  66668. */
  66669. MeshBuilder.CreateBox = function (name, options, scene) {
  66670. if (scene === void 0) { scene = null; }
  66671. var box = new BABYLON.Mesh(name, scene);
  66672. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66673. box._originalBuilderSideOrientation = options.sideOrientation;
  66674. var vertexData = BABYLON.VertexData.CreateBox(options);
  66675. vertexData.applyToMesh(box, options.updatable);
  66676. return box;
  66677. };
  66678. /**
  66679. * Creates a sphere mesh
  66680. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66681. * * 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`)
  66682. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66683. * * 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
  66684. * * 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)
  66685. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66686. * * 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
  66687. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66688. * @param name defines the name of the mesh
  66689. * @param options defines the options used to create the mesh
  66690. * @param scene defines the hosting scene
  66691. * @returns the sphere mesh
  66692. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66693. */
  66694. MeshBuilder.CreateSphere = function (name, options, scene) {
  66695. var sphere = new BABYLON.Mesh(name, scene);
  66696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66697. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66698. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66699. vertexData.applyToMesh(sphere, options.updatable);
  66700. return sphere;
  66701. };
  66702. /**
  66703. * Creates a plane polygonal mesh. By default, this is a disc
  66704. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66705. * * 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
  66706. * * 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
  66707. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66708. * * 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
  66709. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66710. * @param name defines the name of the mesh
  66711. * @param options defines the options used to create the mesh
  66712. * @param scene defines the hosting scene
  66713. * @returns the plane polygonal mesh
  66714. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  66715. */
  66716. MeshBuilder.CreateDisc = function (name, options, scene) {
  66717. if (scene === void 0) { scene = null; }
  66718. var disc = new BABYLON.Mesh(name, scene);
  66719. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66720. disc._originalBuilderSideOrientation = options.sideOrientation;
  66721. var vertexData = BABYLON.VertexData.CreateDisc(options);
  66722. vertexData.applyToMesh(disc, options.updatable);
  66723. return disc;
  66724. };
  66725. /**
  66726. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  66727. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  66728. * * 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`)
  66729. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  66730. * * 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
  66731. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66732. * * 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
  66733. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66734. * @param name defines the name of the mesh
  66735. * @param options defines the options used to create the mesh
  66736. * @param scene defines the hosting scene
  66737. * @returns the icosahedron mesh
  66738. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  66739. */
  66740. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  66741. var sphere = new BABYLON.Mesh(name, scene);
  66742. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66743. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66744. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  66745. vertexData.applyToMesh(sphere, options.updatable);
  66746. return sphere;
  66747. };
  66748. ;
  66749. /**
  66750. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66751. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  66752. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  66753. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  66754. * * 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
  66755. * * 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
  66756. * * 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
  66757. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66758. * * 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
  66759. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66760. * * 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
  66761. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  66762. * * 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
  66763. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  66764. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66765. * @param name defines the name of the mesh
  66766. * @param options defines the options used to create the mesh
  66767. * @param scene defines the hosting scene
  66768. * @returns the ribbon mesh
  66769. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  66770. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66771. */
  66772. MeshBuilder.CreateRibbon = function (name, options, scene) {
  66773. if (scene === void 0) { scene = null; }
  66774. var pathArray = options.pathArray;
  66775. var closeArray = options.closeArray;
  66776. var closePath = options.closePath;
  66777. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66778. var instance = options.instance;
  66779. var updatable = options.updatable;
  66780. if (instance) { // existing ribbon instance update
  66781. // positionFunction : ribbon case
  66782. // only pathArray and sideOrientation parameters are taken into account for positions update
  66783. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  66784. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  66785. var positionFunction = function (positions) {
  66786. var minlg = pathArray[0].length;
  66787. var mesh = instance;
  66788. var i = 0;
  66789. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  66790. for (var si = 1; si <= ns; si++) {
  66791. for (var p = 0; p < pathArray.length; p++) {
  66792. var path = pathArray[p];
  66793. var l = path.length;
  66794. minlg = (minlg < l) ? minlg : l;
  66795. var j = 0;
  66796. while (j < minlg) {
  66797. positions[i] = path[j].x;
  66798. positions[i + 1] = path[j].y;
  66799. positions[i + 2] = path[j].z;
  66800. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  66801. BABYLON.Tmp.Vector3[0].x = path[j].x;
  66802. }
  66803. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  66804. BABYLON.Tmp.Vector3[1].x = path[j].x;
  66805. }
  66806. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  66807. BABYLON.Tmp.Vector3[0].y = path[j].y;
  66808. }
  66809. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  66810. BABYLON.Tmp.Vector3[1].y = path[j].y;
  66811. }
  66812. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  66813. BABYLON.Tmp.Vector3[0].z = path[j].z;
  66814. }
  66815. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  66816. BABYLON.Tmp.Vector3[1].z = path[j].z;
  66817. }
  66818. j++;
  66819. i += 3;
  66820. }
  66821. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  66822. positions[i] = path[0].x;
  66823. positions[i + 1] = path[0].y;
  66824. positions[i + 2] = path[0].z;
  66825. i += 3;
  66826. }
  66827. }
  66828. }
  66829. };
  66830. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66831. positionFunction(positions);
  66832. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  66833. instance._boundingInfo.update(instance._worldMatrix);
  66834. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66835. if (options.colors) {
  66836. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66837. for (var c = 0; c < options.colors.length; c++) {
  66838. colors[c * 4] = options.colors[c].r;
  66839. colors[c * 4 + 1] = options.colors[c].g;
  66840. colors[c * 4 + 2] = options.colors[c].b;
  66841. colors[c * 4 + 3] = options.colors[c].a;
  66842. }
  66843. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  66844. }
  66845. if (options.uvs) {
  66846. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66847. for (var i = 0; i < options.uvs.length; i++) {
  66848. uvs[i * 2] = options.uvs[i].x;
  66849. uvs[i * 2 + 1] = options.uvs[i].y;
  66850. }
  66851. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  66852. }
  66853. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  66854. var indices = instance.getIndices();
  66855. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66856. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  66857. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  66858. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  66859. var indexFirst = 0;
  66860. var indexLast = 0;
  66861. for (var p = 0; p < pathArray.length; p++) {
  66862. indexFirst = instance._creationDataStorage.idx[p] * 3;
  66863. if (p + 1 < pathArray.length) {
  66864. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  66865. }
  66866. else {
  66867. indexLast = normals.length - 3;
  66868. }
  66869. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  66870. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  66871. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  66872. normals[indexLast] = normals[indexFirst];
  66873. normals[indexLast + 1] = normals[indexFirst + 1];
  66874. normals[indexLast + 2] = normals[indexFirst + 2];
  66875. }
  66876. }
  66877. if (!(instance.areNormalsFrozen)) {
  66878. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  66879. }
  66880. }
  66881. return instance;
  66882. }
  66883. else { // new ribbon creation
  66884. var ribbon = new BABYLON.Mesh(name, scene);
  66885. ribbon._originalBuilderSideOrientation = sideOrientation;
  66886. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  66887. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  66888. if (closePath) {
  66889. ribbon._creationDataStorage.idx = vertexData._idx;
  66890. }
  66891. ribbon._creationDataStorage.closePath = closePath;
  66892. ribbon._closeArray = closeArray;
  66893. vertexData.applyToMesh(ribbon, updatable);
  66894. return ribbon;
  66895. }
  66896. };
  66897. /**
  66898. * Creates a cylinder or a cone mesh
  66899. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  66900. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  66901. * * 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.
  66902. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  66903. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  66904. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  66905. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  66906. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  66907. * * 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).
  66908. * * 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
  66909. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  66910. * * 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
  66911. * * 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.
  66912. * * If `enclose` is false, a ring surface is one element.
  66913. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  66914. * * 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
  66915. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66916. * * 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
  66917. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66918. * @param name defines the name of the mesh
  66919. * @param options defines the options used to create the mesh
  66920. * @param scene defines the hosting scene
  66921. * @returns the cylinder mesh
  66922. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66923. */
  66924. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66925. var cylinder = new BABYLON.Mesh(name, scene);
  66926. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66927. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66928. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66929. vertexData.applyToMesh(cylinder, options.updatable);
  66930. return cylinder;
  66931. };
  66932. /**
  66933. * Creates a torus mesh
  66934. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66935. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66936. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66937. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66938. * * 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
  66939. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66940. * @param name defines the name of the mesh
  66941. * @param options defines the options used to create the mesh
  66942. * @param scene defines the hosting scene
  66943. * @returns the torus mesh
  66944. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66945. */
  66946. MeshBuilder.CreateTorus = function (name, options, scene) {
  66947. var torus = new BABYLON.Mesh(name, scene);
  66948. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66949. torus._originalBuilderSideOrientation = options.sideOrientation;
  66950. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66951. vertexData.applyToMesh(torus, options.updatable);
  66952. return torus;
  66953. };
  66954. /**
  66955. * Creates a torus knot mesh
  66956. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66957. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66958. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66959. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66960. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66961. * * 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
  66962. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66963. * @param name defines the name of the mesh
  66964. * @param options defines the options used to create the mesh
  66965. * @param scene defines the hosting scene
  66966. * @returns the torus knot mesh
  66967. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66968. */
  66969. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66970. var torusKnot = new BABYLON.Mesh(name, scene);
  66971. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66972. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  66973. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  66974. vertexData.applyToMesh(torusKnot, options.updatable);
  66975. return torusKnot;
  66976. };
  66977. /**
  66978. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  66979. * * 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
  66980. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  66981. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  66982. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  66983. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  66984. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  66985. * * 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
  66986. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  66987. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66988. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  66989. * @param name defines the name of the new line system
  66990. * @param options defines the options used to create the line system
  66991. * @param scene defines the hosting scene
  66992. * @returns a new line system mesh
  66993. */
  66994. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  66995. var instance = options.instance;
  66996. var lines = options.lines;
  66997. var colors = options.colors;
  66998. if (instance) { // lines update
  66999. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67000. var vertexColor;
  67001. var lineColors;
  67002. if (colors) {
  67003. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67004. }
  67005. var i = 0;
  67006. var c = 0;
  67007. for (var l = 0; l < lines.length; l++) {
  67008. var points = lines[l];
  67009. for (var p = 0; p < points.length; p++) {
  67010. positions[i] = points[p].x;
  67011. positions[i + 1] = points[p].y;
  67012. positions[i + 2] = points[p].z;
  67013. if (colors && vertexColor) {
  67014. lineColors = colors[l];
  67015. vertexColor[c] = lineColors[p].r;
  67016. vertexColor[c + 1] = lineColors[p].g;
  67017. vertexColor[c + 2] = lineColors[p].b;
  67018. vertexColor[c + 3] = lineColors[p].a;
  67019. c += 4;
  67020. }
  67021. i += 3;
  67022. }
  67023. }
  67024. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67025. if (colors && vertexColor) {
  67026. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67027. }
  67028. return instance;
  67029. }
  67030. // line system creation
  67031. var useVertexColor = (colors) ? true : false;
  67032. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67033. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67034. vertexData.applyToMesh(lineSystem, options.updatable);
  67035. return lineSystem;
  67036. };
  67037. /**
  67038. * Creates a line mesh
  67039. * 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
  67040. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67041. * * The parameter `points` is an array successive Vector3
  67042. * * 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
  67043. * * The optional parameter `colors` is an array of successive Color4, one per line point
  67044. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  67045. * * When updating an instance, remember that only point positions can change, not the number of points
  67046. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67047. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  67048. * @param name defines the name of the new line system
  67049. * @param options defines the options used to create the line system
  67050. * @param scene defines the hosting scene
  67051. * @returns a new line mesh
  67052. */
  67053. MeshBuilder.CreateLines = function (name, options, scene) {
  67054. if (scene === void 0) { scene = null; }
  67055. var colors = (options.colors) ? [options.colors] : null;
  67056. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  67057. return lines;
  67058. };
  67059. /**
  67060. * Creates a dashed line mesh
  67061. * * 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
  67062. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67063. * * The parameter `points` is an array successive Vector3
  67064. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  67065. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  67066. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  67067. * * 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
  67068. * * When updating an instance, remember that only point positions can change, not the number of points
  67069. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67070. * @param name defines the name of the mesh
  67071. * @param options defines the options used to create the mesh
  67072. * @param scene defines the hosting scene
  67073. * @returns the dashed line mesh
  67074. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  67075. */
  67076. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  67077. if (scene === void 0) { scene = null; }
  67078. var points = options.points;
  67079. var instance = options.instance;
  67080. var gapSize = options.gapSize || 1;
  67081. var dashSize = options.dashSize || 3;
  67082. if (instance) { // dashed lines update
  67083. var positionFunction = function (positions) {
  67084. var curvect = BABYLON.Vector3.Zero();
  67085. var nbSeg = positions.length / 6;
  67086. var lg = 0;
  67087. var nb = 0;
  67088. var shft = 0;
  67089. var dashshft = 0;
  67090. var curshft = 0;
  67091. var p = 0;
  67092. var i = 0;
  67093. var j = 0;
  67094. for (i = 0; i < points.length - 1; i++) {
  67095. points[i + 1].subtractToRef(points[i], curvect);
  67096. lg += curvect.length();
  67097. }
  67098. shft = lg / nbSeg;
  67099. var dashSize = instance._creationDataStorage.dashSize;
  67100. var gapSize = instance._creationDataStorage.gapSize;
  67101. dashshft = dashSize * shft / (dashSize + gapSize);
  67102. for (i = 0; i < points.length - 1; i++) {
  67103. points[i + 1].subtractToRef(points[i], curvect);
  67104. nb = Math.floor(curvect.length() / shft);
  67105. curvect.normalize();
  67106. j = 0;
  67107. while (j < nb && p < positions.length) {
  67108. curshft = shft * j;
  67109. positions[p] = points[i].x + curshft * curvect.x;
  67110. positions[p + 1] = points[i].y + curshft * curvect.y;
  67111. positions[p + 2] = points[i].z + curshft * curvect.z;
  67112. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  67113. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  67114. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  67115. p += 6;
  67116. j++;
  67117. }
  67118. }
  67119. while (p < positions.length) {
  67120. positions[p] = points[i].x;
  67121. positions[p + 1] = points[i].y;
  67122. positions[p + 2] = points[i].z;
  67123. p += 3;
  67124. }
  67125. };
  67126. instance.updateMeshPositions(positionFunction, false);
  67127. return instance;
  67128. }
  67129. // dashed lines creation
  67130. var dashedLines = new BABYLON.LinesMesh(name, scene);
  67131. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  67132. vertexData.applyToMesh(dashedLines, options.updatable);
  67133. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  67134. dashedLines._creationDataStorage.dashSize = dashSize;
  67135. dashedLines._creationDataStorage.gapSize = gapSize;
  67136. return dashedLines;
  67137. };
  67138. /**
  67139. * 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.
  67140. * * 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.
  67141. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67142. * * 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.
  67143. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  67144. * * 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
  67145. * * 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
  67146. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  67147. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67148. * * 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
  67149. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  67150. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67151. * @param name defines the name of the mesh
  67152. * @param options defines the options used to create the mesh
  67153. * @param scene defines the hosting scene
  67154. * @returns the extruded shape mesh
  67155. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67156. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67157. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67158. */
  67159. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  67160. if (scene === void 0) { scene = null; }
  67161. var path = options.path;
  67162. var shape = options.shape;
  67163. var scale = options.scale || 1;
  67164. var rotation = options.rotation || 0;
  67165. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67166. var updatable = options.updatable;
  67167. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67168. var instance = options.instance || null;
  67169. var invertUV = options.invertUV || false;
  67170. 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);
  67171. };
  67172. /**
  67173. * Creates an custom extruded shape mesh.
  67174. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  67175. * * 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.
  67176. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67177. * * 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
  67178. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  67179. * * 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
  67180. * * It must returns a float value that will be the scale value applied to the shape on each path point
  67181. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  67182. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  67183. * * 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
  67184. * * 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
  67185. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  67186. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67187. * * 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
  67188. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67189. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67190. * @param name defines the name of the mesh
  67191. * @param options defines the options used to create the mesh
  67192. * @param scene defines the hosting scene
  67193. * @returns the custom extruded shape mesh
  67194. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  67195. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67196. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67197. */
  67198. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  67199. var path = options.path;
  67200. var shape = options.shape;
  67201. var scaleFunction = options.scaleFunction || (function () { return 1; });
  67202. var rotationFunction = options.rotationFunction || (function () { return 0; });
  67203. var ribbonCloseArray = options.ribbonCloseArray || false;
  67204. var ribbonClosePath = options.ribbonClosePath || false;
  67205. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67206. var updatable = options.updatable;
  67207. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67208. var instance = options.instance;
  67209. var invertUV = options.invertUV || false;
  67210. 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);
  67211. };
  67212. /**
  67213. * Creates lathe mesh.
  67214. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  67215. * * 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
  67216. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  67217. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  67218. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  67219. * * 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
  67220. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  67221. * * 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
  67222. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67223. * * 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
  67224. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67225. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67226. * @param name defines the name of the mesh
  67227. * @param options defines the options used to create the mesh
  67228. * @param scene defines the hosting scene
  67229. * @returns the lathe mesh
  67230. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  67231. */
  67232. MeshBuilder.CreateLathe = function (name, options, scene) {
  67233. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  67234. var closed = (options.closed === undefined) ? true : options.closed;
  67235. var shape = options.shape;
  67236. var radius = options.radius || 1;
  67237. var tessellation = options.tessellation || 64;
  67238. var clip = options.clip || 0;
  67239. var updatable = options.updatable;
  67240. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67241. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67242. var pi2 = Math.PI * 2;
  67243. var paths = new Array();
  67244. var invertUV = options.invertUV || false;
  67245. var i = 0;
  67246. var p = 0;
  67247. var step = pi2 / tessellation * arc;
  67248. var rotated;
  67249. var path = new Array();
  67250. for (i = 0; i <= tessellation - clip; i++) {
  67251. var path = [];
  67252. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  67253. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  67254. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  67255. }
  67256. for (p = 0; p < shape.length; p++) {
  67257. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  67258. path.push(rotated);
  67259. }
  67260. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  67261. 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));
  67262. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  67263. }
  67264. paths.push(path);
  67265. }
  67266. // lathe ribbon
  67267. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67268. return lathe;
  67269. };
  67270. /**
  67271. * Creates a plane mesh
  67272. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  67273. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  67274. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  67275. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67276. * * 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
  67277. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67278. * @param name defines the name of the mesh
  67279. * @param options defines the options used to create the mesh
  67280. * @param scene defines the hosting scene
  67281. * @returns the plane mesh
  67282. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67283. */
  67284. MeshBuilder.CreatePlane = function (name, options, scene) {
  67285. var plane = new BABYLON.Mesh(name, scene);
  67286. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67287. plane._originalBuilderSideOrientation = options.sideOrientation;
  67288. var vertexData = BABYLON.VertexData.CreatePlane(options);
  67289. vertexData.applyToMesh(plane, options.updatable);
  67290. if (options.sourcePlane) {
  67291. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  67292. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  67293. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  67294. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  67295. plane.rotate(vectorProduct, product);
  67296. }
  67297. }
  67298. return plane;
  67299. };
  67300. /**
  67301. * Creates a ground mesh
  67302. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  67303. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  67304. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67305. * @param name defines the name of the mesh
  67306. * @param options defines the options used to create the mesh
  67307. * @param scene defines the hosting scene
  67308. * @returns the ground mesh
  67309. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67310. */
  67311. MeshBuilder.CreateGround = function (name, options, scene) {
  67312. var ground = new BABYLON.GroundMesh(name, scene);
  67313. ground._setReady(false);
  67314. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  67315. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  67316. ground._width = options.width || 1;
  67317. ground._height = options.height || 1;
  67318. ground._maxX = ground._width / 2;
  67319. ground._maxZ = ground._height / 2;
  67320. ground._minX = -ground._maxX;
  67321. ground._minZ = -ground._maxZ;
  67322. var vertexData = BABYLON.VertexData.CreateGround(options);
  67323. vertexData.applyToMesh(ground, options.updatable);
  67324. ground._setReady(true);
  67325. return ground;
  67326. };
  67327. /**
  67328. * Creates a tiled ground mesh
  67329. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  67330. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  67331. * * 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
  67332. * * 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
  67333. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67334. * @param name defines the name of the mesh
  67335. * @param options defines the options used to create the mesh
  67336. * @param scene defines the hosting scene
  67337. * @returns the tiled ground mesh
  67338. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  67339. */
  67340. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  67341. var tiledGround = new BABYLON.Mesh(name, scene);
  67342. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  67343. vertexData.applyToMesh(tiledGround, options.updatable);
  67344. return tiledGround;
  67345. };
  67346. /**
  67347. * Creates a ground mesh from a height map
  67348. * * The parameter `url` sets the URL of the height map image resource.
  67349. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  67350. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  67351. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  67352. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  67353. * * 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.
  67354. * * 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).
  67355. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  67356. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67357. * @param name defines the name of the mesh
  67358. * @param url defines the url to the height map
  67359. * @param options defines the options used to create the mesh
  67360. * @param scene defines the hosting scene
  67361. * @returns the ground mesh
  67362. * @see http://doc.babylonjs.com/babylon101/height_map
  67363. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  67364. */
  67365. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  67366. var width = options.width || 10.0;
  67367. var height = options.height || 10.0;
  67368. var subdivisions = options.subdivisions || 1 | 0;
  67369. var minHeight = options.minHeight || 0.0;
  67370. var maxHeight = options.maxHeight || 1.0;
  67371. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  67372. var alphaFilter = options.alphaFilter || 0.0;
  67373. var updatable = options.updatable;
  67374. var onReady = options.onReady;
  67375. var ground = new BABYLON.GroundMesh(name, scene);
  67376. ground._subdivisionsX = subdivisions;
  67377. ground._subdivisionsY = subdivisions;
  67378. ground._width = width;
  67379. ground._height = height;
  67380. ground._maxX = ground._width / 2.0;
  67381. ground._maxZ = ground._height / 2.0;
  67382. ground._minX = -ground._maxX;
  67383. ground._minZ = -ground._maxZ;
  67384. ground._setReady(false);
  67385. var onload = function (img) {
  67386. // Getting height map data
  67387. var canvas = document.createElement("canvas");
  67388. var context = canvas.getContext("2d");
  67389. if (!context) {
  67390. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  67391. }
  67392. if (scene.isDisposed) {
  67393. return;
  67394. }
  67395. var bufferWidth = img.width;
  67396. var bufferHeight = img.height;
  67397. canvas.width = bufferWidth;
  67398. canvas.height = bufferHeight;
  67399. context.drawImage(img, 0, 0);
  67400. // Create VertexData from map data
  67401. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  67402. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  67403. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  67404. width: width, height: height,
  67405. subdivisions: subdivisions,
  67406. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  67407. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  67408. alphaFilter: alphaFilter
  67409. });
  67410. vertexData.applyToMesh(ground, updatable);
  67411. //execute ready callback, if set
  67412. if (onReady) {
  67413. onReady(ground);
  67414. }
  67415. ground._setReady(true);
  67416. };
  67417. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  67418. return ground;
  67419. };
  67420. /**
  67421. * Creates a polygon mesh
  67422. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  67423. * * 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
  67424. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67425. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67426. * * 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)
  67427. * * Remember you can only change the shape positions, not their number when updating a polygon
  67428. * @param name defines the name of the mesh
  67429. * @param options defines the options used to create the mesh
  67430. * @param scene defines the hosting scene
  67431. * @returns the polygon mesh
  67432. */
  67433. MeshBuilder.CreatePolygon = function (name, options, scene) {
  67434. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67435. var shape = options.shape;
  67436. var holes = options.holes || [];
  67437. var depth = options.depth || 0;
  67438. var contours = [];
  67439. var hole = [];
  67440. for (var i = 0; i < shape.length; i++) {
  67441. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  67442. }
  67443. var epsilon = 0.00000001;
  67444. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  67445. contours.pop();
  67446. }
  67447. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  67448. for (var hNb = 0; hNb < holes.length; hNb++) {
  67449. hole = [];
  67450. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  67451. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  67452. }
  67453. polygonTriangulation.addHole(hole);
  67454. }
  67455. var polygon = polygonTriangulation.build(options.updatable, depth);
  67456. polygon._originalBuilderSideOrientation = options.sideOrientation;
  67457. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  67458. vertexData.applyToMesh(polygon, options.updatable);
  67459. return polygon;
  67460. };
  67461. ;
  67462. /**
  67463. * Creates an extruded polygon mesh, with depth in the Y direction.
  67464. * * 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)
  67465. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67466. * @param name defines the name of the mesh
  67467. * @param options defines the options used to create the mesh
  67468. * @param scene defines the hosting scene
  67469. * @returns the polygon mesh
  67470. */
  67471. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  67472. return MeshBuilder.CreatePolygon(name, options, scene);
  67473. };
  67474. ;
  67475. /**
  67476. * Creates a tube mesh.
  67477. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67478. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  67479. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  67480. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  67481. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  67482. * * 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)
  67483. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  67484. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  67485. * * 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
  67486. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67487. * * 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
  67488. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67489. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67490. * @param name defines the name of the mesh
  67491. * @param options defines the options used to create the mesh
  67492. * @param scene defines the hosting scene
  67493. * @returns the tube mesh
  67494. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67495. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  67496. */
  67497. MeshBuilder.CreateTube = function (name, options, scene) {
  67498. var path = options.path;
  67499. var instance = options.instance;
  67500. var radius = 1.0;
  67501. if (options.radius !== undefined) {
  67502. radius = options.radius;
  67503. }
  67504. else if (instance) {
  67505. radius = instance._creationDataStorage.radius;
  67506. }
  67507. var tessellation = options.tessellation || 64 | 0;
  67508. var radiusFunction = options.radiusFunction || null;
  67509. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67510. var invertUV = options.invertUV || false;
  67511. var updatable = options.updatable;
  67512. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67513. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  67514. // tube geometry
  67515. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  67516. var tangents = path3D.getTangents();
  67517. var normals = path3D.getNormals();
  67518. var distances = path3D.getDistances();
  67519. var pi2 = Math.PI * 2;
  67520. var step = pi2 / tessellation * arc;
  67521. var returnRadius = function () { return radius; };
  67522. var radiusFunctionFinal = radiusFunction || returnRadius;
  67523. var circlePath;
  67524. var rad;
  67525. var normal;
  67526. var rotated;
  67527. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67528. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67529. for (var i = 0; i < path.length; i++) {
  67530. rad = radiusFunctionFinal(i, distances[i]); // current radius
  67531. circlePath = Array(); // current circle array
  67532. normal = normals[i]; // current normal
  67533. for (var t = 0; t < tessellation; t++) {
  67534. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  67535. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  67536. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  67537. rotated.scaleInPlace(rad).addInPlace(path[i]);
  67538. circlePath[t] = rotated;
  67539. }
  67540. circlePaths[index] = circlePath;
  67541. index++;
  67542. }
  67543. // cap
  67544. var capPath = function (nbPoints, pathIndex) {
  67545. var pointCap = Array();
  67546. for (var i = 0; i < nbPoints; i++) {
  67547. pointCap.push(path[pathIndex]);
  67548. }
  67549. return pointCap;
  67550. };
  67551. switch (cap) {
  67552. case BABYLON.Mesh.NO_CAP:
  67553. break;
  67554. case BABYLON.Mesh.CAP_START:
  67555. circlePaths[0] = capPath(tessellation, 0);
  67556. circlePaths[1] = circlePaths[2].slice(0);
  67557. break;
  67558. case BABYLON.Mesh.CAP_END:
  67559. circlePaths[index] = circlePaths[index - 1].slice(0);
  67560. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67561. break;
  67562. case BABYLON.Mesh.CAP_ALL:
  67563. circlePaths[0] = capPath(tessellation, 0);
  67564. circlePaths[1] = circlePaths[2].slice(0);
  67565. circlePaths[index] = circlePaths[index - 1].slice(0);
  67566. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67567. break;
  67568. default:
  67569. break;
  67570. }
  67571. return circlePaths;
  67572. };
  67573. var path3D;
  67574. var pathArray;
  67575. if (instance) { // tube update
  67576. var arc = options.arc || instance.arc;
  67577. var storage = instance._creationDataStorage;
  67578. path3D = storage.path3D.update(path);
  67579. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  67580. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  67581. instance._creationDataStorage = new BABYLON._CreationDataStorage();
  67582. instance._creationDataStorage.path3D = path3D;
  67583. instance._creationDataStorage.pathArray = pathArray;
  67584. instance._creationDataStorage.arc = arc;
  67585. instance._creationDataStorage.radius = radius;
  67586. return instance;
  67587. }
  67588. // tube creation
  67589. path3D = new BABYLON.Path3D(path);
  67590. var newPathArray = new Array();
  67591. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67592. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  67593. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67594. tube._creationDataStorage = new BABYLON._CreationDataStorage();
  67595. tube._creationDataStorage.pathArray = pathArray;
  67596. tube._creationDataStorage.path3D = path3D;
  67597. tube._creationDataStorage.tessellation = tessellation;
  67598. tube._creationDataStorage.cap = cap;
  67599. tube._creationDataStorage.arc = options.arc;
  67600. tube._creationDataStorage.radius = radius;
  67601. return tube;
  67602. };
  67603. /**
  67604. * Creates a polyhedron mesh
  67605. * * 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
  67606. * * The parameter `size` (positive float, default 1) sets the polygon size
  67607. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  67608. * * 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`
  67609. * * 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
  67610. * * 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)`)
  67611. * * 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
  67612. * * 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
  67613. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67614. * * 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
  67615. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67616. * @param name defines the name of the mesh
  67617. * @param options defines the options used to create the mesh
  67618. * @param scene defines the hosting scene
  67619. * @returns the polyhedron mesh
  67620. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  67621. */
  67622. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  67623. var polyhedron = new BABYLON.Mesh(name, scene);
  67624. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67625. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  67626. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  67627. vertexData.applyToMesh(polyhedron, options.updatable);
  67628. return polyhedron;
  67629. };
  67630. /**
  67631. * Creates a decal mesh.
  67632. * 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
  67633. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  67634. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  67635. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  67636. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  67637. * @param name defines the name of the mesh
  67638. * @param sourceMesh defines the mesh where the decal must be applied
  67639. * @param options defines the options used to create the mesh
  67640. * @param scene defines the hosting scene
  67641. * @returns the decal mesh
  67642. * @see http://doc.babylonjs.com/how_to/decals
  67643. */
  67644. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  67645. var indices = sourceMesh.getIndices();
  67646. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67647. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67648. var position = options.position || BABYLON.Vector3.Zero();
  67649. var normal = options.normal || BABYLON.Vector3.Up();
  67650. var size = options.size || BABYLON.Vector3.One();
  67651. var angle = options.angle || 0;
  67652. // Getting correct rotation
  67653. if (!normal) {
  67654. var target = new BABYLON.Vector3(0, 0, 1);
  67655. var camera = sourceMesh.getScene().activeCamera;
  67656. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  67657. normal = camera.globalPosition.subtract(cameraWorldTarget);
  67658. }
  67659. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  67660. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  67661. var pitch = Math.atan2(normal.y, len);
  67662. // Matrix
  67663. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  67664. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  67665. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67666. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67667. var vertexData = new BABYLON.VertexData();
  67668. vertexData.indices = [];
  67669. vertexData.positions = [];
  67670. vertexData.normals = [];
  67671. vertexData.uvs = [];
  67672. var currentVertexDataIndex = 0;
  67673. var extractDecalVector3 = function (indexId) {
  67674. var result = new BABYLON.PositionNormalVertex();
  67675. if (!indices || !positions || !normals) {
  67676. return result;
  67677. }
  67678. var vertexId = indices[indexId];
  67679. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67680. // Send vector to decal local world
  67681. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67682. // Get normal
  67683. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67684. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67685. return result;
  67686. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67687. var clip = function (vertices, axis) {
  67688. if (vertices.length === 0) {
  67689. return vertices;
  67690. }
  67691. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67692. var clipVertices = function (v0, v1) {
  67693. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67694. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67695. };
  67696. var result = new Array();
  67697. for (var index = 0; index < vertices.length; index += 3) {
  67698. var v1Out;
  67699. var v2Out;
  67700. var v3Out;
  67701. var total = 0;
  67702. var nV1 = null;
  67703. var nV2 = null;
  67704. var nV3 = null;
  67705. var nV4 = null;
  67706. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67707. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67708. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67709. v1Out = d1 > 0;
  67710. v2Out = d2 > 0;
  67711. v3Out = d3 > 0;
  67712. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  67713. switch (total) {
  67714. case 0:
  67715. result.push(vertices[index]);
  67716. result.push(vertices[index + 1]);
  67717. result.push(vertices[index + 2]);
  67718. break;
  67719. case 1:
  67720. if (v1Out) {
  67721. nV1 = vertices[index + 1];
  67722. nV2 = vertices[index + 2];
  67723. nV3 = clipVertices(vertices[index], nV1);
  67724. nV4 = clipVertices(vertices[index], nV2);
  67725. }
  67726. if (v2Out) {
  67727. nV1 = vertices[index];
  67728. nV2 = vertices[index + 2];
  67729. nV3 = clipVertices(vertices[index + 1], nV1);
  67730. nV4 = clipVertices(vertices[index + 1], nV2);
  67731. result.push(nV3);
  67732. result.push(nV2.clone());
  67733. result.push(nV1.clone());
  67734. result.push(nV2.clone());
  67735. result.push(nV3.clone());
  67736. result.push(nV4);
  67737. break;
  67738. }
  67739. if (v3Out) {
  67740. nV1 = vertices[index];
  67741. nV2 = vertices[index + 1];
  67742. nV3 = clipVertices(vertices[index + 2], nV1);
  67743. nV4 = clipVertices(vertices[index + 2], nV2);
  67744. }
  67745. if (nV1 && nV2 && nV3 && nV4) {
  67746. result.push(nV1.clone());
  67747. result.push(nV2.clone());
  67748. result.push(nV3);
  67749. result.push(nV4);
  67750. result.push(nV3.clone());
  67751. result.push(nV2.clone());
  67752. }
  67753. break;
  67754. case 2:
  67755. if (!v1Out) {
  67756. nV1 = vertices[index].clone();
  67757. nV2 = clipVertices(nV1, vertices[index + 1]);
  67758. nV3 = clipVertices(nV1, vertices[index + 2]);
  67759. result.push(nV1);
  67760. result.push(nV2);
  67761. result.push(nV3);
  67762. }
  67763. if (!v2Out) {
  67764. nV1 = vertices[index + 1].clone();
  67765. nV2 = clipVertices(nV1, vertices[index + 2]);
  67766. nV3 = clipVertices(nV1, vertices[index]);
  67767. result.push(nV1);
  67768. result.push(nV2);
  67769. result.push(nV3);
  67770. }
  67771. if (!v3Out) {
  67772. nV1 = vertices[index + 2].clone();
  67773. nV2 = clipVertices(nV1, vertices[index]);
  67774. nV3 = clipVertices(nV1, vertices[index + 1]);
  67775. result.push(nV1);
  67776. result.push(nV2);
  67777. result.push(nV3);
  67778. }
  67779. break;
  67780. case 3:
  67781. break;
  67782. }
  67783. }
  67784. return result;
  67785. };
  67786. for (var index = 0; index < indices.length; index += 3) {
  67787. var faceVertices = new Array();
  67788. faceVertices.push(extractDecalVector3(index));
  67789. faceVertices.push(extractDecalVector3(index + 1));
  67790. faceVertices.push(extractDecalVector3(index + 2));
  67791. // Clip
  67792. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  67793. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  67794. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  67795. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  67796. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  67797. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  67798. if (faceVertices.length === 0) {
  67799. continue;
  67800. }
  67801. // Add UVs and get back to world
  67802. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  67803. var vertex = faceVertices[vIndex];
  67804. //TODO check for Int32Array | Uint32Array | Uint16Array
  67805. vertexData.indices.push(currentVertexDataIndex);
  67806. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  67807. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  67808. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  67809. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  67810. currentVertexDataIndex++;
  67811. }
  67812. }
  67813. // Return mesh
  67814. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  67815. vertexData.applyToMesh(decal);
  67816. decal.position = position.clone();
  67817. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  67818. return decal;
  67819. };
  67820. // Privates
  67821. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  67822. // extrusion geometry
  67823. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  67824. var tangents = path3D.getTangents();
  67825. var normals = path3D.getNormals();
  67826. var binormals = path3D.getBinormals();
  67827. var distances = path3D.getDistances();
  67828. var angle = 0;
  67829. var returnScale = function () { return scale !== null ? scale : 1; };
  67830. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  67831. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  67832. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  67833. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67834. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67835. for (var i = 0; i < curve.length; i++) {
  67836. var shapePath = new Array();
  67837. var angleStep = rotate(i, distances[i]);
  67838. var scaleRatio = scl(i, distances[i]);
  67839. for (var p = 0; p < shape.length; p++) {
  67840. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  67841. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  67842. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  67843. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  67844. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  67845. shapePath[p] = rotated;
  67846. }
  67847. shapePaths[index] = shapePath;
  67848. angle += angleStep;
  67849. index++;
  67850. }
  67851. // cap
  67852. var capPath = function (shapePath) {
  67853. var pointCap = Array();
  67854. var barycenter = BABYLON.Vector3.Zero();
  67855. var i;
  67856. for (i = 0; i < shapePath.length; i++) {
  67857. barycenter.addInPlace(shapePath[i]);
  67858. }
  67859. barycenter.scaleInPlace(1.0 / shapePath.length);
  67860. for (i = 0; i < shapePath.length; i++) {
  67861. pointCap.push(barycenter);
  67862. }
  67863. return pointCap;
  67864. };
  67865. switch (cap) {
  67866. case BABYLON.Mesh.NO_CAP:
  67867. break;
  67868. case BABYLON.Mesh.CAP_START:
  67869. shapePaths[0] = capPath(shapePaths[2]);
  67870. shapePaths[1] = shapePaths[2];
  67871. break;
  67872. case BABYLON.Mesh.CAP_END:
  67873. shapePaths[index] = shapePaths[index - 1];
  67874. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67875. break;
  67876. case BABYLON.Mesh.CAP_ALL:
  67877. shapePaths[0] = capPath(shapePaths[2]);
  67878. shapePaths[1] = shapePaths[2];
  67879. shapePaths[index] = shapePaths[index - 1];
  67880. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67881. break;
  67882. default:
  67883. break;
  67884. }
  67885. return shapePaths;
  67886. };
  67887. var path3D;
  67888. var pathArray;
  67889. if (instance) { // instance update
  67890. var storage = instance._creationDataStorage;
  67891. path3D = storage.path3D.update(curve);
  67892. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  67893. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  67894. return instance;
  67895. }
  67896. // extruded shape creation
  67897. path3D = new BABYLON.Path3D(curve);
  67898. var newShapePaths = new Array();
  67899. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67900. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  67901. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  67902. extrudedGeneric._creationDataStorage = new BABYLON._CreationDataStorage();
  67903. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  67904. extrudedGeneric._creationDataStorage.path3D = path3D;
  67905. extrudedGeneric._creationDataStorage.cap = cap;
  67906. return extrudedGeneric;
  67907. };
  67908. return MeshBuilder;
  67909. }());
  67910. BABYLON.MeshBuilder = MeshBuilder;
  67911. })(BABYLON || (BABYLON = {}));
  67912. //# sourceMappingURL=babylon.meshBuilder.js.map
  67913. var BABYLON;
  67914. (function (BABYLON) {
  67915. /**
  67916. * Draco compression (https://google.github.io/draco/)
  67917. *
  67918. * This class wraps the Draco module.
  67919. *
  67920. * **Encoder**
  67921. *
  67922. * The encoder is not currently implemented.
  67923. *
  67924. * **Decoder**
  67925. *
  67926. * 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.
  67927. *
  67928. * To update the configuration, use the following code:
  67929. * ```javascript
  67930. * BABYLON.DracoCompression.Configuration = {
  67931. * decoder: {
  67932. * wasmUrl: "<url to the WebAssembly library>",
  67933. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67934. * fallbackUrl: "<url to the fallback JavaScript library>",
  67935. * }
  67936. * };
  67937. * ```
  67938. *
  67939. * 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.
  67940. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67941. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67942. *
  67943. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67944. * ```javascript
  67945. * var dracoCompression = new BABYLON.DracoCompression();
  67946. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67947. * [BABYLON.VertexBuffer.PositionKind]: 0
  67948. * });
  67949. * ```
  67950. *
  67951. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67952. */
  67953. var DracoCompression = /** @class */ (function () {
  67954. /**
  67955. * Constructor
  67956. */
  67957. function DracoCompression() {
  67958. }
  67959. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67960. /**
  67961. * Returns true if the decoder is available.
  67962. */
  67963. get: function () {
  67964. if (typeof DracoDecoderModule !== "undefined") {
  67965. return true;
  67966. }
  67967. var decoder = DracoCompression.Configuration.decoder;
  67968. if (decoder) {
  67969. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67970. return true;
  67971. }
  67972. if (decoder.fallbackUrl) {
  67973. return true;
  67974. }
  67975. }
  67976. return false;
  67977. },
  67978. enumerable: true,
  67979. configurable: true
  67980. });
  67981. /**
  67982. * Stop all async operations and release resources.
  67983. */
  67984. DracoCompression.prototype.dispose = function () {
  67985. };
  67986. /**
  67987. * Decode Draco compressed mesh data to vertex data.
  67988. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  67989. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  67990. * @returns A promise that resolves with the decoded vertex data
  67991. */
  67992. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  67993. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  67994. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  67995. var module = wrappedModule.module;
  67996. var vertexData = new BABYLON.VertexData();
  67997. var buffer = new module.DecoderBuffer();
  67998. buffer.Init(dataView, dataView.byteLength);
  67999. var decoder = new module.Decoder();
  68000. var geometry;
  68001. var status;
  68002. try {
  68003. var type = decoder.GetEncodedGeometryType(buffer);
  68004. switch (type) {
  68005. case module.TRIANGULAR_MESH:
  68006. geometry = new module.Mesh();
  68007. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68008. break;
  68009. case module.POINT_CLOUD:
  68010. geometry = new module.PointCloud();
  68011. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68012. break;
  68013. default:
  68014. throw new Error("Invalid geometry type " + type);
  68015. }
  68016. if (!status.ok() || !geometry.ptr) {
  68017. throw new Error(status.error_msg());
  68018. }
  68019. var numPoints = geometry.num_points();
  68020. if (type === module.TRIANGULAR_MESH) {
  68021. var numFaces = geometry.num_faces();
  68022. var faceIndices = new module.DracoInt32Array();
  68023. try {
  68024. var indices = new Uint32Array(numFaces * 3);
  68025. for (var i = 0; i < numFaces; i++) {
  68026. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68027. var offset = i * 3;
  68028. indices[offset + 0] = faceIndices.GetValue(0);
  68029. indices[offset + 1] = faceIndices.GetValue(1);
  68030. indices[offset + 2] = faceIndices.GetValue(2);
  68031. }
  68032. vertexData.indices = indices;
  68033. }
  68034. finally {
  68035. module.destroy(faceIndices);
  68036. }
  68037. }
  68038. for (var kind in attributes) {
  68039. var uniqueId = attributes[kind];
  68040. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  68041. var dracoData = new module.DracoFloat32Array();
  68042. try {
  68043. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  68044. var babylonData = new Float32Array(numPoints * attribute.num_components());
  68045. for (var i = 0; i < babylonData.length; i++) {
  68046. babylonData[i] = dracoData.GetValue(i);
  68047. }
  68048. vertexData.set(babylonData, kind);
  68049. }
  68050. finally {
  68051. module.destroy(dracoData);
  68052. }
  68053. }
  68054. }
  68055. finally {
  68056. if (geometry) {
  68057. module.destroy(geometry);
  68058. }
  68059. module.destroy(decoder);
  68060. module.destroy(buffer);
  68061. }
  68062. return vertexData;
  68063. });
  68064. };
  68065. DracoCompression._GetDecoderModule = function () {
  68066. if (!DracoCompression._DecoderModulePromise) {
  68067. var promise = null;
  68068. var config_1 = {};
  68069. if (typeof DracoDecoderModule !== "undefined") {
  68070. promise = Promise.resolve();
  68071. }
  68072. else {
  68073. var decoder = DracoCompression.Configuration.decoder;
  68074. if (decoder) {
  68075. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68076. promise = Promise.all([
  68077. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  68078. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  68079. config_1.wasmBinary = data;
  68080. })
  68081. ]);
  68082. }
  68083. else if (decoder.fallbackUrl) {
  68084. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  68085. }
  68086. }
  68087. }
  68088. if (!promise) {
  68089. throw new Error("Draco decoder module is not available");
  68090. }
  68091. DracoCompression._DecoderModulePromise = promise.then(function () {
  68092. return new Promise(function (resolve) {
  68093. config_1.onModuleLoaded = function (decoderModule) {
  68094. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  68095. resolve({ module: decoderModule });
  68096. };
  68097. DracoDecoderModule(config_1);
  68098. });
  68099. });
  68100. }
  68101. return DracoCompression._DecoderModulePromise;
  68102. };
  68103. DracoCompression._LoadScriptAsync = function (url) {
  68104. return new Promise(function (resolve, reject) {
  68105. BABYLON.Tools.LoadScript(url, function () {
  68106. resolve();
  68107. }, function (message) {
  68108. reject(new Error(message));
  68109. });
  68110. });
  68111. };
  68112. DracoCompression._LoadFileAsync = function (url) {
  68113. return new Promise(function (resolve, reject) {
  68114. BABYLON.Tools.LoadFile(url, function (data) {
  68115. resolve(data);
  68116. }, undefined, undefined, true, function (request, exception) {
  68117. reject(exception);
  68118. });
  68119. });
  68120. };
  68121. /**
  68122. * The configuration. Defaults to the following urls:
  68123. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  68124. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  68125. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68126. */
  68127. DracoCompression.Configuration = {
  68128. decoder: {
  68129. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  68130. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  68131. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68132. }
  68133. };
  68134. return DracoCompression;
  68135. }());
  68136. BABYLON.DracoCompression = DracoCompression;
  68137. })(BABYLON || (BABYLON = {}));
  68138. //# sourceMappingURL=babylon.dracoCompression.js.map
  68139. var BABYLON;
  68140. (function (BABYLON) {
  68141. // Sets the default audio engine to Babylon JS.
  68142. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  68143. /**
  68144. * This represents the default audio engine used in babylon.
  68145. * It is responsible to play, synchronize and analyse sounds throughout the application.
  68146. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68147. */
  68148. var AudioEngine = /** @class */ (function () {
  68149. /**
  68150. * Instantiates a new audio engine.
  68151. *
  68152. * There should be only one per page as some browsers restrict the number
  68153. * of audio contexts you can create.
  68154. * @param engine defines the hosting engine
  68155. */
  68156. function AudioEngine(engine) {
  68157. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  68158. var _this = this;
  68159. this._audioContext = null;
  68160. this._audioContextInitialized = false;
  68161. this._muteButton = null;
  68162. /**
  68163. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  68164. */
  68165. this.canUseWebAudio = false;
  68166. /**
  68167. * Defines if Babylon should emit a warning if WebAudio is not supported.
  68168. * @ignoreNaming
  68169. */
  68170. this.WarnedWebAudioUnsupported = false;
  68171. /**
  68172. * Gets whether or not mp3 are supported by your browser.
  68173. */
  68174. this.isMP3supported = false;
  68175. /**
  68176. * Gets whether or not ogg are supported by your browser.
  68177. */
  68178. this.isOGGsupported = false;
  68179. /**
  68180. * Gets whether audio has been unlocked on the device.
  68181. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  68182. * a user interaction has happened.
  68183. */
  68184. this.unlocked = true;
  68185. /**
  68186. * Defines if the audio engine relies on a custom unlocked button.
  68187. * In this case, the embedded button will not be displayed.
  68188. */
  68189. this.useCustomUnlockedButton = false;
  68190. /**
  68191. * Event raised when audio has been unlocked on the browser.
  68192. */
  68193. this.onAudioUnlockedObservable = new BABYLON.Observable();
  68194. /**
  68195. * Event raised when audio has been locked on the browser.
  68196. */
  68197. this.onAudioLockedObservable = new BABYLON.Observable();
  68198. this._tryToRun = false;
  68199. this._onResize = function () {
  68200. _this._moveButtonToTopLeft();
  68201. };
  68202. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  68203. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  68204. this.canUseWebAudio = true;
  68205. }
  68206. var audioElem = document.createElement('audio');
  68207. this._engine = engine;
  68208. try {
  68209. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  68210. this.isMP3supported = true;
  68211. }
  68212. }
  68213. catch (e) {
  68214. // protect error during capability check.
  68215. }
  68216. try {
  68217. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  68218. this.isOGGsupported = true;
  68219. }
  68220. }
  68221. catch (e) {
  68222. // protect error during capability check.
  68223. }
  68224. }
  68225. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  68226. /**
  68227. * Gets the current AudioContext if available.
  68228. */
  68229. get: function () {
  68230. if (!this._audioContextInitialized) {
  68231. this._initializeAudioContext();
  68232. }
  68233. else {
  68234. if (!this.unlocked && !this._muteButton) {
  68235. this._displayMuteButton();
  68236. }
  68237. }
  68238. return this._audioContext;
  68239. },
  68240. enumerable: true,
  68241. configurable: true
  68242. });
  68243. /**
  68244. * Flags the audio engine in Locked state.
  68245. * This happens due to new browser policies preventing audio to autoplay.
  68246. */
  68247. AudioEngine.prototype.lock = function () {
  68248. this._triggerSuspendedState();
  68249. };
  68250. /**
  68251. * Unlocks the audio engine once a user action has been done on the dom.
  68252. * This is helpful to resume play once browser policies have been satisfied.
  68253. */
  68254. AudioEngine.prototype.unlock = function () {
  68255. this._triggerRunningState();
  68256. };
  68257. AudioEngine.prototype._resumeAudioContext = function () {
  68258. var result;
  68259. if (this._audioContext.resume) {
  68260. result = this._audioContext.resume();
  68261. }
  68262. return result || Promise.resolve();
  68263. };
  68264. AudioEngine.prototype._initializeAudioContext = function () {
  68265. var _this = this;
  68266. try {
  68267. if (this.canUseWebAudio) {
  68268. this._audioContext = new AudioContext();
  68269. // create a global volume gain node
  68270. this.masterGain = this._audioContext.createGain();
  68271. this.masterGain.gain.value = 1;
  68272. this.masterGain.connect(this._audioContext.destination);
  68273. this._audioContextInitialized = true;
  68274. if (this._audioContext.state === "running") {
  68275. // Do not wait for the promise to unlock.
  68276. this._triggerRunningState();
  68277. }
  68278. else {
  68279. if (this._audioContext && this._audioContext.resume) {
  68280. this._resumeAudioContext().then(function () {
  68281. _this._triggerRunningState();
  68282. }).catch(function () {
  68283. // Can not resume automatically
  68284. // Needs user action
  68285. _this.lock();
  68286. });
  68287. }
  68288. }
  68289. }
  68290. }
  68291. catch (e) {
  68292. this.canUseWebAudio = false;
  68293. BABYLON.Tools.Error("Web Audio: " + e.message);
  68294. }
  68295. };
  68296. AudioEngine.prototype._triggerRunningState = function () {
  68297. var _this = this;
  68298. if (this._tryToRun) {
  68299. return;
  68300. }
  68301. this._tryToRun = true;
  68302. this._resumeAudioContext()
  68303. .then(function () {
  68304. _this._tryToRun = false;
  68305. _this.unlocked = true;
  68306. if (_this._muteButton) {
  68307. _this._hideMuteButton();
  68308. }
  68309. // Notify users that the audio stack is unlocked/unmuted
  68310. _this.onAudioUnlockedObservable.notifyObservers(_this);
  68311. }).catch(function () {
  68312. _this._tryToRun = false;
  68313. _this.unlocked = false;
  68314. });
  68315. };
  68316. AudioEngine.prototype._triggerSuspendedState = function () {
  68317. this.unlocked = false;
  68318. this.onAudioLockedObservable.notifyObservers(this);
  68319. this._displayMuteButton();
  68320. };
  68321. AudioEngine.prototype._displayMuteButton = function () {
  68322. var _this = this;
  68323. if (this.useCustomUnlockedButton) {
  68324. return;
  68325. }
  68326. this._canvas = this._engine.getRenderingCanvas();
  68327. this._muteButton = document.createElement("BUTTON");
  68328. this._muteButton.className = "babylonUnmuteIcon";
  68329. this._muteButton.id = "babylonUnmuteIconBtn";
  68330. this._muteButton.title = "Unmute";
  68331. 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) }";
  68332. var style = document.createElement('style');
  68333. style.appendChild(document.createTextNode(css));
  68334. document.getElementsByTagName('head')[0].appendChild(style);
  68335. document.body.appendChild(this._muteButton);
  68336. this._moveButtonToTopLeft();
  68337. this._muteButton.addEventListener('mousedown', function () {
  68338. _this._triggerRunningState();
  68339. }, true);
  68340. this._muteButton.addEventListener('touchend', function () {
  68341. _this._triggerRunningState();
  68342. }, true);
  68343. this._muteButton.addEventListener('click', function () {
  68344. _this._triggerRunningState();
  68345. }, true);
  68346. window.addEventListener("resize", this._onResize);
  68347. };
  68348. AudioEngine.prototype._moveButtonToTopLeft = function () {
  68349. if (this._canvas && this._muteButton) {
  68350. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  68351. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  68352. }
  68353. };
  68354. AudioEngine.prototype._hideMuteButton = function () {
  68355. if (this._muteButton) {
  68356. document.body.removeChild(this._muteButton);
  68357. this._muteButton = null;
  68358. }
  68359. };
  68360. /**
  68361. * Destroy and release the resources associated with the audio ccontext.
  68362. */
  68363. AudioEngine.prototype.dispose = function () {
  68364. if (this.canUseWebAudio && this._audioContextInitialized) {
  68365. if (this._connectedAnalyser && this._audioContext) {
  68366. this._connectedAnalyser.stopDebugCanvas();
  68367. this._connectedAnalyser.dispose();
  68368. this.masterGain.disconnect();
  68369. this.masterGain.connect(this._audioContext.destination);
  68370. this._connectedAnalyser = null;
  68371. }
  68372. this.masterGain.gain.value = 1;
  68373. }
  68374. this.WarnedWebAudioUnsupported = false;
  68375. this._hideMuteButton();
  68376. window.removeEventListener("resize", this._onResize);
  68377. this.onAudioUnlockedObservable.clear();
  68378. this.onAudioLockedObservable.clear();
  68379. };
  68380. /**
  68381. * Gets the global volume sets on the master gain.
  68382. * @returns the global volume if set or -1 otherwise
  68383. */
  68384. AudioEngine.prototype.getGlobalVolume = function () {
  68385. if (this.canUseWebAudio && this._audioContextInitialized) {
  68386. return this.masterGain.gain.value;
  68387. }
  68388. else {
  68389. return -1;
  68390. }
  68391. };
  68392. /**
  68393. * Sets the global volume of your experience (sets on the master gain).
  68394. * @param newVolume Defines the new global volume of the application
  68395. */
  68396. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  68397. if (this.canUseWebAudio && this._audioContextInitialized) {
  68398. this.masterGain.gain.value = newVolume;
  68399. }
  68400. };
  68401. /**
  68402. * Connect the audio engine to an audio analyser allowing some amazing
  68403. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68404. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68405. * @param analyser The analyser to connect to the engine
  68406. */
  68407. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  68408. if (this._connectedAnalyser) {
  68409. this._connectedAnalyser.stopDebugCanvas();
  68410. }
  68411. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  68412. this._connectedAnalyser = analyser;
  68413. this.masterGain.disconnect();
  68414. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  68415. }
  68416. };
  68417. return AudioEngine;
  68418. }());
  68419. BABYLON.AudioEngine = AudioEngine;
  68420. })(BABYLON || (BABYLON = {}));
  68421. //# sourceMappingURL=babylon.audioEngine.js.map
  68422. var BABYLON;
  68423. (function (BABYLON) {
  68424. /**
  68425. * Defines a sound that can be played in the application.
  68426. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  68427. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68428. */
  68429. var Sound = /** @class */ (function () {
  68430. /**
  68431. * Create a sound and attach it to a scene
  68432. * @param name Name of your sound
  68433. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  68434. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  68435. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  68436. */
  68437. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  68438. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  68439. var _this = this;
  68440. /**
  68441. * Does the sound autoplay once loaded.
  68442. */
  68443. this.autoplay = false;
  68444. /**
  68445. * Does the sound loop after it finishes playing once.
  68446. */
  68447. this.loop = false;
  68448. /**
  68449. * Does the sound use a custom attenuation curve to simulate the falloff
  68450. * happening when the source gets further away from the camera.
  68451. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68452. */
  68453. this.useCustomAttenuation = false;
  68454. /**
  68455. * Is this sound currently played.
  68456. */
  68457. this.isPlaying = false;
  68458. /**
  68459. * Is this sound currently paused.
  68460. */
  68461. this.isPaused = false;
  68462. /**
  68463. * Does this sound enables spatial sound.
  68464. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68465. */
  68466. this.spatialSound = false;
  68467. /**
  68468. * Define the reference distance the sound should be heard perfectly.
  68469. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68470. */
  68471. this.refDistance = 1;
  68472. /**
  68473. * Define the roll off factor of spatial sounds.
  68474. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68475. */
  68476. this.rolloffFactor = 1;
  68477. /**
  68478. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  68479. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68480. */
  68481. this.maxDistance = 100;
  68482. /**
  68483. * Define the distance attenuation model the sound will follow.
  68484. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68485. */
  68486. this.distanceModel = "linear";
  68487. /**
  68488. * Observable event when the current playing sound finishes.
  68489. */
  68490. this.onEndedObservable = new BABYLON.Observable();
  68491. this._panningModel = "equalpower";
  68492. this._playbackRate = 1;
  68493. this._streaming = false;
  68494. this._startTime = 0;
  68495. this._startOffset = 0;
  68496. this._position = BABYLON.Vector3.Zero();
  68497. /** @hidden */
  68498. this._positionInEmitterSpace = false;
  68499. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  68500. this._volume = 1;
  68501. this._isReadyToPlay = false;
  68502. this._isDirectional = false;
  68503. // Used if you'd like to create a directional sound.
  68504. // If not set, the sound will be omnidirectional
  68505. this._coneInnerAngle = 360;
  68506. this._coneOuterAngle = 360;
  68507. this._coneOuterGain = 0;
  68508. this._isOutputConnected = false;
  68509. this._urlType = "Unknown";
  68510. this.name = name;
  68511. this._scene = scene;
  68512. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68513. if (!compo) {
  68514. compo = new BABYLON.AudioSceneComponent(scene);
  68515. scene._addComponent(compo);
  68516. }
  68517. this._readyToPlayCallback = readyToPlayCallback;
  68518. // Default custom attenuation function is a linear attenuation
  68519. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  68520. if (currentDistance < maxDistance) {
  68521. return currentVolume * (1 - currentDistance / maxDistance);
  68522. }
  68523. else {
  68524. return 0;
  68525. }
  68526. };
  68527. if (options) {
  68528. this.autoplay = options.autoplay || false;
  68529. this.loop = options.loop || false;
  68530. // if volume === 0, we need another way to check this option
  68531. if (options.volume !== undefined) {
  68532. this._volume = options.volume;
  68533. }
  68534. this.spatialSound = options.spatialSound || false;
  68535. this.maxDistance = options.maxDistance || 100;
  68536. this.useCustomAttenuation = options.useCustomAttenuation || false;
  68537. this.rolloffFactor = options.rolloffFactor || 1;
  68538. this.refDistance = options.refDistance || 1;
  68539. this.distanceModel = options.distanceModel || "linear";
  68540. this._playbackRate = options.playbackRate || 1;
  68541. this._streaming = options.streaming || false;
  68542. }
  68543. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68544. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  68545. this._soundGain.gain.value = this._volume;
  68546. this._inputAudioNode = this._soundGain;
  68547. this._outputAudioNode = this._soundGain;
  68548. if (this.spatialSound) {
  68549. this._createSpatialParameters();
  68550. }
  68551. this._scene.mainSoundTrack.AddSound(this);
  68552. var validParameter = true;
  68553. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  68554. if (urlOrArrayBuffer) {
  68555. try {
  68556. if (typeof (urlOrArrayBuffer) === "string") {
  68557. this._urlType = "String";
  68558. }
  68559. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  68560. this._urlType = "ArrayBuffer";
  68561. }
  68562. else if (urlOrArrayBuffer instanceof MediaStream) {
  68563. this._urlType = "MediaStream";
  68564. }
  68565. else if (Array.isArray(urlOrArrayBuffer)) {
  68566. this._urlType = "Array";
  68567. }
  68568. var urls = [];
  68569. var codecSupportedFound = false;
  68570. switch (this._urlType) {
  68571. case "MediaStream":
  68572. this._streaming = true;
  68573. this._isReadyToPlay = true;
  68574. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  68575. if (this.autoplay) {
  68576. this.play();
  68577. }
  68578. if (this._readyToPlayCallback) {
  68579. this._readyToPlayCallback();
  68580. }
  68581. break;
  68582. case "ArrayBuffer":
  68583. if (urlOrArrayBuffer.byteLength > 0) {
  68584. codecSupportedFound = true;
  68585. this._soundLoaded(urlOrArrayBuffer);
  68586. }
  68587. break;
  68588. case "String":
  68589. urls.push(urlOrArrayBuffer);
  68590. case "Array":
  68591. if (urls.length === 0)
  68592. urls = urlOrArrayBuffer;
  68593. // If we found a supported format, we load it immediately and stop the loop
  68594. for (var i = 0; i < urls.length; i++) {
  68595. var url = urls[i];
  68596. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  68597. codecSupportedFound = true;
  68598. }
  68599. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  68600. codecSupportedFound = true;
  68601. }
  68602. if (url.indexOf(".wav", url.length - 4) !== -1) {
  68603. codecSupportedFound = true;
  68604. }
  68605. if (url.indexOf("blob:") !== -1) {
  68606. codecSupportedFound = true;
  68607. }
  68608. if (codecSupportedFound) {
  68609. // Loading sound using XHR2
  68610. if (!this._streaming) {
  68611. this._scene._loadFile(url, function (data) {
  68612. _this._soundLoaded(data);
  68613. }, undefined, true, true, function (exception) {
  68614. if (exception) {
  68615. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  68616. }
  68617. BABYLON.Tools.Error("Sound creation aborted.");
  68618. _this._scene.mainSoundTrack.RemoveSound(_this);
  68619. });
  68620. }
  68621. // Streaming sound using HTML5 Audio tag
  68622. else {
  68623. this._htmlAudioElement = new Audio(url);
  68624. this._htmlAudioElement.controls = false;
  68625. this._htmlAudioElement.loop = this.loop;
  68626. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  68627. this._htmlAudioElement.preload = "auto";
  68628. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  68629. _this._isReadyToPlay = true;
  68630. if (_this.autoplay) {
  68631. _this.play();
  68632. }
  68633. if (_this._readyToPlayCallback) {
  68634. _this._readyToPlayCallback();
  68635. }
  68636. });
  68637. document.body.appendChild(this._htmlAudioElement);
  68638. this._htmlAudioElement.load();
  68639. }
  68640. break;
  68641. }
  68642. }
  68643. break;
  68644. default:
  68645. validParameter = false;
  68646. break;
  68647. }
  68648. if (!validParameter) {
  68649. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  68650. }
  68651. else {
  68652. if (!codecSupportedFound) {
  68653. this._isReadyToPlay = true;
  68654. // Simulating a ready to play event to avoid breaking code path
  68655. if (this._readyToPlayCallback) {
  68656. window.setTimeout(function () {
  68657. if (_this._readyToPlayCallback) {
  68658. _this._readyToPlayCallback();
  68659. }
  68660. }, 1000);
  68661. }
  68662. }
  68663. }
  68664. }
  68665. catch (ex) {
  68666. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  68667. this._scene.mainSoundTrack.RemoveSound(this);
  68668. }
  68669. }
  68670. }
  68671. else {
  68672. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68673. this._scene.mainSoundTrack.AddSound(this);
  68674. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68675. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68676. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68677. }
  68678. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68679. if (this._readyToPlayCallback) {
  68680. window.setTimeout(function () {
  68681. if (_this._readyToPlayCallback) {
  68682. _this._readyToPlayCallback();
  68683. }
  68684. }, 1000);
  68685. }
  68686. }
  68687. }
  68688. /**
  68689. * Release the sound and its associated resources
  68690. */
  68691. Sound.prototype.dispose = function () {
  68692. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68693. if (this.isPlaying) {
  68694. this.stop();
  68695. }
  68696. this._isReadyToPlay = false;
  68697. if (this.soundTrackId === -1) {
  68698. this._scene.mainSoundTrack.RemoveSound(this);
  68699. }
  68700. else if (this._scene.soundTracks) {
  68701. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68702. }
  68703. if (this._soundGain) {
  68704. this._soundGain.disconnect();
  68705. this._soundGain = null;
  68706. }
  68707. if (this._soundPanner) {
  68708. this._soundPanner.disconnect();
  68709. this._soundPanner = null;
  68710. }
  68711. if (this._soundSource) {
  68712. this._soundSource.disconnect();
  68713. this._soundSource = null;
  68714. }
  68715. this._audioBuffer = null;
  68716. if (this._htmlAudioElement) {
  68717. this._htmlAudioElement.pause();
  68718. this._htmlAudioElement.src = "";
  68719. document.body.removeChild(this._htmlAudioElement);
  68720. }
  68721. if (this._streamingSource) {
  68722. this._streamingSource.disconnect();
  68723. }
  68724. if (this._connectedMesh && this._registerFunc) {
  68725. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68726. this._connectedMesh = null;
  68727. }
  68728. }
  68729. };
  68730. /**
  68731. * Gets if the sounds is ready to be played or not.
  68732. * @returns true if ready, otherwise false
  68733. */
  68734. Sound.prototype.isReady = function () {
  68735. return this._isReadyToPlay;
  68736. };
  68737. Sound.prototype._soundLoaded = function (audioData) {
  68738. var _this = this;
  68739. if (!BABYLON.Engine.audioEngine.audioContext) {
  68740. return;
  68741. }
  68742. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  68743. _this._audioBuffer = buffer;
  68744. _this._isReadyToPlay = true;
  68745. if (_this.autoplay) {
  68746. _this.play();
  68747. }
  68748. if (_this._readyToPlayCallback) {
  68749. _this._readyToPlayCallback();
  68750. }
  68751. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  68752. };
  68753. /**
  68754. * Sets the data of the sound from an audiobuffer
  68755. * @param audioBuffer The audioBuffer containing the data
  68756. */
  68757. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  68758. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68759. this._audioBuffer = audioBuffer;
  68760. this._isReadyToPlay = true;
  68761. }
  68762. };
  68763. /**
  68764. * Updates the current sounds options such as maxdistance, loop...
  68765. * @param options A JSON object containing values named as the object properties
  68766. */
  68767. Sound.prototype.updateOptions = function (options) {
  68768. if (options) {
  68769. this.loop = options.loop || this.loop;
  68770. this.maxDistance = options.maxDistance || this.maxDistance;
  68771. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  68772. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  68773. this.refDistance = options.refDistance || this.refDistance;
  68774. this.distanceModel = options.distanceModel || this.distanceModel;
  68775. this._playbackRate = options.playbackRate || this._playbackRate;
  68776. this._updateSpatialParameters();
  68777. if (this.isPlaying) {
  68778. if (this._streaming && this._htmlAudioElement) {
  68779. this._htmlAudioElement.playbackRate = this._playbackRate;
  68780. }
  68781. else {
  68782. if (this._soundSource) {
  68783. this._soundSource.playbackRate.value = this._playbackRate;
  68784. }
  68785. }
  68786. }
  68787. }
  68788. };
  68789. Sound.prototype._createSpatialParameters = function () {
  68790. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68791. if (this._scene.headphone) {
  68792. this._panningModel = "HRTF";
  68793. }
  68794. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  68795. this._updateSpatialParameters();
  68796. this._soundPanner.connect(this._outputAudioNode);
  68797. this._inputAudioNode = this._soundPanner;
  68798. }
  68799. };
  68800. Sound.prototype._updateSpatialParameters = function () {
  68801. if (this.spatialSound && this._soundPanner) {
  68802. if (this.useCustomAttenuation) {
  68803. // Tricks to disable in a way embedded Web Audio attenuation
  68804. this._soundPanner.distanceModel = "linear";
  68805. this._soundPanner.maxDistance = Number.MAX_VALUE;
  68806. this._soundPanner.refDistance = 1;
  68807. this._soundPanner.rolloffFactor = 1;
  68808. this._soundPanner.panningModel = this._panningModel;
  68809. }
  68810. else {
  68811. this._soundPanner.distanceModel = this.distanceModel;
  68812. this._soundPanner.maxDistance = this.maxDistance;
  68813. this._soundPanner.refDistance = this.refDistance;
  68814. this._soundPanner.rolloffFactor = this.rolloffFactor;
  68815. this._soundPanner.panningModel = this._panningModel;
  68816. }
  68817. }
  68818. };
  68819. /**
  68820. * Switch the panning model to HRTF:
  68821. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68822. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68823. */
  68824. Sound.prototype.switchPanningModelToHRTF = function () {
  68825. this._panningModel = "HRTF";
  68826. this._switchPanningModel();
  68827. };
  68828. /**
  68829. * Switch the panning model to Equal Power:
  68830. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68831. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68832. */
  68833. Sound.prototype.switchPanningModelToEqualPower = function () {
  68834. this._panningModel = "equalpower";
  68835. this._switchPanningModel();
  68836. };
  68837. Sound.prototype._switchPanningModel = function () {
  68838. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68839. this._soundPanner.panningModel = this._panningModel;
  68840. }
  68841. };
  68842. /**
  68843. * Connect this sound to a sound track audio node like gain...
  68844. * @param soundTrackAudioNode the sound track audio node to connect to
  68845. */
  68846. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  68847. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68848. if (this._isOutputConnected) {
  68849. this._outputAudioNode.disconnect();
  68850. }
  68851. this._outputAudioNode.connect(soundTrackAudioNode);
  68852. this._isOutputConnected = true;
  68853. }
  68854. };
  68855. /**
  68856. * Transform this sound into a directional source
  68857. * @param coneInnerAngle Size of the inner cone in degree
  68858. * @param coneOuterAngle Size of the outer cone in degree
  68859. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  68860. */
  68861. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  68862. if (coneOuterAngle < coneInnerAngle) {
  68863. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  68864. return;
  68865. }
  68866. this._coneInnerAngle = coneInnerAngle;
  68867. this._coneOuterAngle = coneOuterAngle;
  68868. this._coneOuterGain = coneOuterGain;
  68869. this._isDirectional = true;
  68870. if (this.isPlaying && this.loop) {
  68871. this.stop();
  68872. this.play();
  68873. }
  68874. };
  68875. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  68876. /**
  68877. * Gets or sets the inner angle for the directional cone.
  68878. */
  68879. get: function () {
  68880. return this._coneInnerAngle;
  68881. },
  68882. /**
  68883. * Gets or sets the inner angle for the directional cone.
  68884. */
  68885. set: function (value) {
  68886. if (value != this._coneInnerAngle) {
  68887. if (this._coneOuterAngle < value) {
  68888. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68889. return;
  68890. }
  68891. this._coneInnerAngle = value;
  68892. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68893. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68894. }
  68895. }
  68896. },
  68897. enumerable: true,
  68898. configurable: true
  68899. });
  68900. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  68901. /**
  68902. * Gets or sets the outer angle for the directional cone.
  68903. */
  68904. get: function () {
  68905. return this._coneOuterAngle;
  68906. },
  68907. /**
  68908. * Gets or sets the outer angle for the directional cone.
  68909. */
  68910. set: function (value) {
  68911. if (value != this._coneOuterAngle) {
  68912. if (value < this._coneInnerAngle) {
  68913. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68914. return;
  68915. }
  68916. this._coneOuterAngle = value;
  68917. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68918. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68919. }
  68920. }
  68921. },
  68922. enumerable: true,
  68923. configurable: true
  68924. });
  68925. /**
  68926. * Sets the position of the emitter if spatial sound is enabled
  68927. * @param newPosition Defines the new posisiton
  68928. */
  68929. Sound.prototype.setPosition = function (newPosition) {
  68930. this._position = newPosition;
  68931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68932. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68933. }
  68934. };
  68935. /**
  68936. * Sets the local direction of the emitter if spatial sound is enabled
  68937. * @param newLocalDirection Defines the new local direction
  68938. */
  68939. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68940. this._localDirection = newLocalDirection;
  68941. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68942. this._updateDirection();
  68943. }
  68944. };
  68945. Sound.prototype._updateDirection = function () {
  68946. if (!this._connectedMesh || !this._soundPanner) {
  68947. return;
  68948. }
  68949. var mat = this._connectedMesh.getWorldMatrix();
  68950. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68951. direction.normalize();
  68952. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68953. };
  68954. /** @hidden */
  68955. Sound.prototype.updateDistanceFromListener = function () {
  68956. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68957. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68958. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68959. }
  68960. };
  68961. /**
  68962. * Sets a new custom attenuation function for the sound.
  68963. * @param callback Defines the function used for the attenuation
  68964. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68965. */
  68966. Sound.prototype.setAttenuationFunction = function (callback) {
  68967. this._customAttenuationFunction = callback;
  68968. };
  68969. /**
  68970. * Play the sound
  68971. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68972. * @param offset (optional) Start the sound setting it at a specific time
  68973. */
  68974. Sound.prototype.play = function (time, offset) {
  68975. var _this = this;
  68976. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  68977. try {
  68978. if (this._startOffset < 0) {
  68979. time = -this._startOffset;
  68980. this._startOffset = 0;
  68981. }
  68982. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68983. if (!this._soundSource || !this._streamingSource) {
  68984. if (this.spatialSound && this._soundPanner) {
  68985. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68986. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68987. }
  68988. if (this._isDirectional) {
  68989. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68990. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68991. this._soundPanner.coneOuterGain = this._coneOuterGain;
  68992. if (this._connectedMesh) {
  68993. this._updateDirection();
  68994. }
  68995. else {
  68996. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  68997. }
  68998. }
  68999. }
  69000. }
  69001. if (this._streaming) {
  69002. if (!this._streamingSource) {
  69003. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69004. this._htmlAudioElement.onended = function () { _this._onended(); };
  69005. this._htmlAudioElement.playbackRate = this._playbackRate;
  69006. }
  69007. this._streamingSource.disconnect();
  69008. this._streamingSource.connect(this._inputAudioNode);
  69009. if (this._htmlAudioElement) {
  69010. // required to manage properly the new suspended default state of Chrome
  69011. // When the option 'streaming: true' is used, we need first to wait for
  69012. // the audio engine to be unlocked by a user gesture before trying to play
  69013. // an HTML Audio elememt
  69014. var tryToPlay = function () {
  69015. if (BABYLON.Engine.audioEngine.unlocked) {
  69016. var playPromise = _this._htmlAudioElement.play();
  69017. // In browsers that don’t yet support this functionality,
  69018. // playPromise won’t be defined.
  69019. if (playPromise !== undefined) {
  69020. playPromise.catch(function (error) {
  69021. // Automatic playback failed.
  69022. // Waiting for the audio engine to be unlocked by user click on unmute
  69023. BABYLON.Engine.audioEngine.lock();
  69024. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69025. });
  69026. }
  69027. }
  69028. else {
  69029. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69030. }
  69031. };
  69032. tryToPlay();
  69033. }
  69034. }
  69035. else {
  69036. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69037. this._soundSource.buffer = this._audioBuffer;
  69038. this._soundSource.connect(this._inputAudioNode);
  69039. this._soundSource.loop = this.loop;
  69040. this._soundSource.playbackRate.value = this._playbackRate;
  69041. this._soundSource.onended = function () { _this._onended(); };
  69042. if (this._soundSource.buffer) {
  69043. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69044. }
  69045. }
  69046. this._startTime = startTime;
  69047. this.isPlaying = true;
  69048. this.isPaused = false;
  69049. }
  69050. catch (ex) {
  69051. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69052. }
  69053. }
  69054. };
  69055. Sound.prototype._onended = function () {
  69056. this.isPlaying = false;
  69057. if (this.onended) {
  69058. this.onended();
  69059. }
  69060. this.onEndedObservable.notifyObservers(this);
  69061. };
  69062. /**
  69063. * Stop the sound
  69064. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  69065. */
  69066. Sound.prototype.stop = function (time) {
  69067. if (this.isPlaying) {
  69068. if (this._streaming) {
  69069. if (this._htmlAudioElement) {
  69070. this._htmlAudioElement.pause();
  69071. // Test needed for Firefox or it will generate an Invalid State Error
  69072. if (this._htmlAudioElement.currentTime > 0) {
  69073. this._htmlAudioElement.currentTime = 0;
  69074. }
  69075. }
  69076. else {
  69077. this._streamingSource.disconnect();
  69078. }
  69079. }
  69080. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  69081. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69082. this._soundSource.stop(stopTime);
  69083. this._soundSource.onended = function () { };
  69084. if (!this.isPaused) {
  69085. this._startOffset = 0;
  69086. }
  69087. }
  69088. this.isPlaying = false;
  69089. }
  69090. };
  69091. /**
  69092. * Put the sound in pause
  69093. */
  69094. Sound.prototype.pause = function () {
  69095. if (this.isPlaying) {
  69096. this.isPaused = true;
  69097. if (this._streaming) {
  69098. if (this._htmlAudioElement) {
  69099. this._htmlAudioElement.pause();
  69100. }
  69101. else {
  69102. this._streamingSource.disconnect();
  69103. }
  69104. }
  69105. else if (BABYLON.Engine.audioEngine.audioContext) {
  69106. this.stop(0);
  69107. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  69108. }
  69109. }
  69110. };
  69111. /**
  69112. * Sets a dedicated volume for this sounds
  69113. * @param newVolume Define the new volume of the sound
  69114. * @param time Define in how long the sound should be at this value
  69115. */
  69116. Sound.prototype.setVolume = function (newVolume, time) {
  69117. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  69118. if (time && BABYLON.Engine.audioEngine.audioContext) {
  69119. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  69120. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  69121. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  69122. }
  69123. else {
  69124. this._soundGain.gain.value = newVolume;
  69125. }
  69126. }
  69127. this._volume = newVolume;
  69128. };
  69129. /**
  69130. * Set the sound play back rate
  69131. * @param newPlaybackRate Define the playback rate the sound should be played at
  69132. */
  69133. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  69134. this._playbackRate = newPlaybackRate;
  69135. if (this.isPlaying) {
  69136. if (this._streaming && this._htmlAudioElement) {
  69137. this._htmlAudioElement.playbackRate = this._playbackRate;
  69138. }
  69139. else if (this._soundSource) {
  69140. this._soundSource.playbackRate.value = this._playbackRate;
  69141. }
  69142. }
  69143. };
  69144. /**
  69145. * Gets the volume of the sound.
  69146. * @returns the volume of the sound
  69147. */
  69148. Sound.prototype.getVolume = function () {
  69149. return this._volume;
  69150. };
  69151. /**
  69152. * Attach the sound to a dedicated mesh
  69153. * @param meshToConnectTo The mesh to connect the sound with
  69154. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69155. */
  69156. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  69157. var _this = this;
  69158. if (this._connectedMesh && this._registerFunc) {
  69159. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69160. this._registerFunc = null;
  69161. }
  69162. this._connectedMesh = meshToConnectTo;
  69163. if (!this.spatialSound) {
  69164. this.spatialSound = true;
  69165. this._createSpatialParameters();
  69166. if (this.isPlaying && this.loop) {
  69167. this.stop();
  69168. this.play();
  69169. }
  69170. }
  69171. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  69172. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  69173. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  69174. };
  69175. /**
  69176. * Detach the sound from the previously attached mesh
  69177. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69178. */
  69179. Sound.prototype.detachFromMesh = function () {
  69180. if (this._connectedMesh && this._registerFunc) {
  69181. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69182. this._registerFunc = null;
  69183. this._connectedMesh = null;
  69184. }
  69185. };
  69186. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  69187. if (!node.getBoundingInfo) {
  69188. return;
  69189. }
  69190. var mesh = node;
  69191. if (this._positionInEmitterSpace) {
  69192. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  69193. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  69194. }
  69195. else {
  69196. var boundingInfo = mesh.getBoundingInfo();
  69197. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  69198. }
  69199. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  69200. this._updateDirection();
  69201. }
  69202. };
  69203. /**
  69204. * Clone the current sound in the scene.
  69205. * @returns the new sound clone
  69206. */
  69207. Sound.prototype.clone = function () {
  69208. var _this = this;
  69209. if (!this._streaming) {
  69210. var setBufferAndRun = function () {
  69211. if (_this._isReadyToPlay) {
  69212. clonedSound._audioBuffer = _this.getAudioBuffer();
  69213. clonedSound._isReadyToPlay = true;
  69214. if (clonedSound.autoplay) {
  69215. clonedSound.play();
  69216. }
  69217. }
  69218. else {
  69219. window.setTimeout(setBufferAndRun, 300);
  69220. }
  69221. };
  69222. var currentOptions = {
  69223. autoplay: this.autoplay, loop: this.loop,
  69224. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  69225. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  69226. refDistance: this.refDistance, distanceModel: this.distanceModel
  69227. };
  69228. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  69229. if (this.useCustomAttenuation) {
  69230. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  69231. }
  69232. clonedSound.setPosition(this._position);
  69233. clonedSound.setPlaybackRate(this._playbackRate);
  69234. setBufferAndRun();
  69235. return clonedSound;
  69236. }
  69237. // Can't clone a streaming sound
  69238. else {
  69239. return null;
  69240. }
  69241. };
  69242. /**
  69243. * Gets the current underlying audio buffer containing the data
  69244. * @returns the audio buffer
  69245. */
  69246. Sound.prototype.getAudioBuffer = function () {
  69247. return this._audioBuffer;
  69248. };
  69249. /**
  69250. * Serializes the Sound in a JSON representation
  69251. * @returns the JSON representation of the sound
  69252. */
  69253. Sound.prototype.serialize = function () {
  69254. var serializationObject = {
  69255. name: this.name,
  69256. url: this.name,
  69257. autoplay: this.autoplay,
  69258. loop: this.loop,
  69259. volume: this._volume,
  69260. spatialSound: this.spatialSound,
  69261. maxDistance: this.maxDistance,
  69262. rolloffFactor: this.rolloffFactor,
  69263. refDistance: this.refDistance,
  69264. distanceModel: this.distanceModel,
  69265. playbackRate: this._playbackRate,
  69266. panningModel: this._panningModel,
  69267. soundTrackId: this.soundTrackId
  69268. };
  69269. if (this.spatialSound) {
  69270. if (this._connectedMesh)
  69271. serializationObject.connectedMeshId = this._connectedMesh.id;
  69272. serializationObject.position = this._position.asArray();
  69273. serializationObject.refDistance = this.refDistance;
  69274. serializationObject.distanceModel = this.distanceModel;
  69275. serializationObject.isDirectional = this._isDirectional;
  69276. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  69277. serializationObject.coneInnerAngle = this._coneInnerAngle;
  69278. serializationObject.coneOuterAngle = this._coneOuterAngle;
  69279. serializationObject.coneOuterGain = this._coneOuterGain;
  69280. }
  69281. return serializationObject;
  69282. };
  69283. /**
  69284. * Parse a JSON representation of a sound to innstantiate in a given scene
  69285. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  69286. * @param scene Define the scene the new parsed sound should be created in
  69287. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  69288. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  69289. * @returns the newly parsed sound
  69290. */
  69291. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  69292. var soundName = parsedSound.name;
  69293. var soundUrl;
  69294. if (parsedSound.url) {
  69295. soundUrl = rootUrl + parsedSound.url;
  69296. }
  69297. else {
  69298. soundUrl = rootUrl + soundName;
  69299. }
  69300. var options = {
  69301. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  69302. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  69303. rolloffFactor: parsedSound.rolloffFactor,
  69304. refDistance: parsedSound.refDistance,
  69305. distanceModel: parsedSound.distanceModel,
  69306. playbackRate: parsedSound.playbackRate
  69307. };
  69308. var newSound;
  69309. if (!sourceSound) {
  69310. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  69311. scene._addPendingData(newSound);
  69312. }
  69313. else {
  69314. var setBufferAndRun = function () {
  69315. if (sourceSound._isReadyToPlay) {
  69316. newSound._audioBuffer = sourceSound.getAudioBuffer();
  69317. newSound._isReadyToPlay = true;
  69318. if (newSound.autoplay) {
  69319. newSound.play();
  69320. }
  69321. }
  69322. else {
  69323. window.setTimeout(setBufferAndRun, 300);
  69324. }
  69325. };
  69326. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  69327. setBufferAndRun();
  69328. }
  69329. if (parsedSound.position) {
  69330. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  69331. newSound.setPosition(soundPosition);
  69332. }
  69333. if (parsedSound.isDirectional) {
  69334. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  69335. if (parsedSound.localDirectionToMesh) {
  69336. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  69337. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  69338. }
  69339. }
  69340. if (parsedSound.connectedMeshId) {
  69341. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  69342. if (connectedMesh) {
  69343. newSound.attachToMesh(connectedMesh);
  69344. }
  69345. }
  69346. return newSound;
  69347. };
  69348. return Sound;
  69349. }());
  69350. BABYLON.Sound = Sound;
  69351. })(BABYLON || (BABYLON = {}));
  69352. //# sourceMappingURL=babylon.sound.js.map
  69353. var BABYLON;
  69354. (function (BABYLON) {
  69355. /**
  69356. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  69357. * It will be also used in a future release to apply effects on a specific track.
  69358. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69359. */
  69360. var SoundTrack = /** @class */ (function () {
  69361. /**
  69362. * Creates a new sound track.
  69363. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69364. * @param scene Define the scene the sound track belongs to
  69365. * @param options
  69366. */
  69367. function SoundTrack(scene, options) {
  69368. if (options === void 0) { options = {}; }
  69369. /**
  69370. * The unique identifier of the sound track in the scene.
  69371. */
  69372. this.id = -1;
  69373. this._isMainTrack = false;
  69374. this._isInitialized = false;
  69375. this._scene = scene;
  69376. this.soundCollection = new Array();
  69377. this._options = options;
  69378. if (!this._isMainTrack && this._scene.soundTracks) {
  69379. this._scene.soundTracks.push(this);
  69380. this.id = this._scene.soundTracks.length - 1;
  69381. }
  69382. }
  69383. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  69384. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69385. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  69386. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  69387. if (this._options) {
  69388. if (this._options.volume) {
  69389. this._outputAudioNode.gain.value = this._options.volume;
  69390. }
  69391. if (this._options.mainTrack) {
  69392. this._isMainTrack = this._options.mainTrack;
  69393. }
  69394. }
  69395. this._isInitialized = true;
  69396. }
  69397. };
  69398. /**
  69399. * Release the sound track and its associated resources
  69400. */
  69401. SoundTrack.prototype.dispose = function () {
  69402. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  69403. if (this._connectedAnalyser) {
  69404. this._connectedAnalyser.stopDebugCanvas();
  69405. }
  69406. while (this.soundCollection.length) {
  69407. this.soundCollection[0].dispose();
  69408. }
  69409. if (this._outputAudioNode) {
  69410. this._outputAudioNode.disconnect();
  69411. }
  69412. this._outputAudioNode = null;
  69413. }
  69414. };
  69415. /**
  69416. * Adds a sound to this sound track
  69417. * @param sound define the cound to add
  69418. * @ignoreNaming
  69419. */
  69420. SoundTrack.prototype.AddSound = function (sound) {
  69421. if (!this._isInitialized) {
  69422. this._initializeSoundTrackAudioGraph();
  69423. }
  69424. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69425. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  69426. }
  69427. if (sound.soundTrackId) {
  69428. if (sound.soundTrackId === -1) {
  69429. this._scene.mainSoundTrack.RemoveSound(sound);
  69430. }
  69431. else if (this._scene.soundTracks) {
  69432. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  69433. }
  69434. }
  69435. this.soundCollection.push(sound);
  69436. sound.soundTrackId = this.id;
  69437. };
  69438. /**
  69439. * Removes a sound to this sound track
  69440. * @param sound define the cound to remove
  69441. * @ignoreNaming
  69442. */
  69443. SoundTrack.prototype.RemoveSound = function (sound) {
  69444. var index = this.soundCollection.indexOf(sound);
  69445. if (index !== -1) {
  69446. this.soundCollection.splice(index, 1);
  69447. }
  69448. };
  69449. /**
  69450. * Set a global volume for the full sound track.
  69451. * @param newVolume Define the new volume of the sound track
  69452. */
  69453. SoundTrack.prototype.setVolume = function (newVolume) {
  69454. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69455. this._outputAudioNode.gain.value = newVolume;
  69456. }
  69457. };
  69458. /**
  69459. * Switch the panning model to HRTF:
  69460. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69461. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69462. */
  69463. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  69464. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69465. for (var i = 0; i < this.soundCollection.length; i++) {
  69466. this.soundCollection[i].switchPanningModelToHRTF();
  69467. }
  69468. }
  69469. };
  69470. /**
  69471. * Switch the panning model to Equal Power:
  69472. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69473. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69474. */
  69475. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  69476. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69477. for (var i = 0; i < this.soundCollection.length; i++) {
  69478. this.soundCollection[i].switchPanningModelToEqualPower();
  69479. }
  69480. }
  69481. };
  69482. /**
  69483. * Connect the sound track to an audio analyser allowing some amazing
  69484. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69485. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69486. * @param analyser The analyser to connect to the engine
  69487. */
  69488. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  69489. if (this._connectedAnalyser) {
  69490. this._connectedAnalyser.stopDebugCanvas();
  69491. }
  69492. this._connectedAnalyser = analyser;
  69493. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69494. this._outputAudioNode.disconnect();
  69495. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  69496. }
  69497. };
  69498. return SoundTrack;
  69499. }());
  69500. BABYLON.SoundTrack = SoundTrack;
  69501. })(BABYLON || (BABYLON = {}));
  69502. //# sourceMappingURL=babylon.soundtrack.js.map
  69503. var BABYLON;
  69504. (function (BABYLON) {
  69505. /**
  69506. * Class used to work with sound analyzer using fast fourier transform (FFT)
  69507. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69508. */
  69509. var Analyser = /** @class */ (function () {
  69510. /**
  69511. * Creates a new analyser
  69512. * @param scene defines hosting scene
  69513. */
  69514. function Analyser(scene) {
  69515. /**
  69516. * Gets or sets the smoothing
  69517. * @ignorenaming
  69518. */
  69519. this.SMOOTHING = 0.75;
  69520. /**
  69521. * Gets or sets the FFT table size
  69522. * @ignorenaming
  69523. */
  69524. this.FFT_SIZE = 512;
  69525. /**
  69526. * Gets or sets the bar graph amplitude
  69527. * @ignorenaming
  69528. */
  69529. this.BARGRAPHAMPLITUDE = 256;
  69530. /**
  69531. * Gets or sets the position of the debug canvas
  69532. * @ignorenaming
  69533. */
  69534. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  69535. /**
  69536. * Gets or sets the debug canvas size
  69537. * @ignorenaming
  69538. */
  69539. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  69540. this._scene = scene;
  69541. this._audioEngine = BABYLON.Engine.audioEngine;
  69542. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  69543. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  69544. this._webAudioAnalyser.minDecibels = -140;
  69545. this._webAudioAnalyser.maxDecibels = 0;
  69546. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69547. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69548. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  69549. }
  69550. }
  69551. /**
  69552. * Get the number of data values you will have to play with for the visualization
  69553. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  69554. * @returns a number
  69555. */
  69556. Analyser.prototype.getFrequencyBinCount = function () {
  69557. if (this._audioEngine.canUseWebAudio) {
  69558. return this._webAudioAnalyser.frequencyBinCount;
  69559. }
  69560. else {
  69561. return 0;
  69562. }
  69563. };
  69564. /**
  69565. * Gets the current frequency data as a byte array
  69566. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69567. * @returns a Uint8Array
  69568. */
  69569. Analyser.prototype.getByteFrequencyData = function () {
  69570. if (this._audioEngine.canUseWebAudio) {
  69571. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69572. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69573. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  69574. }
  69575. return this._byteFreqs;
  69576. };
  69577. /**
  69578. * Gets the current waveform as a byte array
  69579. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  69580. * @returns a Uint8Array
  69581. */
  69582. Analyser.prototype.getByteTimeDomainData = function () {
  69583. if (this._audioEngine.canUseWebAudio) {
  69584. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69585. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69586. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  69587. }
  69588. return this._byteTime;
  69589. };
  69590. /**
  69591. * Gets the current frequency data as a float array
  69592. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69593. * @returns a Float32Array
  69594. */
  69595. Analyser.prototype.getFloatFrequencyData = function () {
  69596. if (this._audioEngine.canUseWebAudio) {
  69597. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69598. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69599. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  69600. }
  69601. return this._floatFreqs;
  69602. };
  69603. /**
  69604. * Renders the debug canvas
  69605. */
  69606. Analyser.prototype.drawDebugCanvas = function () {
  69607. var _this = this;
  69608. if (this._audioEngine.canUseWebAudio) {
  69609. if (!this._debugCanvas) {
  69610. this._debugCanvas = document.createElement("canvas");
  69611. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  69612. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  69613. this._debugCanvas.style.position = "absolute";
  69614. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  69615. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  69616. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  69617. document.body.appendChild(this._debugCanvas);
  69618. this._registerFunc = function () {
  69619. _this.drawDebugCanvas();
  69620. };
  69621. this._scene.registerBeforeRender(this._registerFunc);
  69622. }
  69623. if (this._registerFunc && this._debugCanvasContext) {
  69624. var workingArray = this.getByteFrequencyData();
  69625. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  69626. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  69627. // Draw the frequency domain chart.
  69628. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  69629. var value = workingArray[i];
  69630. var percent = value / this.BARGRAPHAMPLITUDE;
  69631. var height = this.DEBUGCANVASSIZE.height * percent;
  69632. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  69633. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  69634. var hue = i / this.getFrequencyBinCount() * 360;
  69635. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  69636. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  69637. }
  69638. }
  69639. }
  69640. };
  69641. /**
  69642. * Stops rendering the debug canvas and removes it
  69643. */
  69644. Analyser.prototype.stopDebugCanvas = function () {
  69645. if (this._debugCanvas) {
  69646. if (this._registerFunc) {
  69647. this._scene.unregisterBeforeRender(this._registerFunc);
  69648. this._registerFunc = null;
  69649. }
  69650. document.body.removeChild(this._debugCanvas);
  69651. this._debugCanvas = null;
  69652. this._debugCanvasContext = null;
  69653. }
  69654. };
  69655. /**
  69656. * Connects two audio nodes
  69657. * @param inputAudioNode defines first node to connect
  69658. * @param outputAudioNode defines second node to connect
  69659. */
  69660. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  69661. if (this._audioEngine.canUseWebAudio) {
  69662. inputAudioNode.connect(this._webAudioAnalyser);
  69663. this._webAudioAnalyser.connect(outputAudioNode);
  69664. }
  69665. };
  69666. /**
  69667. * Releases all associated resources
  69668. */
  69669. Analyser.prototype.dispose = function () {
  69670. if (this._audioEngine.canUseWebAudio) {
  69671. this._webAudioAnalyser.disconnect();
  69672. }
  69673. };
  69674. return Analyser;
  69675. }());
  69676. BABYLON.Analyser = Analyser;
  69677. })(BABYLON || (BABYLON = {}));
  69678. //# sourceMappingURL=babylon.analyser.js.map
  69679. var BABYLON;
  69680. (function (BABYLON) {
  69681. /**
  69682. * Wraps one or more Sound objects and selects one with random weight for playback.
  69683. */
  69684. var WeightedSound = /** @class */ (function () {
  69685. /**
  69686. * Creates a new WeightedSound from the list of sounds given.
  69687. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69688. * @param sounds Array of Sounds that will be selected from.
  69689. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69690. */
  69691. function WeightedSound(loop, sounds, weights) {
  69692. var _this = this;
  69693. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69694. this.loop = false;
  69695. this._coneInnerAngle = 360;
  69696. this._coneOuterAngle = 360;
  69697. this._volume = 1;
  69698. /** A Sound is currently playing. */
  69699. this.isPlaying = false;
  69700. /** A Sound is currently paused. */
  69701. this.isPaused = false;
  69702. this._sounds = [];
  69703. this._weights = [];
  69704. if (sounds.length !== weights.length) {
  69705. throw new Error('Sounds length does not equal weights length');
  69706. }
  69707. this.loop = loop;
  69708. this._weights = weights;
  69709. // Normalize the weights
  69710. var weightSum = 0;
  69711. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  69712. var weight = weights_1[_i];
  69713. weightSum += weight;
  69714. }
  69715. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  69716. for (var i = 0; i < this._weights.length; i++) {
  69717. this._weights[i] *= invWeightSum;
  69718. }
  69719. this._sounds = sounds;
  69720. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  69721. var sound = _b[_a];
  69722. sound.onEndedObservable.add(function () { _this._onended(); });
  69723. }
  69724. }
  69725. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  69726. /**
  69727. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  69728. */
  69729. get: function () {
  69730. return this._coneInnerAngle;
  69731. },
  69732. /**
  69733. * The size of cone in degress for a directional sound in which there will be no attenuation.
  69734. */
  69735. set: function (value) {
  69736. if (value !== this._coneInnerAngle) {
  69737. if (this._coneOuterAngle < value) {
  69738. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69739. return;
  69740. }
  69741. this._coneInnerAngle = value;
  69742. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69743. var sound = _a[_i];
  69744. sound.directionalConeInnerAngle = value;
  69745. }
  69746. }
  69747. },
  69748. enumerable: true,
  69749. configurable: true
  69750. });
  69751. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  69752. /**
  69753. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69754. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69755. */
  69756. get: function () {
  69757. return this._coneOuterAngle;
  69758. },
  69759. /**
  69760. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69761. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69762. */
  69763. set: function (value) {
  69764. if (value !== this._coneOuterAngle) {
  69765. if (value < this._coneInnerAngle) {
  69766. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69767. return;
  69768. }
  69769. this._coneOuterAngle = value;
  69770. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69771. var sound = _a[_i];
  69772. sound.directionalConeOuterAngle = value;
  69773. }
  69774. }
  69775. },
  69776. enumerable: true,
  69777. configurable: true
  69778. });
  69779. Object.defineProperty(WeightedSound.prototype, "volume", {
  69780. /**
  69781. * Playback volume.
  69782. */
  69783. get: function () {
  69784. return this._volume;
  69785. },
  69786. /**
  69787. * Playback volume.
  69788. */
  69789. set: function (value) {
  69790. if (value !== this._volume) {
  69791. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69792. var sound = _a[_i];
  69793. sound.setVolume(value);
  69794. }
  69795. }
  69796. },
  69797. enumerable: true,
  69798. configurable: true
  69799. });
  69800. WeightedSound.prototype._onended = function () {
  69801. if (this._currentIndex !== undefined) {
  69802. this._sounds[this._currentIndex].autoplay = false;
  69803. }
  69804. if (this.loop && this.isPlaying) {
  69805. this.play();
  69806. }
  69807. else {
  69808. this.isPlaying = false;
  69809. }
  69810. };
  69811. /**
  69812. * Suspend playback
  69813. */
  69814. WeightedSound.prototype.pause = function () {
  69815. this.isPaused = true;
  69816. if (this._currentIndex !== undefined) {
  69817. this._sounds[this._currentIndex].pause();
  69818. }
  69819. };
  69820. /**
  69821. * Stop playback
  69822. */
  69823. WeightedSound.prototype.stop = function () {
  69824. this.isPlaying = false;
  69825. if (this._currentIndex !== undefined) {
  69826. this._sounds[this._currentIndex].stop();
  69827. }
  69828. };
  69829. /**
  69830. * Start playback.
  69831. * @param startOffset Position the clip head at a specific time in seconds.
  69832. */
  69833. WeightedSound.prototype.play = function (startOffset) {
  69834. if (!this.isPaused) {
  69835. this.stop();
  69836. var randomValue = Math.random();
  69837. var total = 0;
  69838. for (var i = 0; i < this._weights.length; i++) {
  69839. total += this._weights[i];
  69840. if (randomValue <= total) {
  69841. this._currentIndex = i;
  69842. break;
  69843. }
  69844. }
  69845. }
  69846. var sound = this._sounds[this._currentIndex];
  69847. if (sound.isReady()) {
  69848. sound.play(0, this.isPaused ? undefined : startOffset);
  69849. }
  69850. else {
  69851. sound.autoplay = true;
  69852. }
  69853. this.isPlaying = true;
  69854. this.isPaused = false;
  69855. };
  69856. return WeightedSound;
  69857. }());
  69858. BABYLON.WeightedSound = WeightedSound;
  69859. })(BABYLON || (BABYLON = {}));
  69860. //# sourceMappingURL=babylon.weightedsound.js.map
  69861. var BABYLON;
  69862. (function (BABYLON) {
  69863. // Adds the parser to the scene parsers.
  69864. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  69865. // TODO: add sound
  69866. var loadedSounds = [];
  69867. var loadedSound;
  69868. container.sounds = container.sounds || [];
  69869. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69870. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69871. var parsedSound = parsedData.sounds[index];
  69872. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69873. if (!parsedSound.url)
  69874. parsedSound.url = parsedSound.name;
  69875. if (!loadedSounds[parsedSound.url]) {
  69876. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69877. loadedSounds[parsedSound.url] = loadedSound;
  69878. container.sounds.push(loadedSound);
  69879. }
  69880. else {
  69881. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69882. }
  69883. }
  69884. else {
  69885. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69886. }
  69887. }
  69888. }
  69889. loadedSounds = [];
  69890. });
  69891. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  69892. get: function () {
  69893. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69894. if (!compo) {
  69895. compo = new AudioSceneComponent(this);
  69896. this._addComponent(compo);
  69897. }
  69898. if (!this._mainSoundTrack) {
  69899. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  69900. }
  69901. return this._mainSoundTrack;
  69902. },
  69903. enumerable: true,
  69904. configurable: true
  69905. });
  69906. BABYLON.Scene.prototype.getSoundByName = function (name) {
  69907. var index;
  69908. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  69909. if (this.mainSoundTrack.soundCollection[index].name === name) {
  69910. return this.mainSoundTrack.soundCollection[index];
  69911. }
  69912. }
  69913. if (this.soundTracks) {
  69914. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  69915. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  69916. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  69917. return this.soundTracks[sdIndex].soundCollection[index];
  69918. }
  69919. }
  69920. }
  69921. }
  69922. return null;
  69923. };
  69924. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  69925. get: function () {
  69926. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69927. if (!compo) {
  69928. compo = new AudioSceneComponent(this);
  69929. this._addComponent(compo);
  69930. }
  69931. return compo.audioEnabled;
  69932. },
  69933. set: function (value) {
  69934. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69935. if (!compo) {
  69936. compo = new AudioSceneComponent(this);
  69937. this._addComponent(compo);
  69938. }
  69939. if (value) {
  69940. compo.enableAudio();
  69941. }
  69942. else {
  69943. compo.disableAudio();
  69944. }
  69945. },
  69946. enumerable: true,
  69947. configurable: true
  69948. });
  69949. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69950. get: function () {
  69951. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69952. if (!compo) {
  69953. compo = new AudioSceneComponent(this);
  69954. this._addComponent(compo);
  69955. }
  69956. return compo.headphone;
  69957. },
  69958. set: function (value) {
  69959. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69960. if (!compo) {
  69961. compo = new AudioSceneComponent(this);
  69962. this._addComponent(compo);
  69963. }
  69964. if (value) {
  69965. compo.switchAudioModeForHeadphones();
  69966. }
  69967. else {
  69968. compo.switchAudioModeForNormalSpeakers();
  69969. }
  69970. },
  69971. enumerable: true,
  69972. configurable: true
  69973. });
  69974. /**
  69975. * Defines the sound scene component responsible to manage any sounds
  69976. * in a given scene.
  69977. */
  69978. var AudioSceneComponent = /** @class */ (function () {
  69979. /**
  69980. * Creates a new instance of the component for the given scene
  69981. * @param scene Defines the scene to register the component in
  69982. */
  69983. function AudioSceneComponent(scene) {
  69984. /**
  69985. * The component name helpfull to identify the component in the list of scene components.
  69986. */
  69987. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  69988. this._audioEnabled = true;
  69989. this._headphone = false;
  69990. this.scene = scene;
  69991. scene.soundTracks = new Array();
  69992. scene.sounds = new Array();
  69993. }
  69994. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  69995. /**
  69996. * Gets whether audio is enabled or not.
  69997. * Please use related enable/disable method to switch state.
  69998. */
  69999. get: function () {
  70000. return this._audioEnabled;
  70001. },
  70002. enumerable: true,
  70003. configurable: true
  70004. });
  70005. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70006. /**
  70007. * Gets whether audio is outputing to headphone or not.
  70008. * Please use the according Switch methods to change output.
  70009. */
  70010. get: function () {
  70011. return this._headphone;
  70012. },
  70013. enumerable: true,
  70014. configurable: true
  70015. });
  70016. /**
  70017. * Registers the component in a given scene
  70018. */
  70019. AudioSceneComponent.prototype.register = function () {
  70020. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70021. };
  70022. /**
  70023. * Rebuilds the elements related to this component in case of
  70024. * context lost for instance.
  70025. */
  70026. AudioSceneComponent.prototype.rebuild = function () {
  70027. // Nothing to do here. (Not rendering related)
  70028. };
  70029. /**
  70030. * Serializes the component data to the specified json object
  70031. * @param serializationObject The object to serialize to
  70032. */
  70033. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70034. serializationObject.sounds = [];
  70035. if (this.scene.soundTracks) {
  70036. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70037. var soundtrack = this.scene.soundTracks[index];
  70038. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70039. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70040. }
  70041. }
  70042. }
  70043. };
  70044. /**
  70045. * Adds all the element from the container to the scene
  70046. * @param container the container holding the elements
  70047. */
  70048. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70049. var _this = this;
  70050. if (!container.sounds) {
  70051. return;
  70052. }
  70053. container.sounds.forEach(function (sound) {
  70054. sound.play();
  70055. sound.autoplay = true;
  70056. _this.scene.mainSoundTrack.AddSound(sound);
  70057. });
  70058. };
  70059. /**
  70060. * Removes all the elements in the container from the scene
  70061. * @param container contains the elements to remove
  70062. */
  70063. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  70064. var _this = this;
  70065. if (!container.sounds) {
  70066. return;
  70067. }
  70068. container.sounds.forEach(function (sound) {
  70069. sound.stop();
  70070. sound.autoplay = false;
  70071. _this.scene.mainSoundTrack.RemoveSound(sound);
  70072. });
  70073. };
  70074. /**
  70075. * Disposes the component and the associated ressources.
  70076. */
  70077. AudioSceneComponent.prototype.dispose = function () {
  70078. var scene = this.scene;
  70079. if (scene._mainSoundTrack) {
  70080. scene.mainSoundTrack.dispose();
  70081. }
  70082. if (scene.soundTracks) {
  70083. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  70084. scene.soundTracks[scIndex].dispose();
  70085. }
  70086. }
  70087. };
  70088. /**
  70089. * Disables audio in the associated scene.
  70090. */
  70091. AudioSceneComponent.prototype.disableAudio = function () {
  70092. var scene = this.scene;
  70093. this._audioEnabled = false;
  70094. var i;
  70095. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70096. scene.mainSoundTrack.soundCollection[i].pause();
  70097. }
  70098. if (scene.soundTracks) {
  70099. for (i = 0; i < scene.soundTracks.length; i++) {
  70100. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70101. scene.soundTracks[i].soundCollection[j].pause();
  70102. }
  70103. }
  70104. }
  70105. };
  70106. /**
  70107. * Enables audio in the associated scene.
  70108. */
  70109. AudioSceneComponent.prototype.enableAudio = function () {
  70110. var scene = this.scene;
  70111. this._audioEnabled = true;
  70112. var i;
  70113. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70114. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  70115. scene.mainSoundTrack.soundCollection[i].play();
  70116. }
  70117. }
  70118. if (scene.soundTracks) {
  70119. for (i = 0; i < scene.soundTracks.length; i++) {
  70120. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70121. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  70122. scene.soundTracks[i].soundCollection[j].play();
  70123. }
  70124. }
  70125. }
  70126. }
  70127. };
  70128. /**
  70129. * Switch audio to headphone output.
  70130. */
  70131. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  70132. var scene = this.scene;
  70133. this._headphone = true;
  70134. scene.mainSoundTrack.switchPanningModelToHRTF();
  70135. if (scene.soundTracks) {
  70136. for (var i = 0; i < scene.soundTracks.length; i++) {
  70137. scene.soundTracks[i].switchPanningModelToHRTF();
  70138. }
  70139. }
  70140. };
  70141. /**
  70142. * Switch audio to normal speakers.
  70143. */
  70144. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  70145. var scene = this.scene;
  70146. this._headphone = false;
  70147. scene.mainSoundTrack.switchPanningModelToEqualPower();
  70148. if (scene.soundTracks) {
  70149. for (var i = 0; i < scene.soundTracks.length; i++) {
  70150. scene.soundTracks[i].switchPanningModelToEqualPower();
  70151. }
  70152. }
  70153. };
  70154. AudioSceneComponent.prototype._afterRender = function () {
  70155. var scene = this.scene;
  70156. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  70157. return;
  70158. }
  70159. var listeningCamera;
  70160. var audioEngine = BABYLON.Engine.audioEngine;
  70161. if (scene.activeCameras.length > 0) {
  70162. listeningCamera = scene.activeCameras[0];
  70163. }
  70164. else {
  70165. listeningCamera = scene.activeCamera;
  70166. }
  70167. if (listeningCamera && audioEngine.audioContext) {
  70168. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  70169. // for VR cameras
  70170. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  70171. listeningCamera = listeningCamera.rigCameras[0];
  70172. }
  70173. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  70174. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  70175. cameraDirection.normalize();
  70176. // To avoid some errors on GearVR
  70177. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  70178. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  70179. }
  70180. var i;
  70181. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70182. var sound = scene.mainSoundTrack.soundCollection[i];
  70183. if (sound.useCustomAttenuation) {
  70184. sound.updateDistanceFromListener();
  70185. }
  70186. }
  70187. if (scene.soundTracks) {
  70188. for (i = 0; i < scene.soundTracks.length; i++) {
  70189. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70190. sound = scene.soundTracks[i].soundCollection[j];
  70191. if (sound.useCustomAttenuation) {
  70192. sound.updateDistanceFromListener();
  70193. }
  70194. }
  70195. }
  70196. }
  70197. }
  70198. };
  70199. return AudioSceneComponent;
  70200. }());
  70201. BABYLON.AudioSceneComponent = AudioSceneComponent;
  70202. })(BABYLON || (BABYLON = {}));
  70203. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  70204. var BABYLON;
  70205. (function (BABYLON) {
  70206. /**
  70207. * This defines an action helpful to play a defined sound on a triggered action.
  70208. */
  70209. var PlaySoundAction = /** @class */ (function (_super) {
  70210. __extends(PlaySoundAction, _super);
  70211. /**
  70212. * Instantiate the action
  70213. * @param triggerOptions defines the trigger options
  70214. * @param sound defines the sound to play
  70215. * @param condition defines the trigger related conditions
  70216. */
  70217. function PlaySoundAction(triggerOptions, sound, condition) {
  70218. var _this = _super.call(this, triggerOptions, condition) || this;
  70219. _this._sound = sound;
  70220. return _this;
  70221. }
  70222. /** @hidden */
  70223. PlaySoundAction.prototype._prepare = function () {
  70224. };
  70225. /**
  70226. * Execute the action and play the sound.
  70227. */
  70228. PlaySoundAction.prototype.execute = function () {
  70229. if (this._sound !== undefined)
  70230. this._sound.play();
  70231. };
  70232. /**
  70233. * Serializes the actions and its related information.
  70234. * @param parent defines the object to serialize in
  70235. * @returns the serialized object
  70236. */
  70237. PlaySoundAction.prototype.serialize = function (parent) {
  70238. return _super.prototype._serialize.call(this, {
  70239. name: "PlaySoundAction",
  70240. properties: [{ name: "sound", value: this._sound.name }]
  70241. }, parent);
  70242. };
  70243. return PlaySoundAction;
  70244. }(BABYLON.Action));
  70245. BABYLON.PlaySoundAction = PlaySoundAction;
  70246. /**
  70247. * This defines an action helpful to stop a defined sound on a triggered action.
  70248. */
  70249. var StopSoundAction = /** @class */ (function (_super) {
  70250. __extends(StopSoundAction, _super);
  70251. /**
  70252. * Instantiate the action
  70253. * @param triggerOptions defines the trigger options
  70254. * @param sound defines the sound to stop
  70255. * @param condition defines the trigger related conditions
  70256. */
  70257. function StopSoundAction(triggerOptions, sound, condition) {
  70258. var _this = _super.call(this, triggerOptions, condition) || this;
  70259. _this._sound = sound;
  70260. return _this;
  70261. }
  70262. /** @hidden */
  70263. StopSoundAction.prototype._prepare = function () {
  70264. };
  70265. /**
  70266. * Execute the action and stop the sound.
  70267. */
  70268. StopSoundAction.prototype.execute = function () {
  70269. if (this._sound !== undefined)
  70270. this._sound.stop();
  70271. };
  70272. /**
  70273. * Serializes the actions and its related information.
  70274. * @param parent defines the object to serialize in
  70275. * @returns the serialized object
  70276. */
  70277. StopSoundAction.prototype.serialize = function (parent) {
  70278. return _super.prototype._serialize.call(this, {
  70279. name: "StopSoundAction",
  70280. properties: [{ name: "sound", value: this._sound.name }]
  70281. }, parent);
  70282. };
  70283. return StopSoundAction;
  70284. }(BABYLON.Action));
  70285. BABYLON.StopSoundAction = StopSoundAction;
  70286. })(BABYLON || (BABYLON = {}));
  70287. //# sourceMappingURL=babylon.directAudioActions.js.map
  70288. var BABYLON;
  70289. (function (BABYLON) {
  70290. /**
  70291. * Class for creating a cube texture
  70292. */
  70293. var CubeTexture = /** @class */ (function (_super) {
  70294. __extends(CubeTexture, _super);
  70295. /**
  70296. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  70297. * as prefiltered data.
  70298. * @param rootUrl defines the url of the texture or the root name of the six images
  70299. * @param scene defines the scene the texture is attached to
  70300. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  70301. * @param noMipmap defines if mipmaps should be created or not
  70302. * @param files defines the six files to load for the different faces
  70303. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  70304. * @param onError defines a callback triggered in case of error during load
  70305. * @param format defines the internal format to use for the texture once loaded
  70306. * @param prefiltered defines whether or not the texture is created from prefiltered data
  70307. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  70308. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70309. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70310. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70311. * @return the cube texture
  70312. */
  70313. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  70314. if (extensions === void 0) { extensions = null; }
  70315. if (noMipmap === void 0) { noMipmap = false; }
  70316. if (files === void 0) { files = null; }
  70317. if (onLoad === void 0) { onLoad = null; }
  70318. if (onError === void 0) { onError = null; }
  70319. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70320. if (prefiltered === void 0) { prefiltered = false; }
  70321. if (forcedExtension === void 0) { forcedExtension = null; }
  70322. if (createPolynomials === void 0) { createPolynomials = false; }
  70323. if (lodScale === void 0) { lodScale = 0.8; }
  70324. if (lodOffset === void 0) { lodOffset = 0; }
  70325. var _this = _super.call(this, scene) || this;
  70326. /**
  70327. * Gets or sets the center of the bounding box associated with the cube texture.
  70328. * It must define where the camera used to render the texture was set
  70329. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70330. */
  70331. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70332. _this._rotationY = 0;
  70333. /** @hidden */
  70334. _this._prefiltered = false;
  70335. _this.name = rootUrl;
  70336. _this.url = rootUrl;
  70337. _this._noMipmap = noMipmap;
  70338. _this.hasAlpha = false;
  70339. _this._format = format;
  70340. _this.isCube = true;
  70341. _this._textureMatrix = BABYLON.Matrix.Identity();
  70342. _this._createPolynomials = createPolynomials;
  70343. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70344. if (!rootUrl && !files) {
  70345. return _this;
  70346. }
  70347. var lastDot = rootUrl.lastIndexOf(".");
  70348. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  70349. var isDDS = (extension === ".dds");
  70350. var isEnv = (extension === ".env");
  70351. if (isEnv) {
  70352. _this.gammaSpace = false;
  70353. _this._prefiltered = false;
  70354. }
  70355. else {
  70356. _this._prefiltered = prefiltered;
  70357. if (prefiltered) {
  70358. _this.gammaSpace = false;
  70359. }
  70360. }
  70361. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  70362. if (!files) {
  70363. if (!isEnv && !isDDS && !extensions) {
  70364. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  70365. }
  70366. files = [];
  70367. if (extensions) {
  70368. for (var index = 0; index < extensions.length; index++) {
  70369. files.push(rootUrl + extensions[index]);
  70370. }
  70371. }
  70372. }
  70373. _this._files = files;
  70374. if (!_this._texture) {
  70375. if (!scene.useDelayedTextureLoading) {
  70376. if (prefiltered) {
  70377. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  70378. }
  70379. else {
  70380. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  70381. }
  70382. }
  70383. else {
  70384. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70385. }
  70386. }
  70387. else if (onLoad) {
  70388. if (_this._texture.isReady) {
  70389. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  70390. }
  70391. else {
  70392. _this._texture.onLoadedObservable.add(onLoad);
  70393. }
  70394. }
  70395. return _this;
  70396. }
  70397. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  70398. /**
  70399. * Returns the bounding box size
  70400. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70401. */
  70402. get: function () {
  70403. return this._boundingBoxSize;
  70404. },
  70405. /**
  70406. * Gets or sets the size of the bounding box associated with the cube texture
  70407. * When defined, the cubemap will switch to local mode
  70408. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70409. * @example https://www.babylonjs-playground.com/#RNASML
  70410. */
  70411. set: function (value) {
  70412. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70413. return;
  70414. }
  70415. this._boundingBoxSize = value;
  70416. var scene = this.getScene();
  70417. if (scene) {
  70418. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70419. }
  70420. },
  70421. enumerable: true,
  70422. configurable: true
  70423. });
  70424. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  70425. /**
  70426. * Gets texture matrix rotation angle around Y axis radians.
  70427. */
  70428. get: function () {
  70429. return this._rotationY;
  70430. },
  70431. /**
  70432. * Sets texture matrix rotation angle around Y axis in radians.
  70433. */
  70434. set: function (value) {
  70435. this._rotationY = value;
  70436. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  70437. },
  70438. enumerable: true,
  70439. configurable: true
  70440. });
  70441. /**
  70442. * Creates a cube texture from an array of image urls
  70443. * @param files defines an array of image urls
  70444. * @param scene defines the hosting scene
  70445. * @param noMipmap specifies if mip maps are not used
  70446. * @returns a cube texture
  70447. */
  70448. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  70449. var rootUrlKey = "";
  70450. files.forEach(function (url) { return rootUrlKey += url; });
  70451. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  70452. };
  70453. /**
  70454. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  70455. * @param url defines the url of the prefiltered texture
  70456. * @param scene defines the scene the texture is attached to
  70457. * @param forcedExtension defines the extension of the file if different from the url
  70458. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70459. * @return the prefiltered texture
  70460. */
  70461. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  70462. if (forcedExtension === void 0) { forcedExtension = null; }
  70463. if (createPolynomials === void 0) { createPolynomials = true; }
  70464. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  70465. };
  70466. /**
  70467. * Delays loading of the cube texture
  70468. */
  70469. CubeTexture.prototype.delayLoad = function () {
  70470. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70471. return;
  70472. }
  70473. var scene = this.getScene();
  70474. if (!scene) {
  70475. return;
  70476. }
  70477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70478. this._texture = this._getFromCache(this.url, this._noMipmap);
  70479. if (!this._texture) {
  70480. if (this._prefiltered) {
  70481. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  70482. }
  70483. else {
  70484. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  70485. }
  70486. }
  70487. };
  70488. /**
  70489. * Returns the reflection texture matrix
  70490. * @returns the reflection texture matrix
  70491. */
  70492. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  70493. return this._textureMatrix;
  70494. };
  70495. /**
  70496. * Sets the reflection texture matrix
  70497. * @param value Reflection texture matrix
  70498. */
  70499. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70500. this._textureMatrix = value;
  70501. };
  70502. /**
  70503. * Parses text to create a cube texture
  70504. * @param parsedTexture define the serialized text to read from
  70505. * @param scene defines the hosting scene
  70506. * @param rootUrl defines the root url of the cube texture
  70507. * @returns a cube texture
  70508. */
  70509. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70510. var texture = BABYLON.SerializationHelper.Parse(function () {
  70511. var prefiltered = false;
  70512. if (parsedTexture.prefiltered) {
  70513. prefiltered = parsedTexture.prefiltered;
  70514. }
  70515. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  70516. }, parsedTexture, scene);
  70517. // Local Cubemaps
  70518. if (parsedTexture.boundingBoxPosition) {
  70519. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  70520. }
  70521. if (parsedTexture.boundingBoxSize) {
  70522. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  70523. }
  70524. // Animations
  70525. if (parsedTexture.animations) {
  70526. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  70527. var parsedAnimation = parsedTexture.animations[animationIndex];
  70528. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70529. }
  70530. }
  70531. return texture;
  70532. };
  70533. /**
  70534. * Makes a clone, or deep copy, of the cube texture
  70535. * @returns a new cube texture
  70536. */
  70537. CubeTexture.prototype.clone = function () {
  70538. var _this = this;
  70539. return BABYLON.SerializationHelper.Clone(function () {
  70540. var scene = _this.getScene();
  70541. if (!scene) {
  70542. return _this;
  70543. }
  70544. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  70545. }, this);
  70546. };
  70547. __decorate([
  70548. BABYLON.serialize("rotationY")
  70549. ], CubeTexture.prototype, "rotationY", null);
  70550. return CubeTexture;
  70551. }(BABYLON.BaseTexture));
  70552. BABYLON.CubeTexture = CubeTexture;
  70553. })(BABYLON || (BABYLON = {}));
  70554. //# sourceMappingURL=babylon.cubeTexture.js.map
  70555. var BABYLON;
  70556. (function (BABYLON) {
  70557. /**
  70558. * Raw cube texture where the raw buffers are passed in
  70559. */
  70560. var RawCubeTexture = /** @class */ (function (_super) {
  70561. __extends(RawCubeTexture, _super);
  70562. /**
  70563. * Creates a cube texture where the raw buffers are passed in.
  70564. * @param scene defines the scene the texture is attached to
  70565. * @param data defines the array of data to use to create each face
  70566. * @param size defines the size of the textures
  70567. * @param format defines the format of the data
  70568. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  70569. * @param generateMipMaps defines if the engine should generate the mip levels
  70570. * @param invertY defines if data must be stored with Y axis inverted
  70571. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  70572. * @param compression defines the compression used (null by default)
  70573. */
  70574. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  70575. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70576. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70577. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70578. if (invertY === void 0) { invertY = false; }
  70579. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70580. if (compression === void 0) { compression = null; }
  70581. var _this = _super.call(this, "", scene) || this;
  70582. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  70583. return _this;
  70584. }
  70585. /**
  70586. * Updates the raw cube texture.
  70587. * @param data defines the data to store
  70588. * @param format defines the data format
  70589. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  70590. * @param invertY defines if data must be stored with Y axis inverted
  70591. * @param compression defines the compression used (null by default)
  70592. * @param level defines which level of the texture to update
  70593. */
  70594. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  70595. if (compression === void 0) { compression = null; }
  70596. if (level === void 0) { level = 0; }
  70597. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  70598. };
  70599. /**
  70600. * Updates a raw cube texture with RGBD encoded data.
  70601. * @param data defines the array of data [mipmap][face] to use to create each face
  70602. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  70603. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70604. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70605. * @returns a promsie that resolves when the operation is complete
  70606. */
  70607. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  70608. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  70609. if (lodScale === void 0) { lodScale = 0.8; }
  70610. if (lodOffset === void 0) { lodOffset = 0; }
  70611. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  70612. };
  70613. /**
  70614. * Clones the raw cube texture.
  70615. * @return a new cube texture
  70616. */
  70617. RawCubeTexture.prototype.clone = function () {
  70618. var _this = this;
  70619. return BABYLON.SerializationHelper.Clone(function () {
  70620. var scene = _this.getScene();
  70621. var internalTexture = _this._texture;
  70622. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  70623. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  70624. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  70625. }
  70626. return texture;
  70627. }, this);
  70628. };
  70629. /** @hidden */
  70630. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  70631. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  70632. internalTexture._bufferViewArrayArray = data;
  70633. internalTexture._lodGenerationScale = lodScale;
  70634. internalTexture._lodGenerationOffset = lodOffset;
  70635. internalTexture._sphericalPolynomial = sphericalPolynomial;
  70636. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  70637. internalTexture.isReady = true;
  70638. });
  70639. };
  70640. return RawCubeTexture;
  70641. }(BABYLON.CubeTexture));
  70642. BABYLON.RawCubeTexture = RawCubeTexture;
  70643. })(BABYLON || (BABYLON = {}));
  70644. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  70645. var BABYLON;
  70646. (function (BABYLON) {
  70647. var RenderTargetTexture = /** @class */ (function (_super) {
  70648. __extends(RenderTargetTexture, _super);
  70649. /**
  70650. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  70651. * or used a shadow, depth texture...
  70652. * @param name The friendly name of the texture
  70653. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  70654. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  70655. * @param generateMipMaps True if mip maps need to be generated after render.
  70656. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  70657. * @param type The type of the buffer in the RTT (int, half float, float...)
  70658. * @param isCube True if a cube texture needs to be created
  70659. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  70660. * @param generateDepthBuffer True to generate a depth buffer
  70661. * @param generateStencilBuffer True to generate a stencil buffer
  70662. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  70663. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  70664. */
  70665. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  70666. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  70667. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70668. if (isCube === void 0) { isCube = false; }
  70669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70670. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70671. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  70672. if (isMulti === void 0) { isMulti = false; }
  70673. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70674. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70675. _this.isCube = isCube;
  70676. _this.renderParticles = true;
  70677. _this.renderSprites = false;
  70678. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  70679. _this.ignoreCameraViewport = false;
  70680. // Events
  70681. /**
  70682. * An event triggered when the texture is unbind.
  70683. */
  70684. _this.onBeforeBindObservable = new BABYLON.Observable();
  70685. /**
  70686. * An event triggered when the texture is unbind.
  70687. */
  70688. _this.onAfterUnbindObservable = new BABYLON.Observable();
  70689. /**
  70690. * An event triggered before rendering the texture
  70691. */
  70692. _this.onBeforeRenderObservable = new BABYLON.Observable();
  70693. /**
  70694. * An event triggered after rendering the texture
  70695. */
  70696. _this.onAfterRenderObservable = new BABYLON.Observable();
  70697. /**
  70698. * An event triggered after the texture clear
  70699. */
  70700. _this.onClearObservable = new BABYLON.Observable();
  70701. _this._currentRefreshId = -1;
  70702. _this._refreshRate = 1;
  70703. _this._samples = 1;
  70704. /**
  70705. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70706. * It must define where the camera used to render the texture is set
  70707. */
  70708. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70709. scene = _this.getScene();
  70710. if (!scene) {
  70711. return _this;
  70712. }
  70713. _this.renderList = new Array();
  70714. _this._engine = scene.getEngine();
  70715. _this.name = name;
  70716. _this.isRenderTarget = true;
  70717. _this._initialSizeParameter = size;
  70718. _this._processSizeParameter(size);
  70719. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  70720. });
  70721. _this._generateMipMaps = generateMipMaps ? true : false;
  70722. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  70723. // Rendering groups
  70724. _this._renderingManager = new BABYLON.RenderingManager(scene);
  70725. _this._renderingManager._useSceneAutoClearSetup = true;
  70726. if (isMulti) {
  70727. return _this;
  70728. }
  70729. _this._renderTargetOptions = {
  70730. generateMipMaps: generateMipMaps,
  70731. type: type,
  70732. format: format,
  70733. samplingMode: samplingMode,
  70734. generateDepthBuffer: generateDepthBuffer,
  70735. generateStencilBuffer: generateStencilBuffer
  70736. };
  70737. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  70738. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70739. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70740. }
  70741. if (isCube) {
  70742. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  70743. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  70744. _this._textureMatrix = BABYLON.Matrix.Identity();
  70745. }
  70746. else {
  70747. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  70748. }
  70749. return _this;
  70750. }
  70751. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  70752. get: function () {
  70753. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  70754. },
  70755. enumerable: true,
  70756. configurable: true
  70757. });
  70758. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  70759. get: function () {
  70760. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  70761. },
  70762. enumerable: true,
  70763. configurable: true
  70764. });
  70765. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  70766. get: function () {
  70767. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  70768. },
  70769. enumerable: true,
  70770. configurable: true
  70771. });
  70772. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  70773. /**
  70774. * Use this list to define the list of mesh you want to render.
  70775. */
  70776. get: function () {
  70777. return this._renderList;
  70778. },
  70779. set: function (value) {
  70780. this._renderList = value;
  70781. if (this._renderList) {
  70782. this._hookArray(this._renderList);
  70783. }
  70784. },
  70785. enumerable: true,
  70786. configurable: true
  70787. });
  70788. RenderTargetTexture.prototype._hookArray = function (array) {
  70789. var _this = this;
  70790. var oldPush = array.push;
  70791. array.push = function () {
  70792. var items = [];
  70793. for (var _i = 0; _i < arguments.length; _i++) {
  70794. items[_i] = arguments[_i];
  70795. }
  70796. var wasEmpty = array.length === 0;
  70797. var result = oldPush.apply(array, items);
  70798. if (wasEmpty) {
  70799. _this.getScene().meshes.forEach(function (mesh) {
  70800. mesh._markSubMeshesAsLightDirty();
  70801. });
  70802. }
  70803. return result;
  70804. };
  70805. var oldSplice = array.splice;
  70806. array.splice = function (index, deleteCount) {
  70807. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70808. if (array.length === 0) {
  70809. _this.getScene().meshes.forEach(function (mesh) {
  70810. mesh._markSubMeshesAsLightDirty();
  70811. });
  70812. }
  70813. return deleted;
  70814. };
  70815. };
  70816. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  70817. set: function (callback) {
  70818. if (this._onAfterUnbindObserver) {
  70819. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  70820. }
  70821. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  70822. },
  70823. enumerable: true,
  70824. configurable: true
  70825. });
  70826. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  70827. set: function (callback) {
  70828. if (this._onBeforeRenderObserver) {
  70829. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70830. }
  70831. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70832. },
  70833. enumerable: true,
  70834. configurable: true
  70835. });
  70836. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  70837. set: function (callback) {
  70838. if (this._onAfterRenderObserver) {
  70839. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70840. }
  70841. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70842. },
  70843. enumerable: true,
  70844. configurable: true
  70845. });
  70846. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  70847. set: function (callback) {
  70848. if (this._onClearObserver) {
  70849. this.onClearObservable.remove(this._onClearObserver);
  70850. }
  70851. this._onClearObserver = this.onClearObservable.add(callback);
  70852. },
  70853. enumerable: true,
  70854. configurable: true
  70855. });
  70856. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  70857. get: function () {
  70858. return this._renderTargetOptions;
  70859. },
  70860. enumerable: true,
  70861. configurable: true
  70862. });
  70863. RenderTargetTexture.prototype._onRatioRescale = function () {
  70864. if (this._sizeRatio) {
  70865. this.resize(this._initialSizeParameter);
  70866. }
  70867. };
  70868. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  70869. get: function () {
  70870. return this._boundingBoxSize;
  70871. },
  70872. /**
  70873. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  70874. * When defined, the cubemap will switch to local mode
  70875. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70876. * @example https://www.babylonjs-playground.com/#RNASML
  70877. */
  70878. set: function (value) {
  70879. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70880. return;
  70881. }
  70882. this._boundingBoxSize = value;
  70883. var scene = this.getScene();
  70884. if (scene) {
  70885. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70886. }
  70887. },
  70888. enumerable: true,
  70889. configurable: true
  70890. });
  70891. /**
  70892. * Creates a depth stencil texture.
  70893. * This is only available in WebGL 2 or with the depth texture extension available.
  70894. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  70895. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  70896. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  70897. */
  70898. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  70899. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  70900. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  70901. if (generateStencil === void 0) { generateStencil = false; }
  70902. if (!this.getScene()) {
  70903. return;
  70904. }
  70905. var engine = this.getScene().getEngine();
  70906. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  70907. bilinearFiltering: bilinearFiltering,
  70908. comparisonFunction: comparisonFunction,
  70909. generateStencil: generateStencil,
  70910. isCube: this.isCube
  70911. });
  70912. engine.setFrameBufferDepthStencilTexture(this);
  70913. };
  70914. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  70915. if (size.ratio) {
  70916. this._sizeRatio = size.ratio;
  70917. this._size = {
  70918. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  70919. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  70920. };
  70921. }
  70922. else {
  70923. this._size = size;
  70924. }
  70925. };
  70926. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  70927. get: function () {
  70928. return this._samples;
  70929. },
  70930. set: function (value) {
  70931. if (this._samples === value) {
  70932. return;
  70933. }
  70934. var scene = this.getScene();
  70935. if (!scene) {
  70936. return;
  70937. }
  70938. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  70939. },
  70940. enumerable: true,
  70941. configurable: true
  70942. });
  70943. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  70944. this._currentRefreshId = -1;
  70945. };
  70946. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  70947. get: function () {
  70948. return this._refreshRate;
  70949. },
  70950. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70951. set: function (value) {
  70952. this._refreshRate = value;
  70953. this.resetRefreshCounter();
  70954. },
  70955. enumerable: true,
  70956. configurable: true
  70957. });
  70958. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  70959. if (!this._postProcessManager) {
  70960. var scene = this.getScene();
  70961. if (!scene) {
  70962. return;
  70963. }
  70964. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  70965. this._postProcesses = new Array();
  70966. }
  70967. this._postProcesses.push(postProcess);
  70968. this._postProcesses[0].autoClear = false;
  70969. };
  70970. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70971. if (!this._postProcesses) {
  70972. return;
  70973. }
  70974. if (dispose) {
  70975. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  70976. var postProcess = _a[_i];
  70977. postProcess.dispose();
  70978. }
  70979. }
  70980. this._postProcesses = [];
  70981. };
  70982. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  70983. if (!this._postProcesses) {
  70984. return;
  70985. }
  70986. var index = this._postProcesses.indexOf(postProcess);
  70987. if (index === -1) {
  70988. return;
  70989. }
  70990. this._postProcesses.splice(index, 1);
  70991. if (this._postProcesses.length > 0) {
  70992. this._postProcesses[0].autoClear = false;
  70993. }
  70994. };
  70995. /** @hidden */
  70996. RenderTargetTexture.prototype._shouldRender = function () {
  70997. if (this._currentRefreshId === -1) { // At least render once
  70998. this._currentRefreshId = 1;
  70999. return true;
  71000. }
  71001. if (this.refreshRate === this._currentRefreshId) {
  71002. this._currentRefreshId = 1;
  71003. return true;
  71004. }
  71005. this._currentRefreshId++;
  71006. return false;
  71007. };
  71008. RenderTargetTexture.prototype.getRenderSize = function () {
  71009. if (this._size.width) {
  71010. return this._size.width;
  71011. }
  71012. return this._size;
  71013. };
  71014. RenderTargetTexture.prototype.getRenderWidth = function () {
  71015. if (this._size.width) {
  71016. return this._size.width;
  71017. }
  71018. return this._size;
  71019. };
  71020. RenderTargetTexture.prototype.getRenderHeight = function () {
  71021. if (this._size.width) {
  71022. return this._size.height;
  71023. }
  71024. return this._size;
  71025. };
  71026. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  71027. get: function () {
  71028. return true;
  71029. },
  71030. enumerable: true,
  71031. configurable: true
  71032. });
  71033. RenderTargetTexture.prototype.scale = function (ratio) {
  71034. var newSize = this.getRenderSize() * ratio;
  71035. this.resize(newSize);
  71036. };
  71037. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  71038. if (this.isCube) {
  71039. return this._textureMatrix;
  71040. }
  71041. return _super.prototype.getReflectionTextureMatrix.call(this);
  71042. };
  71043. RenderTargetTexture.prototype.resize = function (size) {
  71044. this.releaseInternalTexture();
  71045. var scene = this.getScene();
  71046. if (!scene) {
  71047. return;
  71048. }
  71049. this._processSizeParameter(size);
  71050. if (this.isCube) {
  71051. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  71052. }
  71053. else {
  71054. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  71055. }
  71056. };
  71057. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  71058. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  71059. if (dumpForDebug === void 0) { dumpForDebug = false; }
  71060. var scene = this.getScene();
  71061. if (!scene) {
  71062. return;
  71063. }
  71064. var engine = scene.getEngine();
  71065. if (this.useCameraPostProcesses !== undefined) {
  71066. useCameraPostProcess = this.useCameraPostProcesses;
  71067. }
  71068. if (this._waitingRenderList) {
  71069. this.renderList = [];
  71070. for (var index = 0; index < this._waitingRenderList.length; index++) {
  71071. var id = this._waitingRenderList[index];
  71072. var mesh_1 = scene.getMeshByID(id);
  71073. if (mesh_1) {
  71074. this.renderList.push(mesh_1);
  71075. }
  71076. }
  71077. delete this._waitingRenderList;
  71078. }
  71079. // Is predicate defined?
  71080. if (this.renderListPredicate) {
  71081. if (this.renderList) {
  71082. this.renderList.splice(0); // Clear previous renderList
  71083. }
  71084. else {
  71085. this.renderList = [];
  71086. }
  71087. var scene = this.getScene();
  71088. if (!scene) {
  71089. return;
  71090. }
  71091. var sceneMeshes = scene.meshes;
  71092. for (var index = 0; index < sceneMeshes.length; index++) {
  71093. var mesh = sceneMeshes[index];
  71094. if (this.renderListPredicate(mesh)) {
  71095. this.renderList.push(mesh);
  71096. }
  71097. }
  71098. }
  71099. this.onBeforeBindObservable.notifyObservers(this);
  71100. // Set custom projection.
  71101. // Needs to be before binding to prevent changing the aspect ratio.
  71102. var camera;
  71103. if (this.activeCamera) {
  71104. camera = this.activeCamera;
  71105. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71106. if (this.activeCamera !== scene.activeCamera) {
  71107. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  71108. }
  71109. }
  71110. else {
  71111. camera = scene.activeCamera;
  71112. if (camera) {
  71113. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71114. }
  71115. }
  71116. // Prepare renderingManager
  71117. this._renderingManager.reset();
  71118. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  71119. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  71120. var sceneRenderId = scene.getRenderId();
  71121. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  71122. var mesh = currentRenderList[meshIndex];
  71123. if (mesh) {
  71124. if (!mesh.isReady(this.refreshRate === 0)) {
  71125. this.resetRefreshCounter();
  71126. continue;
  71127. }
  71128. mesh._preActivateForIntermediateRendering(sceneRenderId);
  71129. var isMasked = void 0;
  71130. if (!this.renderList && camera) {
  71131. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  71132. }
  71133. else {
  71134. isMasked = false;
  71135. }
  71136. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  71137. mesh._activate(sceneRenderId);
  71138. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  71139. var subMesh = mesh.subMeshes[subIndex];
  71140. scene._activeIndices.addCount(subMesh.indexCount, false);
  71141. this._renderingManager.dispatch(subMesh, mesh);
  71142. }
  71143. }
  71144. }
  71145. }
  71146. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  71147. var particleSystem = scene.particleSystems[particleIndex];
  71148. var emitter = particleSystem.emitter;
  71149. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  71150. continue;
  71151. }
  71152. if (currentRenderList.indexOf(emitter) >= 0) {
  71153. this._renderingManager.dispatchParticles(particleSystem);
  71154. }
  71155. }
  71156. if (this.isCube) {
  71157. for (var face = 0; face < 6; face++) {
  71158. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71159. scene.incrementRenderId();
  71160. scene.resetCachedMaterial();
  71161. }
  71162. }
  71163. else {
  71164. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71165. }
  71166. this.onAfterUnbindObservable.notifyObservers(this);
  71167. if (scene.activeCamera) {
  71168. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  71169. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  71170. }
  71171. engine.setViewport(scene.activeCamera.viewport);
  71172. }
  71173. scene.resetCachedMaterial();
  71174. };
  71175. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  71176. var minimum = 128;
  71177. var x = renderDimension * scale;
  71178. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  71179. // Ensure we don't exceed the render dimension (while staying POT)
  71180. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  71181. };
  71182. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71183. var _this = this;
  71184. if (!this._texture) {
  71185. return;
  71186. }
  71187. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  71188. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71189. });
  71190. };
  71191. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  71192. var scene = this.getScene();
  71193. if (!scene) {
  71194. return;
  71195. }
  71196. var engine = scene.getEngine();
  71197. if (!this._texture) {
  71198. return;
  71199. }
  71200. // Bind
  71201. if (this._postProcessManager) {
  71202. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  71203. }
  71204. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  71205. if (this._texture) {
  71206. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  71207. }
  71208. }
  71209. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  71210. // Clear
  71211. if (this.onClearObservable.hasObservers()) {
  71212. this.onClearObservable.notifyObservers(engine);
  71213. }
  71214. else {
  71215. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  71216. }
  71217. if (!this._doNotChangeAspectRatio) {
  71218. scene.updateTransformMatrix(true);
  71219. }
  71220. // Render
  71221. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  71222. if (this._postProcessManager) {
  71223. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  71224. }
  71225. else if (useCameraPostProcess) {
  71226. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  71227. }
  71228. if (!this._doNotChangeAspectRatio) {
  71229. scene.updateTransformMatrix(true);
  71230. }
  71231. // Dump ?
  71232. if (dumpForDebug) {
  71233. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  71234. }
  71235. // Unbind
  71236. if (!this.isCube || faceIndex === 5) {
  71237. if (this.isCube) {
  71238. if (faceIndex === 5) {
  71239. engine.generateMipMapsForCubemap(this._texture);
  71240. }
  71241. }
  71242. this.unbindFrameBuffer(engine, faceIndex);
  71243. }
  71244. else {
  71245. this.onAfterRenderObservable.notifyObservers(faceIndex);
  71246. }
  71247. };
  71248. /**
  71249. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  71250. * This allowed control for front to back rendering or reversly depending of the special needs.
  71251. *
  71252. * @param renderingGroupId The rendering group id corresponding to its index
  71253. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  71254. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  71255. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  71256. */
  71257. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  71258. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  71259. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  71260. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  71261. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  71262. };
  71263. /**
  71264. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71265. *
  71266. * @param renderingGroupId The rendering group id corresponding to its index
  71267. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71268. */
  71269. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71270. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71271. this._renderingManager._useSceneAutoClearSetup = false;
  71272. };
  71273. RenderTargetTexture.prototype.clone = function () {
  71274. var textureSize = this.getSize();
  71275. 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);
  71276. // Base texture
  71277. newTexture.hasAlpha = this.hasAlpha;
  71278. newTexture.level = this.level;
  71279. // RenderTarget Texture
  71280. newTexture.coordinatesMode = this.coordinatesMode;
  71281. if (this.renderList) {
  71282. newTexture.renderList = this.renderList.slice(0);
  71283. }
  71284. return newTexture;
  71285. };
  71286. RenderTargetTexture.prototype.serialize = function () {
  71287. if (!this.name) {
  71288. return null;
  71289. }
  71290. var serializationObject = _super.prototype.serialize.call(this);
  71291. serializationObject.renderTargetSize = this.getRenderSize();
  71292. serializationObject.renderList = [];
  71293. if (this.renderList) {
  71294. for (var index = 0; index < this.renderList.length; index++) {
  71295. serializationObject.renderList.push(this.renderList[index].id);
  71296. }
  71297. }
  71298. return serializationObject;
  71299. };
  71300. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  71301. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  71302. var objBuffer = this.getInternalTexture();
  71303. var scene = this.getScene();
  71304. if (objBuffer && scene) {
  71305. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  71306. }
  71307. };
  71308. RenderTargetTexture.prototype.dispose = function () {
  71309. if (this._postProcessManager) {
  71310. this._postProcessManager.dispose();
  71311. this._postProcessManager = null;
  71312. }
  71313. this.clearPostProcesses(true);
  71314. if (this._resizeObserver) {
  71315. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  71316. this._resizeObserver = null;
  71317. }
  71318. this.renderList = null;
  71319. // Remove from custom render targets
  71320. var scene = this.getScene();
  71321. if (!scene) {
  71322. return;
  71323. }
  71324. var index = scene.customRenderTargets.indexOf(this);
  71325. if (index >= 0) {
  71326. scene.customRenderTargets.splice(index, 1);
  71327. }
  71328. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  71329. var camera = _a[_i];
  71330. index = camera.customRenderTargets.indexOf(this);
  71331. if (index >= 0) {
  71332. camera.customRenderTargets.splice(index, 1);
  71333. }
  71334. }
  71335. _super.prototype.dispose.call(this);
  71336. };
  71337. /** @hidden */
  71338. RenderTargetTexture.prototype._rebuild = function () {
  71339. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71340. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71341. }
  71342. if (this._postProcessManager) {
  71343. this._postProcessManager._rebuild();
  71344. }
  71345. };
  71346. /**
  71347. * Clear the info related to rendering groups preventing retention point in material dispose.
  71348. */
  71349. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  71350. if (this._renderingManager) {
  71351. this._renderingManager.freeRenderingGroups();
  71352. }
  71353. };
  71354. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  71355. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  71356. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  71357. return RenderTargetTexture;
  71358. }(BABYLON.Texture));
  71359. BABYLON.RenderTargetTexture = RenderTargetTexture;
  71360. })(BABYLON || (BABYLON = {}));
  71361. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  71362. var BABYLON;
  71363. (function (BABYLON) {
  71364. ;
  71365. var MultiRenderTarget = /** @class */ (function (_super) {
  71366. __extends(MultiRenderTarget, _super);
  71367. function MultiRenderTarget(name, size, count, scene, options) {
  71368. var _this = this;
  71369. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  71370. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  71371. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  71372. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  71373. _this._engine = scene.getEngine();
  71374. if (!_this.isSupported) {
  71375. _this.dispose();
  71376. return;
  71377. }
  71378. var types = [];
  71379. var samplingModes = [];
  71380. for (var i = 0; i < count; i++) {
  71381. if (options && options.types && options.types[i] !== undefined) {
  71382. types.push(options.types[i]);
  71383. }
  71384. else {
  71385. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71386. }
  71387. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  71388. samplingModes.push(options.samplingModes[i]);
  71389. }
  71390. else {
  71391. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71392. }
  71393. }
  71394. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  71395. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  71396. _this._size = size;
  71397. _this._multiRenderTargetOptions = {
  71398. samplingModes: samplingModes,
  71399. generateMipMaps: generateMipMaps,
  71400. generateDepthBuffer: generateDepthBuffer,
  71401. generateStencilBuffer: generateStencilBuffer,
  71402. generateDepthTexture: generateDepthTexture,
  71403. types: types,
  71404. textureCount: count
  71405. };
  71406. _this._createInternalTextures();
  71407. _this._createTextures();
  71408. return _this;
  71409. }
  71410. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  71411. get: function () {
  71412. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  71413. },
  71414. enumerable: true,
  71415. configurable: true
  71416. });
  71417. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  71418. get: function () {
  71419. return this._textures;
  71420. },
  71421. enumerable: true,
  71422. configurable: true
  71423. });
  71424. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  71425. get: function () {
  71426. return this._textures[this._textures.length - 1];
  71427. },
  71428. enumerable: true,
  71429. configurable: true
  71430. });
  71431. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  71432. set: function (wrap) {
  71433. if (this._textures) {
  71434. for (var i = 0; i < this._textures.length; i++) {
  71435. this._textures[i].wrapU = wrap;
  71436. }
  71437. }
  71438. },
  71439. enumerable: true,
  71440. configurable: true
  71441. });
  71442. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  71443. set: function (wrap) {
  71444. if (this._textures) {
  71445. for (var i = 0; i < this._textures.length; i++) {
  71446. this._textures[i].wrapV = wrap;
  71447. }
  71448. }
  71449. },
  71450. enumerable: true,
  71451. configurable: true
  71452. });
  71453. /** @hidden */
  71454. MultiRenderTarget.prototype._rebuild = function () {
  71455. this.releaseInternalTextures();
  71456. this._createInternalTextures();
  71457. for (var i = 0; i < this._internalTextures.length; i++) {
  71458. var texture = this._textures[i];
  71459. texture._texture = this._internalTextures[i];
  71460. }
  71461. // Keeps references to frame buffer and stencil/depth buffer
  71462. this._texture = this._internalTextures[0];
  71463. };
  71464. MultiRenderTarget.prototype._createInternalTextures = function () {
  71465. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  71466. };
  71467. MultiRenderTarget.prototype._createTextures = function () {
  71468. this._textures = [];
  71469. for (var i = 0; i < this._internalTextures.length; i++) {
  71470. var texture = new BABYLON.Texture(null, this.getScene());
  71471. texture._texture = this._internalTextures[i];
  71472. this._textures.push(texture);
  71473. }
  71474. // Keeps references to frame buffer and stencil/depth buffer
  71475. this._texture = this._internalTextures[0];
  71476. };
  71477. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  71478. get: function () {
  71479. return this._samples;
  71480. },
  71481. set: function (value) {
  71482. if (this._samples === value) {
  71483. return;
  71484. }
  71485. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  71486. },
  71487. enumerable: true,
  71488. configurable: true
  71489. });
  71490. MultiRenderTarget.prototype.resize = function (size) {
  71491. this.releaseInternalTextures();
  71492. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  71493. this._createInternalTextures();
  71494. };
  71495. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71496. var _this = this;
  71497. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  71498. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71499. });
  71500. };
  71501. MultiRenderTarget.prototype.dispose = function () {
  71502. this.releaseInternalTextures();
  71503. _super.prototype.dispose.call(this);
  71504. };
  71505. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  71506. if (!this._internalTextures) {
  71507. return;
  71508. }
  71509. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  71510. if (this._internalTextures[i] !== undefined) {
  71511. this._internalTextures[i].dispose();
  71512. this._internalTextures.splice(i, 1);
  71513. }
  71514. }
  71515. };
  71516. return MultiRenderTarget;
  71517. }(BABYLON.RenderTargetTexture));
  71518. BABYLON.MultiRenderTarget = MultiRenderTarget;
  71519. })(BABYLON || (BABYLON = {}));
  71520. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  71521. var BABYLON;
  71522. (function (BABYLON) {
  71523. var MirrorTexture = /** @class */ (function (_super) {
  71524. __extends(MirrorTexture, _super);
  71525. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  71526. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71528. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71529. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  71530. _this.scene = scene;
  71531. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  71532. _this._transformMatrix = BABYLON.Matrix.Zero();
  71533. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  71534. _this._adaptiveBlurKernel = 0;
  71535. _this._blurKernelX = 0;
  71536. _this._blurKernelY = 0;
  71537. _this._blurRatio = 1.0;
  71538. _this.ignoreCameraViewport = true;
  71539. _this._updateGammaSpace();
  71540. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71541. _this._updateGammaSpace;
  71542. });
  71543. _this.onBeforeRenderObservable.add(function () {
  71544. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  71545. _this._savedViewMatrix = scene.getViewMatrix();
  71546. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  71547. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  71548. scene.clipPlane = _this.mirrorPlane;
  71549. scene.getEngine().cullBackFaces = false;
  71550. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  71551. });
  71552. _this.onAfterRenderObservable.add(function () {
  71553. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  71554. scene.getEngine().cullBackFaces = true;
  71555. scene._mirroredCameraPosition = null;
  71556. delete scene.clipPlane;
  71557. });
  71558. return _this;
  71559. }
  71560. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  71561. get: function () {
  71562. return this._blurRatio;
  71563. },
  71564. set: function (value) {
  71565. if (this._blurRatio === value) {
  71566. return;
  71567. }
  71568. this._blurRatio = value;
  71569. this._preparePostProcesses();
  71570. },
  71571. enumerable: true,
  71572. configurable: true
  71573. });
  71574. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  71575. set: function (value) {
  71576. this._adaptiveBlurKernel = value;
  71577. this._autoComputeBlurKernel();
  71578. },
  71579. enumerable: true,
  71580. configurable: true
  71581. });
  71582. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  71583. set: function (value) {
  71584. this.blurKernelX = value;
  71585. this.blurKernelY = value;
  71586. },
  71587. enumerable: true,
  71588. configurable: true
  71589. });
  71590. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  71591. get: function () {
  71592. return this._blurKernelX;
  71593. },
  71594. set: function (value) {
  71595. if (this._blurKernelX === value) {
  71596. return;
  71597. }
  71598. this._blurKernelX = value;
  71599. this._preparePostProcesses();
  71600. },
  71601. enumerable: true,
  71602. configurable: true
  71603. });
  71604. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  71605. get: function () {
  71606. return this._blurKernelY;
  71607. },
  71608. set: function (value) {
  71609. if (this._blurKernelY === value) {
  71610. return;
  71611. }
  71612. this._blurKernelY = value;
  71613. this._preparePostProcesses();
  71614. },
  71615. enumerable: true,
  71616. configurable: true
  71617. });
  71618. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  71619. var engine = this.getScene().getEngine();
  71620. var dw = this.getRenderWidth() / engine.getRenderWidth();
  71621. var dh = this.getRenderHeight() / engine.getRenderHeight();
  71622. this.blurKernelX = this._adaptiveBlurKernel * dw;
  71623. this.blurKernelY = this._adaptiveBlurKernel * dh;
  71624. };
  71625. MirrorTexture.prototype._onRatioRescale = function () {
  71626. if (this._sizeRatio) {
  71627. this.resize(this._initialSizeParameter);
  71628. if (!this._adaptiveBlurKernel) {
  71629. this._preparePostProcesses();
  71630. }
  71631. }
  71632. if (this._adaptiveBlurKernel) {
  71633. this._autoComputeBlurKernel();
  71634. }
  71635. };
  71636. MirrorTexture.prototype._updateGammaSpace = function () {
  71637. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  71638. };
  71639. MirrorTexture.prototype._preparePostProcesses = function () {
  71640. this.clearPostProcesses(true);
  71641. if (this._blurKernelX && this._blurKernelY) {
  71642. var engine = this.getScene().getEngine();
  71643. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71644. 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);
  71645. this._blurX.autoClear = false;
  71646. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  71647. this._blurX.inputTexture = this._texture;
  71648. }
  71649. else {
  71650. this._blurX.alwaysForcePOT = true;
  71651. }
  71652. 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);
  71653. this._blurY.autoClear = false;
  71654. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  71655. this.addPostProcess(this._blurX);
  71656. this.addPostProcess(this._blurY);
  71657. }
  71658. else {
  71659. if (this._blurY) {
  71660. this.removePostProcess(this._blurY);
  71661. this._blurY.dispose();
  71662. this._blurY = null;
  71663. }
  71664. if (this._blurX) {
  71665. this.removePostProcess(this._blurX);
  71666. this._blurX.dispose();
  71667. this._blurX = null;
  71668. }
  71669. }
  71670. };
  71671. MirrorTexture.prototype.clone = function () {
  71672. var scene = this.getScene();
  71673. if (!scene) {
  71674. return this;
  71675. }
  71676. var textureSize = this.getSize();
  71677. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  71678. // Base texture
  71679. newTexture.hasAlpha = this.hasAlpha;
  71680. newTexture.level = this.level;
  71681. // Mirror Texture
  71682. newTexture.mirrorPlane = this.mirrorPlane.clone();
  71683. if (this.renderList) {
  71684. newTexture.renderList = this.renderList.slice(0);
  71685. }
  71686. return newTexture;
  71687. };
  71688. MirrorTexture.prototype.serialize = function () {
  71689. if (!this.name) {
  71690. return null;
  71691. }
  71692. var serializationObject = _super.prototype.serialize.call(this);
  71693. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  71694. return serializationObject;
  71695. };
  71696. MirrorTexture.prototype.dispose = function () {
  71697. _super.prototype.dispose.call(this);
  71698. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  71699. };
  71700. return MirrorTexture;
  71701. }(BABYLON.RenderTargetTexture));
  71702. BABYLON.MirrorTexture = MirrorTexture;
  71703. })(BABYLON || (BABYLON = {}));
  71704. //# sourceMappingURL=babylon.mirrorTexture.js.map
  71705. var BABYLON;
  71706. (function (BABYLON) {
  71707. /**
  71708. * Creates a refraction texture used by refraction channel of the standard material.
  71709. * @param name the texture name
  71710. * @param size size of the underlying texture
  71711. * @param scene root scene
  71712. */
  71713. var RefractionTexture = /** @class */ (function (_super) {
  71714. __extends(RefractionTexture, _super);
  71715. function RefractionTexture(name, size, scene, generateMipMaps) {
  71716. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  71717. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  71718. _this.depth = 2.0;
  71719. _this.onBeforeRenderObservable.add(function () {
  71720. scene.clipPlane = _this.refractionPlane;
  71721. });
  71722. _this.onAfterRenderObservable.add(function () {
  71723. delete scene.clipPlane;
  71724. });
  71725. return _this;
  71726. }
  71727. RefractionTexture.prototype.clone = function () {
  71728. var scene = this.getScene();
  71729. if (!scene) {
  71730. return this;
  71731. }
  71732. var textureSize = this.getSize();
  71733. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  71734. // Base texture
  71735. newTexture.hasAlpha = this.hasAlpha;
  71736. newTexture.level = this.level;
  71737. // Refraction Texture
  71738. newTexture.refractionPlane = this.refractionPlane.clone();
  71739. if (this.renderList) {
  71740. newTexture.renderList = this.renderList.slice(0);
  71741. }
  71742. newTexture.depth = this.depth;
  71743. return newTexture;
  71744. };
  71745. RefractionTexture.prototype.serialize = function () {
  71746. if (!this.name) {
  71747. return null;
  71748. }
  71749. var serializationObject = _super.prototype.serialize.call(this);
  71750. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  71751. serializationObject.depth = this.depth;
  71752. return serializationObject;
  71753. };
  71754. return RefractionTexture;
  71755. }(BABYLON.RenderTargetTexture));
  71756. BABYLON.RefractionTexture = RefractionTexture;
  71757. })(BABYLON || (BABYLON = {}));
  71758. //# sourceMappingURL=babylon.refractionTexture.js.map
  71759. var BABYLON;
  71760. (function (BABYLON) {
  71761. /**
  71762. * A class extending {BABYLON.Texture} allowing drawing on a texture
  71763. * @see http://doc.babylonjs.com/how_to/dynamictexture
  71764. */
  71765. var DynamicTexture = /** @class */ (function (_super) {
  71766. __extends(DynamicTexture, _super);
  71767. /**
  71768. * Creates a {BABYLON.DynamicTexture}
  71769. * @param name defines the name of the texture
  71770. * @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
  71771. * @param scene defines the scene where you want the texture
  71772. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  71773. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  71774. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  71775. */
  71776. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  71777. if (scene === void 0) { scene = null; }
  71778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71779. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71780. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  71781. _this.name = name;
  71782. _this._engine = _this.getScene().getEngine();
  71783. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71784. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71785. _this._generateMipMaps = generateMipMaps;
  71786. if (options.getContext) {
  71787. _this._canvas = options;
  71788. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71789. }
  71790. else {
  71791. _this._canvas = document.createElement("canvas");
  71792. if (options.width || options.width === 0) {
  71793. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71794. }
  71795. else {
  71796. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  71797. }
  71798. }
  71799. var textureSize = _this.getSize();
  71800. _this._canvas.width = textureSize.width;
  71801. _this._canvas.height = textureSize.height;
  71802. _this._context = _this._canvas.getContext("2d");
  71803. return _this;
  71804. }
  71805. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  71806. /**
  71807. * Gets the current state of canRescale
  71808. */
  71809. get: function () {
  71810. return true;
  71811. },
  71812. enumerable: true,
  71813. configurable: true
  71814. });
  71815. DynamicTexture.prototype._recreate = function (textureSize) {
  71816. this._canvas.width = textureSize.width;
  71817. this._canvas.height = textureSize.height;
  71818. this.releaseInternalTexture();
  71819. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  71820. };
  71821. /**
  71822. * Scales the texture
  71823. * @param ratio the scale factor to apply to both width and height
  71824. */
  71825. DynamicTexture.prototype.scale = function (ratio) {
  71826. var textureSize = this.getSize();
  71827. textureSize.width *= ratio;
  71828. textureSize.height *= ratio;
  71829. this._recreate(textureSize);
  71830. };
  71831. /**
  71832. * Resizes the texture
  71833. * @param width the new width
  71834. * @param height the new height
  71835. */
  71836. DynamicTexture.prototype.scaleTo = function (width, height) {
  71837. var textureSize = this.getSize();
  71838. textureSize.width = width;
  71839. textureSize.height = height;
  71840. this._recreate(textureSize);
  71841. };
  71842. /**
  71843. * Gets the context of the canvas used by the texture
  71844. * @returns the canvas context of the dynamic texture
  71845. */
  71846. DynamicTexture.prototype.getContext = function () {
  71847. return this._context;
  71848. };
  71849. /**
  71850. * Clears the texture
  71851. */
  71852. DynamicTexture.prototype.clear = function () {
  71853. var size = this.getSize();
  71854. this._context.fillRect(0, 0, size.width, size.height);
  71855. };
  71856. /**
  71857. * Updates the texture
  71858. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71859. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  71860. */
  71861. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  71862. if (premulAlpha === void 0) { premulAlpha = false; }
  71863. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  71864. };
  71865. /**
  71866. * Draws text onto the texture
  71867. * @param text defines the text to be drawn
  71868. * @param x defines the placement of the text from the left
  71869. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  71870. * @param font defines the font to be used with font-style, font-size, font-name
  71871. * @param color defines the color used for the text
  71872. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  71873. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71874. * @param update defines whether texture is immediately update (default is true)
  71875. */
  71876. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  71877. if (update === void 0) { update = true; }
  71878. var size = this.getSize();
  71879. if (clearColor) {
  71880. this._context.fillStyle = clearColor;
  71881. this._context.fillRect(0, 0, size.width, size.height);
  71882. }
  71883. this._context.font = font;
  71884. if (x === null || x === undefined) {
  71885. var textSize = this._context.measureText(text);
  71886. x = (size.width - textSize.width) / 2;
  71887. }
  71888. if (y === null || y === undefined) {
  71889. var fontSize = parseInt((font.replace(/\D/g, '')));
  71890. y = (size.height / 2) + (fontSize / 3.65);
  71891. }
  71892. this._context.fillStyle = color;
  71893. this._context.fillText(text, x, y);
  71894. if (update) {
  71895. this.update(invertY);
  71896. }
  71897. };
  71898. /**
  71899. * Clones the texture
  71900. * @returns the clone of the texture.
  71901. */
  71902. DynamicTexture.prototype.clone = function () {
  71903. var scene = this.getScene();
  71904. if (!scene) {
  71905. return this;
  71906. }
  71907. var textureSize = this.getSize();
  71908. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  71909. // Base texture
  71910. newTexture.hasAlpha = this.hasAlpha;
  71911. newTexture.level = this.level;
  71912. // Dynamic Texture
  71913. newTexture.wrapU = this.wrapU;
  71914. newTexture.wrapV = this.wrapV;
  71915. return newTexture;
  71916. };
  71917. /**
  71918. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  71919. * @returns a serialized dynamic texture object
  71920. */
  71921. DynamicTexture.prototype.serialize = function () {
  71922. var scene = this.getScene();
  71923. if (scene && !scene.isReady()) {
  71924. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  71925. }
  71926. var serializationObject = _super.prototype.serialize.call(this);
  71927. serializationObject.base64String = this._canvas.toDataURL();
  71928. serializationObject.invertY = this._invertY;
  71929. serializationObject.samplingMode = this.samplingMode;
  71930. return serializationObject;
  71931. };
  71932. /** @hidden */
  71933. DynamicTexture.prototype._rebuild = function () {
  71934. this.update();
  71935. };
  71936. return DynamicTexture;
  71937. }(BABYLON.Texture));
  71938. BABYLON.DynamicTexture = DynamicTexture;
  71939. })(BABYLON || (BABYLON = {}));
  71940. //# sourceMappingURL=babylon.dynamicTexture.js.map
  71941. var BABYLON;
  71942. (function (BABYLON) {
  71943. var VideoTexture = /** @class */ (function (_super) {
  71944. __extends(VideoTexture, _super);
  71945. /**
  71946. * Creates a video texture.
  71947. * Sample : https://doc.babylonjs.com/how_to/video_texture
  71948. * @param {string | null} name optional name, will detect from video source, if not defined
  71949. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  71950. * @param {BABYLON.Scene} scene is obviously the current scene.
  71951. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  71952. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  71953. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  71954. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  71955. */
  71956. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  71957. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71958. if (invertY === void 0) { invertY = false; }
  71959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71960. if (settings === void 0) { settings = {
  71961. autoPlay: true,
  71962. loop: true,
  71963. autoUpdateTexture: true,
  71964. }; }
  71965. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71966. _this._onUserActionRequestedObservable = null;
  71967. _this._stillImageCaptured = false;
  71968. _this._poster = false;
  71969. _this._createInternalTexture = function () {
  71970. if (_this._texture != null) {
  71971. if (_this._poster) {
  71972. _this._texture.dispose();
  71973. _this._poster = false;
  71974. }
  71975. else {
  71976. return;
  71977. }
  71978. }
  71979. if (!_this._engine.needPOTTextures ||
  71980. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  71981. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71982. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71983. }
  71984. else {
  71985. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71986. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71987. _this._generateMipMaps = false;
  71988. }
  71989. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  71990. if (!_this.video.autoplay) {
  71991. var oldHandler_1 = _this.video.onplaying;
  71992. var error_1 = false;
  71993. _this.video.onplaying = function () {
  71994. _this.video.onplaying = oldHandler_1;
  71995. _this._texture.isReady = true;
  71996. _this._updateInternalTexture();
  71997. if (!error_1) {
  71998. _this.video.pause();
  71999. }
  72000. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72001. _this.onLoadObservable.notifyObservers(_this);
  72002. }
  72003. };
  72004. var playing = _this.video.play();
  72005. if (playing) {
  72006. playing.then(function () {
  72007. // Everything is good.
  72008. })
  72009. .catch(function () {
  72010. error_1 = true;
  72011. // On Chrome for instance, new policies might prevent playing without user interaction.
  72012. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  72013. _this._onUserActionRequestedObservable.notifyObservers(_this);
  72014. }
  72015. });
  72016. }
  72017. else {
  72018. _this.video.onplaying = oldHandler_1;
  72019. _this._texture.isReady = true;
  72020. _this._updateInternalTexture();
  72021. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72022. _this.onLoadObservable.notifyObservers(_this);
  72023. }
  72024. }
  72025. }
  72026. else {
  72027. _this._texture.isReady = true;
  72028. _this._updateInternalTexture();
  72029. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72030. _this.onLoadObservable.notifyObservers(_this);
  72031. }
  72032. }
  72033. };
  72034. _this.reset = function () {
  72035. if (_this._texture == null) {
  72036. return;
  72037. }
  72038. if (!_this._poster) {
  72039. _this._texture.dispose();
  72040. _this._texture = null;
  72041. }
  72042. };
  72043. _this._updateInternalTexture = function (e) {
  72044. if (_this._texture == null || !_this._texture.isReady) {
  72045. return;
  72046. }
  72047. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  72048. return;
  72049. }
  72050. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  72051. };
  72052. _this._engine = _this.getScene().getEngine();
  72053. _this._generateMipMaps = generateMipMaps;
  72054. _this._samplingMode = samplingMode;
  72055. _this.autoUpdateTexture = settings.autoUpdateTexture;
  72056. _this.name = name || _this._getName(src);
  72057. _this.video = _this._getVideo(src);
  72058. if (settings.poster) {
  72059. _this.video.poster = settings.poster;
  72060. }
  72061. if (settings.autoPlay !== undefined) {
  72062. _this.video.autoplay = settings.autoPlay;
  72063. }
  72064. if (settings.loop !== undefined) {
  72065. _this.video.loop = settings.loop;
  72066. }
  72067. _this.video.setAttribute("playsinline", "");
  72068. _this.video.addEventListener("canplay", _this._createInternalTexture);
  72069. _this.video.addEventListener("paused", _this._updateInternalTexture);
  72070. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  72071. _this.video.addEventListener("emptied", _this.reset);
  72072. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  72073. _this._createInternalTexture();
  72074. }
  72075. if (settings.poster) {
  72076. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  72077. _this._poster = true;
  72078. }
  72079. return _this;
  72080. }
  72081. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  72082. get: function () {
  72083. if (!this._onUserActionRequestedObservable) {
  72084. this._onUserActionRequestedObservable = new BABYLON.Observable();
  72085. }
  72086. return this._onUserActionRequestedObservable;
  72087. },
  72088. enumerable: true,
  72089. configurable: true
  72090. });
  72091. VideoTexture.prototype._getName = function (src) {
  72092. if (src instanceof HTMLVideoElement) {
  72093. return src.currentSrc;
  72094. }
  72095. if (typeof src === "object") {
  72096. return src.toString();
  72097. }
  72098. return src;
  72099. };
  72100. ;
  72101. VideoTexture.prototype._getVideo = function (src) {
  72102. if (src instanceof HTMLVideoElement) {
  72103. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  72104. return src;
  72105. }
  72106. var video = document.createElement("video");
  72107. if (typeof src === "string") {
  72108. BABYLON.Tools.SetCorsBehavior(src, video);
  72109. video.src = src;
  72110. }
  72111. else {
  72112. BABYLON.Tools.SetCorsBehavior(src[0], video);
  72113. src.forEach(function (url) {
  72114. var source = document.createElement("source");
  72115. source.src = url;
  72116. video.appendChild(source);
  72117. });
  72118. }
  72119. return video;
  72120. };
  72121. ;
  72122. /**
  72123. * @hidden Internal method to initiate `update`.
  72124. */
  72125. VideoTexture.prototype._rebuild = function () {
  72126. this.update();
  72127. };
  72128. /**
  72129. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  72130. */
  72131. VideoTexture.prototype.update = function () {
  72132. if (!this.autoUpdateTexture) {
  72133. // Expecting user to call `updateTexture` manually
  72134. return;
  72135. }
  72136. this.updateTexture(true);
  72137. };
  72138. /**
  72139. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  72140. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  72141. */
  72142. VideoTexture.prototype.updateTexture = function (isVisible) {
  72143. if (!isVisible) {
  72144. return;
  72145. }
  72146. if (this.video.paused && this._stillImageCaptured) {
  72147. return;
  72148. }
  72149. this._stillImageCaptured = true;
  72150. this._updateInternalTexture();
  72151. };
  72152. /**
  72153. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  72154. * @param url New url.
  72155. */
  72156. VideoTexture.prototype.updateURL = function (url) {
  72157. this.video.src = url;
  72158. };
  72159. VideoTexture.prototype.dispose = function () {
  72160. _super.prototype.dispose.call(this);
  72161. if (this._onUserActionRequestedObservable) {
  72162. this._onUserActionRequestedObservable.clear();
  72163. this._onUserActionRequestedObservable = null;
  72164. }
  72165. this.video.removeEventListener("canplay", this._createInternalTexture);
  72166. this.video.removeEventListener("paused", this._updateInternalTexture);
  72167. this.video.removeEventListener("seeked", this._updateInternalTexture);
  72168. this.video.removeEventListener("emptied", this.reset);
  72169. this.video.pause();
  72170. };
  72171. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  72172. var video = document.createElement("video");
  72173. video.setAttribute('autoplay', '');
  72174. video.setAttribute('muted', '');
  72175. video.setAttribute('playsinline', '');
  72176. var constraintsDeviceId;
  72177. if (constraints && constraints.deviceId) {
  72178. constraintsDeviceId = {
  72179. exact: constraints.deviceId,
  72180. };
  72181. }
  72182. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  72183. if (navigator.mediaDevices) {
  72184. navigator.mediaDevices.getUserMedia({ video: constraints })
  72185. .then(function (stream) {
  72186. if (video.mozSrcObject !== undefined) {
  72187. // hack for Firefox < 19
  72188. video.mozSrcObject = stream;
  72189. }
  72190. else {
  72191. video.srcObject = stream;
  72192. }
  72193. var onPlaying = function () {
  72194. if (onReady) {
  72195. onReady(new VideoTexture("video", video, scene, true, true));
  72196. }
  72197. video.removeEventListener("playing", onPlaying);
  72198. };
  72199. video.addEventListener("playing", onPlaying);
  72200. video.play();
  72201. })
  72202. .catch(function (err) {
  72203. BABYLON.Tools.Error(err.name);
  72204. });
  72205. }
  72206. else {
  72207. navigator.getUserMedia =
  72208. navigator.getUserMedia ||
  72209. navigator.webkitGetUserMedia ||
  72210. navigator.mozGetUserMedia ||
  72211. navigator.msGetUserMedia;
  72212. if (navigator.getUserMedia) {
  72213. navigator.getUserMedia({
  72214. video: {
  72215. deviceId: constraintsDeviceId,
  72216. width: {
  72217. min: (constraints && constraints.minWidth) || 256,
  72218. max: (constraints && constraints.maxWidth) || 640,
  72219. },
  72220. height: {
  72221. min: (constraints && constraints.minHeight) || 256,
  72222. max: (constraints && constraints.maxHeight) || 480,
  72223. },
  72224. },
  72225. }, function (stream) {
  72226. if (video.mozSrcObject !== undefined) {
  72227. // hack for Firefox < 19
  72228. video.mozSrcObject = stream;
  72229. }
  72230. else {
  72231. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  72232. }
  72233. video.play();
  72234. if (onReady) {
  72235. onReady(new VideoTexture("video", video, scene, true, true));
  72236. }
  72237. }, function (e) {
  72238. BABYLON.Tools.Error(e.name);
  72239. });
  72240. }
  72241. }
  72242. };
  72243. return VideoTexture;
  72244. }(BABYLON.Texture));
  72245. BABYLON.VideoTexture = VideoTexture;
  72246. })(BABYLON || (BABYLON = {}));
  72247. //# sourceMappingURL=babylon.videoTexture.js.map
  72248. var BABYLON;
  72249. (function (BABYLON) {
  72250. var RawTexture = /** @class */ (function (_super) {
  72251. __extends(RawTexture, _super);
  72252. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  72253. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72254. if (invertY === void 0) { invertY = false; }
  72255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72256. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72257. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72258. _this.format = format;
  72259. _this._engine = scene.getEngine();
  72260. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  72261. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72262. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72263. return _this;
  72264. }
  72265. RawTexture.prototype.update = function (data) {
  72266. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72267. };
  72268. // Statics
  72269. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72270. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72271. if (invertY === void 0) { invertY = false; }
  72272. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72273. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  72274. };
  72275. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72276. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72277. if (invertY === void 0) { invertY = false; }
  72278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72279. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72280. };
  72281. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72282. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72283. if (invertY === void 0) { invertY = false; }
  72284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72285. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72286. };
  72287. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72288. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72289. if (invertY === void 0) { invertY = false; }
  72290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72291. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72292. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  72293. };
  72294. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72295. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72296. if (invertY === void 0) { invertY = false; }
  72297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72298. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72299. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  72300. };
  72301. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72302. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72303. if (invertY === void 0) { invertY = false; }
  72304. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72305. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72306. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  72307. };
  72308. return RawTexture;
  72309. }(BABYLON.Texture));
  72310. BABYLON.RawTexture = RawTexture;
  72311. })(BABYLON || (BABYLON = {}));
  72312. //# sourceMappingURL=babylon.rawTexture.js.map
  72313. var BABYLON;
  72314. (function (BABYLON) {
  72315. /**
  72316. * Class used to store 3D textures containing user data
  72317. */
  72318. var RawTexture3D = /** @class */ (function (_super) {
  72319. __extends(RawTexture3D, _super);
  72320. /**
  72321. * Create a new RawTexture3D
  72322. * @param data defines the data of the texture
  72323. * @param width defines the width of the texture
  72324. * @param height defines the height of the texture
  72325. * @param depth defines the depth of the texture
  72326. * @param format defines the texture format to use
  72327. * @param scene defines the hosting scene
  72328. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  72329. * @param invertY defines if texture must be stored with Y axis inverted
  72330. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  72331. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  72332. */
  72333. function RawTexture3D(data, width, height, depth,
  72334. /** Gets or sets the texture format to use */
  72335. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  72336. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72337. if (invertY === void 0) { invertY = false; }
  72338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72339. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72340. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72341. _this.format = format;
  72342. _this._engine = scene.getEngine();
  72343. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  72344. _this.is3D = true;
  72345. return _this;
  72346. }
  72347. /**
  72348. * Update the texture with new data
  72349. * @param data defines the data to store in the texture
  72350. */
  72351. RawTexture3D.prototype.update = function (data) {
  72352. if (!this._texture) {
  72353. return;
  72354. }
  72355. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72356. };
  72357. return RawTexture3D;
  72358. }(BABYLON.Texture));
  72359. BABYLON.RawTexture3D = RawTexture3D;
  72360. })(BABYLON || (BABYLON = {}));
  72361. //# sourceMappingURL=babylon.rawTexture3D.js.map
  72362. var BABYLON;
  72363. (function (BABYLON) {
  72364. /**
  72365. * PostProcessManager is used to manage one or more post processes or post process pipelines
  72366. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72367. */
  72368. var PostProcessManager = /** @class */ (function () {
  72369. /**
  72370. * Creates a new instance PostProcess
  72371. * @param scene The scene that the post process is associated with.
  72372. */
  72373. function PostProcessManager(scene) {
  72374. this._vertexBuffers = {};
  72375. this._scene = scene;
  72376. }
  72377. PostProcessManager.prototype._prepareBuffers = function () {
  72378. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  72379. return;
  72380. }
  72381. // VBO
  72382. var vertices = [];
  72383. vertices.push(1, 1);
  72384. vertices.push(-1, 1);
  72385. vertices.push(-1, -1);
  72386. vertices.push(1, -1);
  72387. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72388. this._buildIndexBuffer();
  72389. };
  72390. PostProcessManager.prototype._buildIndexBuffer = function () {
  72391. // Indices
  72392. var indices = [];
  72393. indices.push(0);
  72394. indices.push(1);
  72395. indices.push(2);
  72396. indices.push(0);
  72397. indices.push(2);
  72398. indices.push(3);
  72399. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  72400. };
  72401. /**
  72402. * Rebuilds the vertex buffers of the manager.
  72403. * @hidden
  72404. */
  72405. PostProcessManager.prototype._rebuild = function () {
  72406. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72407. if (!vb) {
  72408. return;
  72409. }
  72410. vb._rebuild();
  72411. this._buildIndexBuffer();
  72412. };
  72413. // Methods
  72414. /**
  72415. * Prepares a frame to be run through a post process.
  72416. * @param sourceTexture The input texture to the post procesess. (default: null)
  72417. * @param postProcesses An array of post processes to be run. (default: null)
  72418. * @returns True if the post processes were able to be run.
  72419. * @hidden
  72420. */
  72421. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  72422. if (sourceTexture === void 0) { sourceTexture = null; }
  72423. if (postProcesses === void 0) { postProcesses = null; }
  72424. var camera = this._scene.activeCamera;
  72425. if (!camera) {
  72426. return false;
  72427. }
  72428. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72429. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72430. return false;
  72431. }
  72432. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  72433. return true;
  72434. };
  72435. /**
  72436. * Manually render a set of post processes to a texture.
  72437. * @param postProcesses An array of post processes to be run.
  72438. * @param targetTexture The target texture to render to.
  72439. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  72440. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  72441. * @param lodLevel defines which lod of the texture to render to
  72442. */
  72443. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  72444. if (targetTexture === void 0) { targetTexture = null; }
  72445. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72446. if (faceIndex === void 0) { faceIndex = 0; }
  72447. if (lodLevel === void 0) { lodLevel = 0; }
  72448. var engine = this._scene.getEngine();
  72449. for (var index = 0; index < postProcesses.length; index++) {
  72450. if (index < postProcesses.length - 1) {
  72451. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  72452. }
  72453. else {
  72454. if (targetTexture) {
  72455. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  72456. }
  72457. else {
  72458. engine.restoreDefaultFramebuffer();
  72459. }
  72460. }
  72461. var pp = postProcesses[index];
  72462. var effect = pp.apply();
  72463. if (effect) {
  72464. pp.onBeforeRenderObservable.notifyObservers(effect);
  72465. // VBOs
  72466. this._prepareBuffers();
  72467. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72468. // Draw order
  72469. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72470. pp.onAfterRenderObservable.notifyObservers(effect);
  72471. }
  72472. }
  72473. // Restore depth buffer
  72474. engine.setDepthBuffer(true);
  72475. engine.setDepthWrite(true);
  72476. };
  72477. /**
  72478. * Finalize the result of the output of the postprocesses.
  72479. * @param doNotPresent If true the result will not be displayed to the screen.
  72480. * @param targetTexture The target texture to render to.
  72481. * @param faceIndex The index of the face to bind the target texture to.
  72482. * @param postProcesses The array of post processes to render.
  72483. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  72484. * @hidden
  72485. */
  72486. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  72487. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72488. var camera = this._scene.activeCamera;
  72489. if (!camera) {
  72490. return;
  72491. }
  72492. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72493. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72494. return;
  72495. }
  72496. var engine = this._scene.getEngine();
  72497. for (var index = 0, len = postProcesses.length; index < len; index++) {
  72498. var pp = postProcesses[index];
  72499. if (index < len - 1) {
  72500. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  72501. }
  72502. else {
  72503. if (targetTexture) {
  72504. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  72505. pp._outputTexture = targetTexture;
  72506. }
  72507. else {
  72508. engine.restoreDefaultFramebuffer();
  72509. pp._outputTexture = null;
  72510. }
  72511. }
  72512. if (doNotPresent) {
  72513. break;
  72514. }
  72515. var effect = pp.apply();
  72516. if (effect) {
  72517. pp.onBeforeRenderObservable.notifyObservers(effect);
  72518. // VBOs
  72519. this._prepareBuffers();
  72520. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72521. // Draw order
  72522. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72523. pp.onAfterRenderObservable.notifyObservers(effect);
  72524. }
  72525. }
  72526. // Restore states
  72527. engine.setDepthBuffer(true);
  72528. engine.setDepthWrite(true);
  72529. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72530. };
  72531. /**
  72532. * Disposes of the post process manager.
  72533. */
  72534. PostProcessManager.prototype.dispose = function () {
  72535. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72536. if (buffer) {
  72537. buffer.dispose();
  72538. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72539. }
  72540. if (this._indexBuffer) {
  72541. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72542. this._indexBuffer = null;
  72543. }
  72544. };
  72545. return PostProcessManager;
  72546. }());
  72547. BABYLON.PostProcessManager = PostProcessManager;
  72548. })(BABYLON || (BABYLON = {}));
  72549. //# sourceMappingURL=babylon.postProcessManager.js.map
  72550. var BABYLON;
  72551. (function (BABYLON) {
  72552. /**
  72553. * PostProcess can be used to apply a shader to a texture after it has been rendered
  72554. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72555. */
  72556. var PostProcess = /** @class */ (function () {
  72557. /**
  72558. * Creates a new instance PostProcess
  72559. * @param name The name of the PostProcess.
  72560. * @param fragmentUrl The url of the fragment shader to be used.
  72561. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  72562. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  72563. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  72564. * @param camera The camera to apply the render pass to.
  72565. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72566. * @param engine The engine which the post process will be applied. (default: current engine)
  72567. * @param reusable If the post process can be reused on the same frame. (default: false)
  72568. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  72569. * @param textureType Type of textures used when performing the post process. (default: 0)
  72570. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  72571. * @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
  72572. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  72573. */
  72574. function PostProcess(
  72575. /** Name of the PostProcess. */
  72576. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  72577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  72578. if (defines === void 0) { defines = null; }
  72579. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72580. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  72581. if (blockCompilation === void 0) { blockCompilation = false; }
  72582. this.name = name;
  72583. /**
  72584. * Width of the texture to apply the post process on
  72585. */
  72586. this.width = -1;
  72587. /**
  72588. * Height of the texture to apply the post process on
  72589. */
  72590. this.height = -1;
  72591. /**
  72592. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  72593. * @hidden
  72594. */
  72595. this._outputTexture = null;
  72596. /**
  72597. * If the buffer needs to be cleared before applying the post process. (default: true)
  72598. * Should be set to false if shader will overwrite all previous pixels.
  72599. */
  72600. this.autoClear = true;
  72601. /**
  72602. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  72603. */
  72604. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  72605. /**
  72606. * Animations to be used for the post processing
  72607. */
  72608. this.animations = new Array();
  72609. /**
  72610. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  72611. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  72612. */
  72613. this.enablePixelPerfectMode = false;
  72614. /**
  72615. * Force the postprocess to be applied without taking in account viewport
  72616. */
  72617. this.forceFullscreenViewport = true;
  72618. /**
  72619. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  72620. *
  72621. * | Value | Type | Description |
  72622. * | ----- | ----------------------------------- | ----------- |
  72623. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  72624. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  72625. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  72626. *
  72627. */
  72628. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  72629. /**
  72630. * Force textures to be a power of two (default: false)
  72631. */
  72632. this.alwaysForcePOT = false;
  72633. this._samples = 1;
  72634. /**
  72635. * Modify the scale of the post process to be the same as the viewport (default: false)
  72636. */
  72637. this.adaptScaleToCurrentViewport = false;
  72638. this._reusable = false;
  72639. /**
  72640. * Smart array of input and output textures for the post process.
  72641. * @hidden
  72642. */
  72643. this._textures = new BABYLON.SmartArray(2);
  72644. /**
  72645. * The index in _textures that corresponds to the output texture.
  72646. * @hidden
  72647. */
  72648. this._currentRenderTextureInd = 0;
  72649. this._scaleRatio = new BABYLON.Vector2(1, 1);
  72650. this._texelSize = BABYLON.Vector2.Zero();
  72651. // Events
  72652. /**
  72653. * An event triggered when the postprocess is activated.
  72654. */
  72655. this.onActivateObservable = new BABYLON.Observable();
  72656. /**
  72657. * An event triggered when the postprocess changes its size.
  72658. */
  72659. this.onSizeChangedObservable = new BABYLON.Observable();
  72660. /**
  72661. * An event triggered when the postprocess applies its effect.
  72662. */
  72663. this.onApplyObservable = new BABYLON.Observable();
  72664. /**
  72665. * An event triggered before rendering the postprocess
  72666. */
  72667. this.onBeforeRenderObservable = new BABYLON.Observable();
  72668. /**
  72669. * An event triggered after rendering the postprocess
  72670. */
  72671. this.onAfterRenderObservable = new BABYLON.Observable();
  72672. if (camera != null) {
  72673. this._camera = camera;
  72674. this._scene = camera.getScene();
  72675. camera.attachPostProcess(this);
  72676. this._engine = this._scene.getEngine();
  72677. this._scene.postProcesses.push(this);
  72678. }
  72679. else if (engine) {
  72680. this._engine = engine;
  72681. this._engine.postProcesses.push(this);
  72682. }
  72683. this._options = options;
  72684. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  72685. this._reusable = reusable || false;
  72686. this._textureType = textureType;
  72687. this._samplers = samplers || [];
  72688. this._samplers.push("textureSampler");
  72689. this._fragmentUrl = fragmentUrl;
  72690. this._vertexUrl = vertexUrl;
  72691. this._parameters = parameters || [];
  72692. this._parameters.push("scale");
  72693. this._indexParameters = indexParameters;
  72694. if (!blockCompilation) {
  72695. this.updateEffect(defines);
  72696. }
  72697. }
  72698. Object.defineProperty(PostProcess.prototype, "samples", {
  72699. /**
  72700. * Number of sample textures (default: 1)
  72701. */
  72702. get: function () {
  72703. return this._samples;
  72704. },
  72705. set: function (n) {
  72706. var _this = this;
  72707. this._samples = n;
  72708. this._textures.forEach(function (texture) {
  72709. if (texture.samples !== _this._samples) {
  72710. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  72711. }
  72712. });
  72713. },
  72714. enumerable: true,
  72715. configurable: true
  72716. });
  72717. Object.defineProperty(PostProcess.prototype, "onActivate", {
  72718. /**
  72719. * A function that is added to the onActivateObservable
  72720. */
  72721. set: function (callback) {
  72722. if (this._onActivateObserver) {
  72723. this.onActivateObservable.remove(this._onActivateObserver);
  72724. }
  72725. if (callback) {
  72726. this._onActivateObserver = this.onActivateObservable.add(callback);
  72727. }
  72728. },
  72729. enumerable: true,
  72730. configurable: true
  72731. });
  72732. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  72733. /**
  72734. * A function that is added to the onSizeChangedObservable
  72735. */
  72736. set: function (callback) {
  72737. if (this._onSizeChangedObserver) {
  72738. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  72739. }
  72740. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  72741. },
  72742. enumerable: true,
  72743. configurable: true
  72744. });
  72745. Object.defineProperty(PostProcess.prototype, "onApply", {
  72746. /**
  72747. * A function that is added to the onApplyObservable
  72748. */
  72749. set: function (callback) {
  72750. if (this._onApplyObserver) {
  72751. this.onApplyObservable.remove(this._onApplyObserver);
  72752. }
  72753. this._onApplyObserver = this.onApplyObservable.add(callback);
  72754. },
  72755. enumerable: true,
  72756. configurable: true
  72757. });
  72758. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  72759. /**
  72760. * A function that is added to the onBeforeRenderObservable
  72761. */
  72762. set: function (callback) {
  72763. if (this._onBeforeRenderObserver) {
  72764. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72765. }
  72766. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72767. },
  72768. enumerable: true,
  72769. configurable: true
  72770. });
  72771. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  72772. /**
  72773. * A function that is added to the onAfterRenderObservable
  72774. */
  72775. set: function (callback) {
  72776. if (this._onAfterRenderObserver) {
  72777. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72778. }
  72779. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72780. },
  72781. enumerable: true,
  72782. configurable: true
  72783. });
  72784. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  72785. /**
  72786. * 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
  72787. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  72788. */
  72789. get: function () {
  72790. return this._textures.data[this._currentRenderTextureInd];
  72791. },
  72792. set: function (value) {
  72793. this._forcedOutputTexture = value;
  72794. },
  72795. enumerable: true,
  72796. configurable: true
  72797. });
  72798. /**
  72799. * Gets the camera which post process is applied to.
  72800. * @returns The camera the post process is applied to.
  72801. */
  72802. PostProcess.prototype.getCamera = function () {
  72803. return this._camera;
  72804. };
  72805. Object.defineProperty(PostProcess.prototype, "texelSize", {
  72806. /**
  72807. * Gets the texel size of the postprocess.
  72808. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  72809. */
  72810. get: function () {
  72811. if (this._shareOutputWithPostProcess) {
  72812. return this._shareOutputWithPostProcess.texelSize;
  72813. }
  72814. if (this._forcedOutputTexture) {
  72815. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  72816. }
  72817. return this._texelSize;
  72818. },
  72819. enumerable: true,
  72820. configurable: true
  72821. });
  72822. /**
  72823. * Gets the engine which this post process belongs to.
  72824. * @returns The engine the post process was enabled with.
  72825. */
  72826. PostProcess.prototype.getEngine = function () {
  72827. return this._engine;
  72828. };
  72829. /**
  72830. * The effect that is created when initializing the post process.
  72831. * @returns The created effect corrisponding the the postprocess.
  72832. */
  72833. PostProcess.prototype.getEffect = function () {
  72834. return this._effect;
  72835. };
  72836. /**
  72837. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  72838. * @param postProcess The post process to share the output with.
  72839. * @returns This post process.
  72840. */
  72841. PostProcess.prototype.shareOutputWith = function (postProcess) {
  72842. this._disposeTextures();
  72843. this._shareOutputWithPostProcess = postProcess;
  72844. return this;
  72845. };
  72846. /**
  72847. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  72848. * This should be called if the post process that shares output with this post process is disabled/disposed.
  72849. */
  72850. PostProcess.prototype.useOwnOutput = function () {
  72851. if (this._textures.length == 0) {
  72852. this._textures = new BABYLON.SmartArray(2);
  72853. }
  72854. this._shareOutputWithPostProcess = null;
  72855. };
  72856. /**
  72857. * Updates the effect with the current post process compile time values and recompiles the shader.
  72858. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72859. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72860. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72861. * @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
  72862. * @param onCompiled Called when the shader has been compiled.
  72863. * @param onError Called if there is an error when compiling a shader.
  72864. */
  72865. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72866. if (defines === void 0) { defines = null; }
  72867. if (uniforms === void 0) { uniforms = null; }
  72868. if (samplers === void 0) { samplers = null; }
  72869. 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);
  72870. };
  72871. /**
  72872. * The post process is reusable if it can be used multiple times within one frame.
  72873. * @returns If the post process is reusable
  72874. */
  72875. PostProcess.prototype.isReusable = function () {
  72876. return this._reusable;
  72877. };
  72878. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  72879. PostProcess.prototype.markTextureDirty = function () {
  72880. this.width = -1;
  72881. };
  72882. /**
  72883. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  72884. * 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.
  72885. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  72886. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  72887. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  72888. * @returns The target texture that was bound to be written to.
  72889. */
  72890. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  72891. var _this = this;
  72892. if (sourceTexture === void 0) { sourceTexture = null; }
  72893. camera = camera || this._camera;
  72894. var scene = camera.getScene();
  72895. var engine = scene.getEngine();
  72896. var maxSize = engine.getCaps().maxTextureSize;
  72897. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  72898. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  72899. // 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
  72900. var webVRCamera = camera.parent;
  72901. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  72902. requiredWidth /= 2;
  72903. }
  72904. var desiredWidth = (this._options.width || requiredWidth);
  72905. var desiredHeight = this._options.height || requiredHeight;
  72906. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  72907. if (this.adaptScaleToCurrentViewport) {
  72908. var currentViewport = engine.currentViewport;
  72909. if (currentViewport) {
  72910. desiredWidth *= currentViewport.width;
  72911. desiredHeight *= currentViewport.height;
  72912. }
  72913. }
  72914. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  72915. if (!this._options.width) {
  72916. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  72917. }
  72918. if (!this._options.height) {
  72919. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  72920. }
  72921. }
  72922. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  72923. if (this._textures.length > 0) {
  72924. for (var i = 0; i < this._textures.length; i++) {
  72925. this._engine._releaseTexture(this._textures.data[i]);
  72926. }
  72927. this._textures.reset();
  72928. }
  72929. this.width = desiredWidth;
  72930. this.height = desiredHeight;
  72931. var textureSize = { width: this.width, height: this.height };
  72932. var textureOptions = {
  72933. generateMipMaps: false,
  72934. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  72935. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  72936. samplingMode: this.renderTargetSamplingMode,
  72937. type: this._textureType
  72938. };
  72939. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72940. if (this._reusable) {
  72941. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72942. }
  72943. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  72944. this.onSizeChangedObservable.notifyObservers(this);
  72945. }
  72946. this._textures.forEach(function (texture) {
  72947. if (texture.samples !== _this.samples) {
  72948. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  72949. }
  72950. });
  72951. }
  72952. var target;
  72953. if (this._shareOutputWithPostProcess) {
  72954. target = this._shareOutputWithPostProcess.inputTexture;
  72955. }
  72956. else if (this._forcedOutputTexture) {
  72957. target = this._forcedOutputTexture;
  72958. this.width = this._forcedOutputTexture.width;
  72959. this.height = this._forcedOutputTexture.height;
  72960. }
  72961. else {
  72962. target = this.inputTexture;
  72963. }
  72964. // Bind the input of this post process to be used as the output of the previous post process.
  72965. if (this.enablePixelPerfectMode) {
  72966. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  72967. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72968. }
  72969. else {
  72970. this._scaleRatio.copyFromFloats(1, 1);
  72971. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72972. }
  72973. this.onActivateObservable.notifyObservers(camera);
  72974. // Clear
  72975. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  72976. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  72977. }
  72978. if (this._reusable) {
  72979. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  72980. }
  72981. return target;
  72982. };
  72983. Object.defineProperty(PostProcess.prototype, "isSupported", {
  72984. /**
  72985. * If the post process is supported.
  72986. */
  72987. get: function () {
  72988. return this._effect.isSupported;
  72989. },
  72990. enumerable: true,
  72991. configurable: true
  72992. });
  72993. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  72994. /**
  72995. * The aspect ratio of the output texture.
  72996. */
  72997. get: function () {
  72998. if (this._shareOutputWithPostProcess) {
  72999. return this._shareOutputWithPostProcess.aspectRatio;
  73000. }
  73001. if (this._forcedOutputTexture) {
  73002. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  73003. }
  73004. return this.width / this.height;
  73005. },
  73006. enumerable: true,
  73007. configurable: true
  73008. });
  73009. /**
  73010. * Get a value indicating if the post-process is ready to be used
  73011. * @returns true if the post-process is ready (shader is compiled)
  73012. */
  73013. PostProcess.prototype.isReady = function () {
  73014. return this._effect && this._effect.isReady();
  73015. };
  73016. /**
  73017. * Binds all textures and uniforms to the shader, this will be run on every pass.
  73018. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  73019. */
  73020. PostProcess.prototype.apply = function () {
  73021. // Check
  73022. if (!this._effect || !this._effect.isReady())
  73023. return null;
  73024. // States
  73025. this._engine.enableEffect(this._effect);
  73026. this._engine.setState(false);
  73027. this._engine.setDepthBuffer(false);
  73028. this._engine.setDepthWrite(false);
  73029. // Alpha
  73030. this._engine.setAlphaMode(this.alphaMode);
  73031. if (this.alphaConstants) {
  73032. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  73033. }
  73034. // Bind the output texture of the preivous post process as the input to this post process.
  73035. var source;
  73036. if (this._shareOutputWithPostProcess) {
  73037. source = this._shareOutputWithPostProcess.inputTexture;
  73038. }
  73039. else if (this._forcedOutputTexture) {
  73040. source = this._forcedOutputTexture;
  73041. }
  73042. else {
  73043. source = this.inputTexture;
  73044. }
  73045. this._effect._bindTexture("textureSampler", source);
  73046. // Parameters
  73047. this._effect.setVector2("scale", this._scaleRatio);
  73048. this.onApplyObservable.notifyObservers(this._effect);
  73049. return this._effect;
  73050. };
  73051. PostProcess.prototype._disposeTextures = function () {
  73052. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  73053. return;
  73054. }
  73055. if (this._textures.length > 0) {
  73056. for (var i = 0; i < this._textures.length; i++) {
  73057. this._engine._releaseTexture(this._textures.data[i]);
  73058. }
  73059. }
  73060. this._textures.dispose();
  73061. };
  73062. /**
  73063. * Disposes the post process.
  73064. * @param camera The camera to dispose the post process on.
  73065. */
  73066. PostProcess.prototype.dispose = function (camera) {
  73067. camera = camera || this._camera;
  73068. this._disposeTextures();
  73069. if (this._scene) {
  73070. var index_1 = this._scene.postProcesses.indexOf(this);
  73071. if (index_1 !== -1) {
  73072. this._scene.postProcesses.splice(index_1, 1);
  73073. }
  73074. }
  73075. else {
  73076. var index_2 = this._engine.postProcesses.indexOf(this);
  73077. if (index_2 !== -1) {
  73078. this._engine.postProcesses.splice(index_2, 1);
  73079. }
  73080. }
  73081. if (!camera) {
  73082. return;
  73083. }
  73084. camera.detachPostProcess(this);
  73085. var index = camera._postProcesses.indexOf(this);
  73086. if (index === 0 && camera._postProcesses.length > 0) {
  73087. var firstPostProcess = this._camera._getFirstPostProcess();
  73088. if (firstPostProcess) {
  73089. firstPostProcess.markTextureDirty();
  73090. }
  73091. }
  73092. this.onActivateObservable.clear();
  73093. this.onAfterRenderObservable.clear();
  73094. this.onApplyObservable.clear();
  73095. this.onBeforeRenderObservable.clear();
  73096. this.onSizeChangedObservable.clear();
  73097. };
  73098. return PostProcess;
  73099. }());
  73100. BABYLON.PostProcess = PostProcess;
  73101. })(BABYLON || (BABYLON = {}));
  73102. //# sourceMappingURL=babylon.postProcess.js.map
  73103. var BABYLON;
  73104. (function (BABYLON) {
  73105. var PassPostProcess = /** @class */ (function (_super) {
  73106. __extends(PassPostProcess, _super);
  73107. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73108. if (camera === void 0) { camera = null; }
  73109. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73110. if (blockCompilation === void 0) { blockCompilation = false; }
  73111. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  73112. }
  73113. return PassPostProcess;
  73114. }(BABYLON.PostProcess));
  73115. BABYLON.PassPostProcess = PassPostProcess;
  73116. })(BABYLON || (BABYLON = {}));
  73117. //# sourceMappingURL=babylon.passPostProcess.js.map
  73118. var __assign = (this && this.__assign) || function () {
  73119. __assign = Object.assign || function(t) {
  73120. for (var s, i = 1, n = arguments.length; i < n; i++) {
  73121. s = arguments[i];
  73122. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  73123. t[p] = s[p];
  73124. }
  73125. return t;
  73126. };
  73127. return __assign.apply(this, arguments);
  73128. };
  73129. var BABYLON;
  73130. (function (BABYLON) {
  73131. /**
  73132. * Default implementation IShadowGenerator.
  73133. * This is the main object responsible of generating shadows in the framework.
  73134. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  73135. */
  73136. var ShadowGenerator = /** @class */ (function () {
  73137. /**
  73138. * Creates a ShadowGenerator object.
  73139. * A ShadowGenerator is the required tool to use the shadows.
  73140. * Each light casting shadows needs to use its own ShadowGenerator.
  73141. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  73142. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  73143. * @param light The light object generating the shadows.
  73144. * @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.
  73145. */
  73146. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  73147. this._bias = 0.00005;
  73148. this._normalBias = 0;
  73149. this._blurBoxOffset = 1;
  73150. this._blurScale = 2;
  73151. this._blurKernel = 1;
  73152. this._useKernelBlur = false;
  73153. this._filter = ShadowGenerator.FILTER_NONE;
  73154. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  73155. this._contactHardeningLightSizeUVRatio = 0.1;
  73156. this._darkness = 0;
  73157. this._transparencyShadow = false;
  73158. /**
  73159. * Controls the extent to which the shadows fade out at the edge of the frustum
  73160. * Used only by directionals and spots
  73161. */
  73162. this.frustumEdgeFalloff = 0;
  73163. /**
  73164. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  73165. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  73166. * It might on the other hand introduce peter panning.
  73167. */
  73168. this.forceBackFacesOnly = false;
  73169. this._lightDirection = BABYLON.Vector3.Zero();
  73170. this._viewMatrix = BABYLON.Matrix.Zero();
  73171. this._projectionMatrix = BABYLON.Matrix.Zero();
  73172. this._transformMatrix = BABYLON.Matrix.Zero();
  73173. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73174. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73175. this._currentFaceIndex = 0;
  73176. this._currentFaceIndexCache = 0;
  73177. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  73178. this._mapSize = mapSize;
  73179. this._light = light;
  73180. this._scene = light.getScene();
  73181. light._shadowGenerator = this;
  73182. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  73183. if (!component) {
  73184. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  73185. this._scene._addComponent(component);
  73186. }
  73187. // Texture type fallback from float to int if not supported.
  73188. var caps = this._scene.getEngine().getCaps();
  73189. if (!useFullFloatFirst) {
  73190. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73191. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73192. }
  73193. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73194. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73195. }
  73196. else {
  73197. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73198. }
  73199. }
  73200. else {
  73201. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73202. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73203. }
  73204. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73205. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73206. }
  73207. else {
  73208. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73209. }
  73210. }
  73211. this._initializeGenerator();
  73212. this._applyFilterValues();
  73213. }
  73214. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  73215. /**
  73216. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  73217. */
  73218. get: function () {
  73219. return this._bias;
  73220. },
  73221. /**
  73222. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  73223. */
  73224. set: function (bias) {
  73225. this._bias = bias;
  73226. },
  73227. enumerable: true,
  73228. configurable: true
  73229. });
  73230. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  73231. /**
  73232. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73233. */
  73234. get: function () {
  73235. return this._normalBias;
  73236. },
  73237. /**
  73238. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73239. */
  73240. set: function (normalBias) {
  73241. this._normalBias = normalBias;
  73242. },
  73243. enumerable: true,
  73244. configurable: true
  73245. });
  73246. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  73247. /**
  73248. * Gets the blur box offset: offset applied during the blur pass.
  73249. * Only usefull if useKernelBlur = false
  73250. */
  73251. get: function () {
  73252. return this._blurBoxOffset;
  73253. },
  73254. /**
  73255. * Sets the blur box offset: offset applied during the blur pass.
  73256. * Only usefull if useKernelBlur = false
  73257. */
  73258. set: function (value) {
  73259. if (this._blurBoxOffset === value) {
  73260. return;
  73261. }
  73262. this._blurBoxOffset = value;
  73263. this._disposeBlurPostProcesses();
  73264. },
  73265. enumerable: true,
  73266. configurable: true
  73267. });
  73268. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  73269. /**
  73270. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  73271. * 2 means half of the size.
  73272. */
  73273. get: function () {
  73274. return this._blurScale;
  73275. },
  73276. /**
  73277. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  73278. * 2 means half of the size.
  73279. */
  73280. set: function (value) {
  73281. if (this._blurScale === value) {
  73282. return;
  73283. }
  73284. this._blurScale = value;
  73285. this._disposeBlurPostProcesses();
  73286. },
  73287. enumerable: true,
  73288. configurable: true
  73289. });
  73290. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  73291. /**
  73292. * Gets the blur kernel: kernel size of the blur pass.
  73293. * Only usefull if useKernelBlur = true
  73294. */
  73295. get: function () {
  73296. return this._blurKernel;
  73297. },
  73298. /**
  73299. * Sets the blur kernel: kernel size of the blur pass.
  73300. * Only usefull if useKernelBlur = true
  73301. */
  73302. set: function (value) {
  73303. if (this._blurKernel === value) {
  73304. return;
  73305. }
  73306. this._blurKernel = value;
  73307. this._disposeBlurPostProcesses();
  73308. },
  73309. enumerable: true,
  73310. configurable: true
  73311. });
  73312. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  73313. /**
  73314. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  73315. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73316. */
  73317. get: function () {
  73318. return this._useKernelBlur;
  73319. },
  73320. /**
  73321. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  73322. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73323. */
  73324. set: function (value) {
  73325. if (this._useKernelBlur === value) {
  73326. return;
  73327. }
  73328. this._useKernelBlur = value;
  73329. this._disposeBlurPostProcesses();
  73330. },
  73331. enumerable: true,
  73332. configurable: true
  73333. });
  73334. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  73335. /**
  73336. * Gets the depth scale used in ESM mode.
  73337. */
  73338. get: function () {
  73339. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  73340. },
  73341. /**
  73342. * Sets the depth scale used in ESM mode.
  73343. * This can override the scale stored on the light.
  73344. */
  73345. set: function (value) {
  73346. this._depthScale = value;
  73347. },
  73348. enumerable: true,
  73349. configurable: true
  73350. });
  73351. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  73352. /**
  73353. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  73354. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73355. */
  73356. get: function () {
  73357. return this._filter;
  73358. },
  73359. /**
  73360. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  73361. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73362. */
  73363. set: function (value) {
  73364. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  73365. if (this._light.needCube()) {
  73366. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73367. this.useExponentialShadowMap = true;
  73368. return;
  73369. }
  73370. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73371. this.useCloseExponentialShadowMap = true;
  73372. return;
  73373. }
  73374. // PCF on cubemap would also be expensive
  73375. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73376. this.usePoissonSampling = true;
  73377. return;
  73378. }
  73379. }
  73380. // Weblg1 fallback for PCF.
  73381. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73382. if (this._scene.getEngine().webGLVersion === 1) {
  73383. this.usePoissonSampling = true;
  73384. return;
  73385. }
  73386. }
  73387. if (this._filter === value) {
  73388. return;
  73389. }
  73390. this._filter = value;
  73391. this._disposeBlurPostProcesses();
  73392. this._applyFilterValues();
  73393. this._light._markMeshesAsLightDirty();
  73394. },
  73395. enumerable: true,
  73396. configurable: true
  73397. });
  73398. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  73399. /**
  73400. * Gets if the current filter is set to Poisson Sampling.
  73401. */
  73402. get: function () {
  73403. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  73404. },
  73405. /**
  73406. * Sets the current filter to Poisson Sampling.
  73407. */
  73408. set: function (value) {
  73409. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  73410. return;
  73411. }
  73412. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  73413. },
  73414. enumerable: true,
  73415. configurable: true
  73416. });
  73417. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  73418. /**
  73419. * Gets if the current filter is set to VSM.
  73420. * DEPRECATED. Should use useExponentialShadowMap instead.
  73421. */
  73422. get: function () {
  73423. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73424. return this.useExponentialShadowMap;
  73425. },
  73426. /**
  73427. * Sets the current filter is to VSM.
  73428. * DEPRECATED. Should use useExponentialShadowMap instead.
  73429. */
  73430. set: function (value) {
  73431. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73432. this.useExponentialShadowMap = value;
  73433. },
  73434. enumerable: true,
  73435. configurable: true
  73436. });
  73437. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  73438. /**
  73439. * Gets if the current filter is set to blurred VSM.
  73440. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73441. */
  73442. get: function () {
  73443. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73444. return this.useBlurExponentialShadowMap;
  73445. },
  73446. /**
  73447. * Sets the current filter is to blurred VSM.
  73448. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73449. */
  73450. set: function (value) {
  73451. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73452. this.useBlurExponentialShadowMap = value;
  73453. },
  73454. enumerable: true,
  73455. configurable: true
  73456. });
  73457. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  73458. /**
  73459. * Gets if the current filter is set to ESM.
  73460. */
  73461. get: function () {
  73462. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  73463. },
  73464. /**
  73465. * Sets the current filter is to ESM.
  73466. */
  73467. set: function (value) {
  73468. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  73469. return;
  73470. }
  73471. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73472. },
  73473. enumerable: true,
  73474. configurable: true
  73475. });
  73476. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  73477. /**
  73478. * Gets if the current filter is set to filtered ESM.
  73479. */
  73480. get: function () {
  73481. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  73482. },
  73483. /**
  73484. * Gets if the current filter is set to filtered ESM.
  73485. */
  73486. set: function (value) {
  73487. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73488. return;
  73489. }
  73490. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73491. },
  73492. enumerable: true,
  73493. configurable: true
  73494. });
  73495. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  73496. /**
  73497. * Gets if the current filter is set to "close ESM" (using the inverse of the
  73498. * exponential to prevent steep falloff artifacts).
  73499. */
  73500. get: function () {
  73501. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  73502. },
  73503. /**
  73504. * Sets the current filter to "close ESM" (using the inverse of the
  73505. * exponential to prevent steep falloff artifacts).
  73506. */
  73507. set: function (value) {
  73508. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  73509. return;
  73510. }
  73511. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73512. },
  73513. enumerable: true,
  73514. configurable: true
  73515. });
  73516. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  73517. /**
  73518. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  73519. * exponential to prevent steep falloff artifacts).
  73520. */
  73521. get: function () {
  73522. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  73523. },
  73524. /**
  73525. * Sets the current filter to filtered "close ESM" (using the inverse of the
  73526. * exponential to prevent steep falloff artifacts).
  73527. */
  73528. set: function (value) {
  73529. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73530. return;
  73531. }
  73532. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73533. },
  73534. enumerable: true,
  73535. configurable: true
  73536. });
  73537. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  73538. /**
  73539. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  73540. */
  73541. get: function () {
  73542. return this.filter === ShadowGenerator.FILTER_PCF;
  73543. },
  73544. /**
  73545. * Sets the current filter to "PCF" (percentage closer filtering).
  73546. */
  73547. set: function (value) {
  73548. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  73549. return;
  73550. }
  73551. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  73552. },
  73553. enumerable: true,
  73554. configurable: true
  73555. });
  73556. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  73557. /**
  73558. * Gets the PCF or PCSS Quality.
  73559. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  73560. */
  73561. get: function () {
  73562. return this._filteringQuality;
  73563. },
  73564. /**
  73565. * Sets the PCF or PCSS Quality.
  73566. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  73567. */
  73568. set: function (filteringQuality) {
  73569. this._filteringQuality = filteringQuality;
  73570. },
  73571. enumerable: true,
  73572. configurable: true
  73573. });
  73574. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  73575. /**
  73576. * Gets if the current filter is set to "PCSS" (contact hardening).
  73577. */
  73578. get: function () {
  73579. return this.filter === ShadowGenerator.FILTER_PCSS;
  73580. },
  73581. /**
  73582. * Sets the current filter to "PCSS" (contact hardening).
  73583. */
  73584. set: function (value) {
  73585. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  73586. return;
  73587. }
  73588. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  73589. },
  73590. enumerable: true,
  73591. configurable: true
  73592. });
  73593. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  73594. /**
  73595. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  73596. * Using a ratio helps keeping shape stability independently of the map size.
  73597. *
  73598. * It does not account for the light projection as it was having too much
  73599. * instability during the light setup or during light position changes.
  73600. *
  73601. * Only valid if useContactHardeningShadow is true.
  73602. */
  73603. get: function () {
  73604. return this._contactHardeningLightSizeUVRatio;
  73605. },
  73606. /**
  73607. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  73608. * Using a ratio helps keeping shape stability independently of the map size.
  73609. *
  73610. * It does not account for the light projection as it was having too much
  73611. * instability during the light setup or during light position changes.
  73612. *
  73613. * Only valid if useContactHardeningShadow is true.
  73614. */
  73615. set: function (contactHardeningLightSizeUVRatio) {
  73616. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  73617. },
  73618. enumerable: true,
  73619. configurable: true
  73620. });
  73621. /**
  73622. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  73623. * 0 means strongest and 1 would means no shadow.
  73624. * @returns the darkness.
  73625. */
  73626. ShadowGenerator.prototype.getDarkness = function () {
  73627. return this._darkness;
  73628. };
  73629. /**
  73630. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  73631. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  73632. * @returns the shadow generator allowing fluent coding.
  73633. */
  73634. ShadowGenerator.prototype.setDarkness = function (darkness) {
  73635. if (darkness >= 1.0)
  73636. this._darkness = 1.0;
  73637. else if (darkness <= 0.0)
  73638. this._darkness = 0.0;
  73639. else
  73640. this._darkness = darkness;
  73641. return this;
  73642. };
  73643. /**
  73644. * Sets the ability to have transparent shadow (boolean).
  73645. * @param transparent True if transparent else False
  73646. * @returns the shadow generator allowing fluent coding
  73647. */
  73648. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  73649. this._transparencyShadow = transparent;
  73650. return this;
  73651. };
  73652. /**
  73653. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  73654. * @returns The render target texture if present otherwise, null
  73655. */
  73656. ShadowGenerator.prototype.getShadowMap = function () {
  73657. return this._shadowMap;
  73658. };
  73659. /**
  73660. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  73661. * @returns The render target texture if the shadow map is present otherwise, null
  73662. */
  73663. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  73664. if (this._shadowMap2) {
  73665. return this._shadowMap2;
  73666. }
  73667. return this._shadowMap;
  73668. };
  73669. /**
  73670. * Helper function to add a mesh and its descendants to the list of shadow casters.
  73671. * @param mesh Mesh to add
  73672. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  73673. * @returns the Shadow Generator itself
  73674. */
  73675. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  73676. if (includeDescendants === void 0) { includeDescendants = true; }
  73677. var _a;
  73678. if (!this._shadowMap) {
  73679. return this;
  73680. }
  73681. if (!this._shadowMap.renderList) {
  73682. this._shadowMap.renderList = [];
  73683. }
  73684. this._shadowMap.renderList.push(mesh);
  73685. if (includeDescendants) {
  73686. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  73687. }
  73688. return this;
  73689. };
  73690. /**
  73691. * Helper function to remove a mesh and its descendants from the list of shadow casters
  73692. * @param mesh Mesh to remove
  73693. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  73694. * @returns the Shadow Generator itself
  73695. */
  73696. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  73697. if (includeDescendants === void 0) { includeDescendants = true; }
  73698. if (!this._shadowMap || !this._shadowMap.renderList) {
  73699. return this;
  73700. }
  73701. var index = this._shadowMap.renderList.indexOf(mesh);
  73702. if (index !== -1) {
  73703. this._shadowMap.renderList.splice(index, 1);
  73704. }
  73705. if (includeDescendants) {
  73706. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  73707. var child = _a[_i];
  73708. this.removeShadowCaster(child);
  73709. }
  73710. }
  73711. return this;
  73712. };
  73713. /**
  73714. * Returns the associated light object.
  73715. * @returns the light generating the shadow
  73716. */
  73717. ShadowGenerator.prototype.getLight = function () {
  73718. return this._light;
  73719. };
  73720. ShadowGenerator.prototype._initializeGenerator = function () {
  73721. this._light._markMeshesAsLightDirty();
  73722. this._initializeShadowMap();
  73723. };
  73724. ShadowGenerator.prototype._initializeShadowMap = function () {
  73725. var _this = this;
  73726. // Render target
  73727. var engine = this._scene.getEngine();
  73728. if (engine.webGLVersion > 1) {
  73729. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  73730. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  73731. }
  73732. else {
  73733. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  73734. }
  73735. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73736. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73737. this._shadowMap.anisotropicFilteringLevel = 1;
  73738. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73739. this._shadowMap.renderParticles = false;
  73740. this._shadowMap.ignoreCameraViewport = true;
  73741. // Record Face Index before render.
  73742. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  73743. _this._currentFaceIndex = faceIndex;
  73744. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73745. engine.setColorWrite(false);
  73746. }
  73747. });
  73748. // Custom render function.
  73749. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  73750. // Blur if required afer render.
  73751. this._shadowMap.onAfterUnbindObservable.add(function () {
  73752. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73753. engine.setColorWrite(true);
  73754. }
  73755. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  73756. return;
  73757. }
  73758. var shadowMap = _this.getShadowMapForRendering();
  73759. if (shadowMap) {
  73760. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  73761. }
  73762. });
  73763. // Clear according to the chosen filter.
  73764. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  73765. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  73766. this._shadowMap.onClearObservable.add(function (engine) {
  73767. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73768. engine.clear(clearOne, false, true, false);
  73769. }
  73770. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  73771. engine.clear(clearZero, true, true, false);
  73772. }
  73773. else {
  73774. engine.clear(clearOne, true, true, false);
  73775. }
  73776. });
  73777. };
  73778. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  73779. var _this = this;
  73780. var engine = this._scene.getEngine();
  73781. var targetSize = this._mapSize / this.blurScale;
  73782. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  73783. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  73784. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73785. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73786. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73787. }
  73788. if (this.useKernelBlur) {
  73789. 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);
  73790. this._kernelBlurXPostprocess.width = targetSize;
  73791. this._kernelBlurXPostprocess.height = targetSize;
  73792. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  73793. effect.setTexture("textureSampler", _this._shadowMap);
  73794. });
  73795. 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);
  73796. this._kernelBlurXPostprocess.autoClear = false;
  73797. this._kernelBlurYPostprocess.autoClear = false;
  73798. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73799. this._kernelBlurXPostprocess.packedFloat = true;
  73800. this._kernelBlurYPostprocess.packedFloat = true;
  73801. }
  73802. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  73803. }
  73804. else {
  73805. 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);
  73806. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  73807. effect.setFloat2("screenSize", targetSize, targetSize);
  73808. effect.setTexture("textureSampler", _this._shadowMap);
  73809. });
  73810. this._boxBlurPostprocess.autoClear = false;
  73811. this._blurPostProcesses = [this._boxBlurPostprocess];
  73812. }
  73813. };
  73814. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73815. var index;
  73816. var engine = this._scene.getEngine();
  73817. if (depthOnlySubMeshes.length) {
  73818. engine.setColorWrite(false);
  73819. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73820. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  73821. }
  73822. engine.setColorWrite(true);
  73823. }
  73824. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73825. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  73826. }
  73827. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73828. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  73829. }
  73830. if (this._transparencyShadow) {
  73831. for (index = 0; index < transparentSubMeshes.length; index++) {
  73832. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  73833. }
  73834. }
  73835. };
  73836. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  73837. var _this = this;
  73838. var mesh = subMesh.getRenderingMesh();
  73839. var scene = this._scene;
  73840. var engine = scene.getEngine();
  73841. var material = subMesh.getMaterial();
  73842. if (!material) {
  73843. return;
  73844. }
  73845. // Culling
  73846. engine.setState(material.backFaceCulling);
  73847. // Managing instances
  73848. var batch = mesh._getInstancesRenderList(subMesh._id);
  73849. if (batch.mustReturn) {
  73850. return;
  73851. }
  73852. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73853. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  73854. engine.enableEffect(this._effect);
  73855. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73856. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  73857. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  73858. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73859. this._effect.setVector3("lightData", this._cachedDirection);
  73860. }
  73861. else {
  73862. this._effect.setVector3("lightData", this._cachedPosition);
  73863. }
  73864. if (scene.activeCamera) {
  73865. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  73866. }
  73867. // Alpha test
  73868. if (material && material.needAlphaTesting()) {
  73869. var alphaTexture = material.getAlphaTestTexture();
  73870. if (alphaTexture) {
  73871. this._effect.setTexture("diffuseSampler", alphaTexture);
  73872. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  73873. }
  73874. }
  73875. // Bones
  73876. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73877. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  73878. }
  73879. // Morph targets
  73880. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  73881. if (this.forceBackFacesOnly) {
  73882. engine.setState(true, 0, false, true);
  73883. }
  73884. // Draw
  73885. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73886. if (this.forceBackFacesOnly) {
  73887. engine.setState(true, 0, false, false);
  73888. }
  73889. }
  73890. else {
  73891. // Need to reset refresh rate of the shadowMap
  73892. if (this._shadowMap) {
  73893. this._shadowMap.resetRefreshCounter();
  73894. }
  73895. }
  73896. };
  73897. ShadowGenerator.prototype._applyFilterValues = function () {
  73898. if (!this._shadowMap) {
  73899. return;
  73900. }
  73901. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  73902. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  73903. }
  73904. else {
  73905. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73906. }
  73907. };
  73908. /**
  73909. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73910. * @param onCompiled Callback triggered at the and of the effects compilation
  73911. * @param options Sets of optional options forcing the compilation with different modes
  73912. */
  73913. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  73914. var _this = this;
  73915. var localOptions = __assign({ useInstances: false }, options);
  73916. var shadowMap = this.getShadowMap();
  73917. if (!shadowMap) {
  73918. if (onCompiled) {
  73919. onCompiled(this);
  73920. }
  73921. return;
  73922. }
  73923. var renderList = shadowMap.renderList;
  73924. if (!renderList) {
  73925. if (onCompiled) {
  73926. onCompiled(this);
  73927. }
  73928. return;
  73929. }
  73930. var subMeshes = new Array();
  73931. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  73932. var mesh = renderList_1[_i];
  73933. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  73934. }
  73935. if (subMeshes.length === 0) {
  73936. if (onCompiled) {
  73937. onCompiled(this);
  73938. }
  73939. return;
  73940. }
  73941. var currentIndex = 0;
  73942. var checkReady = function () {
  73943. if (!_this._scene || !_this._scene.getEngine()) {
  73944. return;
  73945. }
  73946. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  73947. currentIndex++;
  73948. if (currentIndex >= subMeshes.length) {
  73949. if (onCompiled) {
  73950. onCompiled(_this);
  73951. }
  73952. return;
  73953. }
  73954. }
  73955. setTimeout(checkReady, 16);
  73956. };
  73957. checkReady();
  73958. };
  73959. /**
  73960. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73961. * @param options Sets of optional options forcing the compilation with different modes
  73962. * @returns A promise that resolves when the compilation completes
  73963. */
  73964. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  73965. var _this = this;
  73966. return new Promise(function (resolve) {
  73967. _this.forceCompilation(function () {
  73968. resolve();
  73969. }, options);
  73970. });
  73971. };
  73972. /**
  73973. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  73974. * @param subMesh The submesh we want to render in the shadow map
  73975. * @param useInstances Defines wether will draw in the map using instances
  73976. * @returns true if ready otherwise, false
  73977. */
  73978. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  73979. var defines = [];
  73980. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73981. defines.push("#define FLOAT");
  73982. }
  73983. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73984. defines.push("#define ESM");
  73985. }
  73986. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  73987. defines.push("#define DEPTHTEXTURE");
  73988. }
  73989. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73990. var mesh = subMesh.getMesh();
  73991. var material = subMesh.getMaterial();
  73992. // Normal bias.
  73993. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73994. attribs.push(BABYLON.VertexBuffer.NormalKind);
  73995. defines.push("#define NORMAL");
  73996. if (mesh.nonUniformScaling) {
  73997. defines.push("#define NONUNIFORMSCALING");
  73998. }
  73999. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74000. defines.push("#define DIRECTIONINLIGHTDATA");
  74001. }
  74002. }
  74003. // Alpha test
  74004. if (material && material.needAlphaTesting()) {
  74005. var alphaTexture = material.getAlphaTestTexture();
  74006. if (alphaTexture) {
  74007. defines.push("#define ALPHATEST");
  74008. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74009. attribs.push(BABYLON.VertexBuffer.UVKind);
  74010. defines.push("#define UV1");
  74011. }
  74012. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74013. if (alphaTexture.coordinatesIndex === 1) {
  74014. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74015. defines.push("#define UV2");
  74016. }
  74017. }
  74018. }
  74019. }
  74020. // Bones
  74021. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74022. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74023. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74024. if (mesh.numBoneInfluencers > 4) {
  74025. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74026. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74027. }
  74028. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74029. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  74030. }
  74031. else {
  74032. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74033. }
  74034. // Morph targets
  74035. var manager = mesh.morphTargetManager;
  74036. var morphInfluencers = 0;
  74037. if (manager) {
  74038. if (manager.numInfluencers > 0) {
  74039. defines.push("#define MORPHTARGETS");
  74040. morphInfluencers = manager.numInfluencers;
  74041. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  74042. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  74043. }
  74044. }
  74045. // Instances
  74046. if (useInstances) {
  74047. defines.push("#define INSTANCES");
  74048. attribs.push("world0");
  74049. attribs.push("world1");
  74050. attribs.push("world2");
  74051. attribs.push("world3");
  74052. }
  74053. // Get correct effect
  74054. var join = defines.join("\n");
  74055. if (this._cachedDefines !== join) {
  74056. this._cachedDefines = join;
  74057. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  74058. }
  74059. if (!this._effect.isReady()) {
  74060. return false;
  74061. }
  74062. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74063. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  74064. this._initializeBlurRTTAndPostProcesses();
  74065. }
  74066. }
  74067. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  74068. return false;
  74069. }
  74070. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  74071. return false;
  74072. }
  74073. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  74074. return false;
  74075. }
  74076. return true;
  74077. };
  74078. /**
  74079. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  74080. * @param defines Defines of the material we want to update
  74081. * @param lightIndex Index of the light in the enabled light list of the material
  74082. */
  74083. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  74084. var scene = this._scene;
  74085. var light = this._light;
  74086. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74087. return;
  74088. }
  74089. defines["SHADOW" + lightIndex] = true;
  74090. if (this.useContactHardeningShadow) {
  74091. defines["SHADOWPCSS" + lightIndex] = true;
  74092. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74093. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74094. }
  74095. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74096. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74097. }
  74098. // else default to high.
  74099. }
  74100. if (this.usePercentageCloserFiltering) {
  74101. defines["SHADOWPCF" + lightIndex] = true;
  74102. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74103. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74104. }
  74105. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74106. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74107. }
  74108. // else default to high.
  74109. }
  74110. else if (this.usePoissonSampling) {
  74111. defines["SHADOWPOISSON" + lightIndex] = true;
  74112. }
  74113. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74114. defines["SHADOWESM" + lightIndex] = true;
  74115. }
  74116. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74117. defines["SHADOWCLOSEESM" + lightIndex] = true;
  74118. }
  74119. if (light.needCube()) {
  74120. defines["SHADOWCUBE" + lightIndex] = true;
  74121. }
  74122. };
  74123. /**
  74124. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  74125. * defined in the generator but impacting the effect).
  74126. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  74127. * @param effect The effect we are binfing the information for
  74128. */
  74129. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  74130. var light = this._light;
  74131. var scene = this._scene;
  74132. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74133. return;
  74134. }
  74135. var camera = scene.activeCamera;
  74136. if (!camera) {
  74137. return;
  74138. }
  74139. var shadowMap = this.getShadowMap();
  74140. if (!shadowMap) {
  74141. return;
  74142. }
  74143. if (!light.needCube()) {
  74144. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  74145. }
  74146. // Only PCF uses depth stencil texture.
  74147. if (this._filter === ShadowGenerator.FILTER_PCF) {
  74148. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74149. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74150. }
  74151. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  74152. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74153. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  74154. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74155. }
  74156. else {
  74157. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74158. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  74159. }
  74160. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  74161. };
  74162. /**
  74163. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  74164. * (eq to shadow prjection matrix * light transform matrix)
  74165. * @returns The transform matrix used to create the shadow map
  74166. */
  74167. ShadowGenerator.prototype.getTransformMatrix = function () {
  74168. var scene = this._scene;
  74169. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  74170. return this._transformMatrix;
  74171. }
  74172. this._currentRenderID = scene.getRenderId();
  74173. this._currentFaceIndexCache = this._currentFaceIndex;
  74174. var lightPosition = this._light.position;
  74175. if (this._light.computeTransformedInformation()) {
  74176. lightPosition = this._light.transformedPosition;
  74177. }
  74178. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  74179. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  74180. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  74181. }
  74182. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  74183. this._cachedPosition.copyFrom(lightPosition);
  74184. this._cachedDirection.copyFrom(this._lightDirection);
  74185. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  74186. var shadowMap = this.getShadowMap();
  74187. if (shadowMap) {
  74188. var renderList = shadowMap.renderList;
  74189. if (renderList) {
  74190. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  74191. }
  74192. }
  74193. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  74194. }
  74195. return this._transformMatrix;
  74196. };
  74197. /**
  74198. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  74199. * Cube and 2D textures for instance.
  74200. */
  74201. ShadowGenerator.prototype.recreateShadowMap = function () {
  74202. var shadowMap = this._shadowMap;
  74203. if (!shadowMap) {
  74204. return;
  74205. }
  74206. // Track render list.
  74207. var renderList = shadowMap.renderList;
  74208. // Clean up existing data.
  74209. this._disposeRTTandPostProcesses();
  74210. // Reinitializes.
  74211. this._initializeGenerator();
  74212. // Reaffect the filter to ensure a correct fallback if necessary.
  74213. this.filter = this.filter;
  74214. // Reaffect the filter.
  74215. this._applyFilterValues();
  74216. // Reaffect Render List.
  74217. this._shadowMap.renderList = renderList;
  74218. };
  74219. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  74220. if (this._shadowMap2) {
  74221. this._shadowMap2.dispose();
  74222. this._shadowMap2 = null;
  74223. }
  74224. if (this._boxBlurPostprocess) {
  74225. this._boxBlurPostprocess.dispose();
  74226. this._boxBlurPostprocess = null;
  74227. }
  74228. if (this._kernelBlurXPostprocess) {
  74229. this._kernelBlurXPostprocess.dispose();
  74230. this._kernelBlurXPostprocess = null;
  74231. }
  74232. if (this._kernelBlurYPostprocess) {
  74233. this._kernelBlurYPostprocess.dispose();
  74234. this._kernelBlurYPostprocess = null;
  74235. }
  74236. this._blurPostProcesses = [];
  74237. };
  74238. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  74239. if (this._shadowMap) {
  74240. this._shadowMap.dispose();
  74241. this._shadowMap = null;
  74242. }
  74243. this._disposeBlurPostProcesses();
  74244. };
  74245. /**
  74246. * Disposes the ShadowGenerator.
  74247. * Returns nothing.
  74248. */
  74249. ShadowGenerator.prototype.dispose = function () {
  74250. this._disposeRTTandPostProcesses();
  74251. if (this._light) {
  74252. this._light._shadowGenerator = null;
  74253. this._light._markMeshesAsLightDirty();
  74254. }
  74255. };
  74256. /**
  74257. * Serializes the shadow generator setup to a json object.
  74258. * @returns The serialized JSON object
  74259. */
  74260. ShadowGenerator.prototype.serialize = function () {
  74261. var serializationObject = {};
  74262. var shadowMap = this.getShadowMap();
  74263. if (!shadowMap) {
  74264. return serializationObject;
  74265. }
  74266. serializationObject.lightId = this._light.id;
  74267. serializationObject.mapSize = shadowMap.getRenderSize();
  74268. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  74269. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  74270. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74271. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74272. serializationObject.usePoissonSampling = this.usePoissonSampling;
  74273. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  74274. serializationObject.depthScale = this.depthScale;
  74275. serializationObject.darkness = this.getDarkness();
  74276. serializationObject.blurBoxOffset = this.blurBoxOffset;
  74277. serializationObject.blurKernel = this.blurKernel;
  74278. serializationObject.blurScale = this.blurScale;
  74279. serializationObject.useKernelBlur = this.useKernelBlur;
  74280. serializationObject.transparencyShadow = this._transparencyShadow;
  74281. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  74282. serializationObject.bias = this.bias;
  74283. serializationObject.normalBias = this.normalBias;
  74284. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  74285. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  74286. serializationObject.filteringQuality = this.filteringQuality;
  74287. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  74288. serializationObject.renderList = [];
  74289. if (shadowMap.renderList) {
  74290. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  74291. var mesh = shadowMap.renderList[meshIndex];
  74292. serializationObject.renderList.push(mesh.id);
  74293. }
  74294. }
  74295. return serializationObject;
  74296. };
  74297. /**
  74298. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  74299. * @param parsedShadowGenerator The JSON object to parse
  74300. * @param scene The scene to create the shadow map for
  74301. * @returns The parsed shadow generator
  74302. */
  74303. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  74304. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  74305. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  74306. var shadowMap = shadowGenerator.getShadowMap();
  74307. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  74308. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  74309. meshes.forEach(function (mesh) {
  74310. if (!shadowMap) {
  74311. return;
  74312. }
  74313. if (!shadowMap.renderList) {
  74314. shadowMap.renderList = [];
  74315. }
  74316. shadowMap.renderList.push(mesh);
  74317. });
  74318. }
  74319. if (parsedShadowGenerator.usePoissonSampling) {
  74320. shadowGenerator.usePoissonSampling = true;
  74321. }
  74322. else if (parsedShadowGenerator.useExponentialShadowMap) {
  74323. shadowGenerator.useExponentialShadowMap = true;
  74324. }
  74325. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  74326. shadowGenerator.useBlurExponentialShadowMap = true;
  74327. }
  74328. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  74329. shadowGenerator.useCloseExponentialShadowMap = true;
  74330. }
  74331. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  74332. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  74333. }
  74334. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  74335. shadowGenerator.usePercentageCloserFiltering = true;
  74336. }
  74337. else if (parsedShadowGenerator.useContactHardeningShadow) {
  74338. shadowGenerator.useContactHardeningShadow = true;
  74339. }
  74340. if (parsedShadowGenerator.filteringQuality) {
  74341. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  74342. }
  74343. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  74344. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  74345. }
  74346. // Backward compat
  74347. else if (parsedShadowGenerator.useVarianceShadowMap) {
  74348. shadowGenerator.useExponentialShadowMap = true;
  74349. }
  74350. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  74351. shadowGenerator.useBlurExponentialShadowMap = true;
  74352. }
  74353. if (parsedShadowGenerator.depthScale) {
  74354. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  74355. }
  74356. if (parsedShadowGenerator.blurScale) {
  74357. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  74358. }
  74359. if (parsedShadowGenerator.blurBoxOffset) {
  74360. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  74361. }
  74362. if (parsedShadowGenerator.useKernelBlur) {
  74363. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  74364. }
  74365. if (parsedShadowGenerator.blurKernel) {
  74366. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  74367. }
  74368. if (parsedShadowGenerator.bias !== undefined) {
  74369. shadowGenerator.bias = parsedShadowGenerator.bias;
  74370. }
  74371. if (parsedShadowGenerator.normalBias !== undefined) {
  74372. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  74373. }
  74374. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  74375. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  74376. }
  74377. if (parsedShadowGenerator.darkness) {
  74378. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  74379. }
  74380. if (parsedShadowGenerator.transparencyShadow) {
  74381. shadowGenerator.setTransparencyShadow(true);
  74382. }
  74383. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  74384. return shadowGenerator;
  74385. };
  74386. /**
  74387. * Shadow generator mode None: no filtering applied.
  74388. */
  74389. ShadowGenerator.FILTER_NONE = 0;
  74390. /**
  74391. * Shadow generator mode ESM: Exponential Shadow Mapping.
  74392. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74393. */
  74394. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  74395. /**
  74396. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  74397. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  74398. */
  74399. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  74400. /**
  74401. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  74402. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74403. */
  74404. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  74405. /**
  74406. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  74407. * edge artifacts on steep falloff.
  74408. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74409. */
  74410. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  74411. /**
  74412. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  74413. * edge artifacts on steep falloff.
  74414. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74415. */
  74416. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  74417. /**
  74418. * Shadow generator mode PCF: Percentage Closer Filtering
  74419. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74420. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  74421. */
  74422. ShadowGenerator.FILTER_PCF = 6;
  74423. /**
  74424. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  74425. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74426. * Contact Hardening
  74427. */
  74428. ShadowGenerator.FILTER_PCSS = 7;
  74429. /**
  74430. * Reserved for PCF and PCSS
  74431. * Highest Quality.
  74432. *
  74433. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  74434. *
  74435. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  74436. */
  74437. ShadowGenerator.QUALITY_HIGH = 0;
  74438. /**
  74439. * Reserved for PCF and PCSS
  74440. * Good tradeoff for quality/perf cross devices
  74441. *
  74442. * Execute PCF on a 3*3 kernel.
  74443. *
  74444. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  74445. */
  74446. ShadowGenerator.QUALITY_MEDIUM = 1;
  74447. /**
  74448. * Reserved for PCF and PCSS
  74449. * The lowest quality but the fastest.
  74450. *
  74451. * Execute PCF on a 1*1 kernel.
  74452. *
  74453. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  74454. */
  74455. ShadowGenerator.QUALITY_LOW = 2;
  74456. return ShadowGenerator;
  74457. }());
  74458. BABYLON.ShadowGenerator = ShadowGenerator;
  74459. })(BABYLON || (BABYLON = {}));
  74460. //# sourceMappingURL=babylon.shadowGenerator.js.map
  74461. var BABYLON;
  74462. (function (BABYLON) {
  74463. // Adds the parser to the scene parsers.
  74464. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  74465. // Shadows
  74466. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  74467. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  74468. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  74469. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  74470. // SG would be available on their associated lights
  74471. }
  74472. }
  74473. });
  74474. /**
  74475. * Defines the shadow generator component responsible to manage any shadow generators
  74476. * in a given scene.
  74477. */
  74478. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  74479. /**
  74480. * Creates a new instance of the component for the given scene
  74481. * @param scene Defines the scene to register the component in
  74482. */
  74483. function ShadowGeneratorSceneComponent(scene) {
  74484. /**
  74485. * The component name helpfull to identify the component in the list of scene components.
  74486. */
  74487. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  74488. this.scene = scene;
  74489. }
  74490. /**
  74491. * Registers the component in a given scene
  74492. */
  74493. ShadowGeneratorSceneComponent.prototype.register = function () {
  74494. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  74495. };
  74496. /**
  74497. * Rebuilds the elements related to this component in case of
  74498. * context lost for instance.
  74499. */
  74500. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  74501. // Nothing To Do Here.
  74502. };
  74503. /**
  74504. * Serializes the component data to the specified json object
  74505. * @param serializationObject The object to serialize to
  74506. */
  74507. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  74508. // Shadows
  74509. serializationObject.shadowGenerators = [];
  74510. var lights = this.scene.lights;
  74511. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  74512. var light = lights_1[_i];
  74513. var shadowGenerator = light.getShadowGenerator();
  74514. if (shadowGenerator) {
  74515. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  74516. }
  74517. }
  74518. };
  74519. /**
  74520. * Adds all the element from the container to the scene
  74521. * @param container the container holding the elements
  74522. */
  74523. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  74524. // Nothing To Do Here. (directly attached to a light)
  74525. };
  74526. /**
  74527. * Removes all the elements in the container from the scene
  74528. * @param container contains the elements to remove
  74529. */
  74530. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  74531. // Nothing To Do Here. (directly attached to a light)
  74532. };
  74533. /**
  74534. * Rebuilds the elements related to this component in case of
  74535. * context lost for instance.
  74536. */
  74537. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  74538. // Nothing To Do Here.
  74539. };
  74540. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  74541. // Shadows
  74542. var scene = this.scene;
  74543. if (this.scene.shadowsEnabled) {
  74544. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  74545. var light = scene.lights[lightIndex];
  74546. var shadowGenerator = light.getShadowGenerator();
  74547. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  74548. var shadowMap = (shadowGenerator.getShadowMap());
  74549. if (scene.textures.indexOf(shadowMap) !== -1) {
  74550. renderTargets.push(shadowMap);
  74551. }
  74552. }
  74553. }
  74554. }
  74555. };
  74556. return ShadowGeneratorSceneComponent;
  74557. }());
  74558. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  74559. })(BABYLON || (BABYLON = {}));
  74560. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  74561. var BABYLON;
  74562. (function (BABYLON) {
  74563. var DefaultLoadingScreen = /** @class */ (function () {
  74564. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  74565. if (_loadingText === void 0) { _loadingText = ""; }
  74566. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  74567. var _this = this;
  74568. this._renderingCanvas = _renderingCanvas;
  74569. this._loadingText = _loadingText;
  74570. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  74571. // Resize
  74572. this._resizeLoadingUI = function () {
  74573. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  74574. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  74575. if (!_this._loadingDiv) {
  74576. return;
  74577. }
  74578. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  74579. _this._loadingDiv.style.left = canvasRect.left + "px";
  74580. _this._loadingDiv.style.top = canvasRect.top + "px";
  74581. _this._loadingDiv.style.width = canvasRect.width + "px";
  74582. _this._loadingDiv.style.height = canvasRect.height + "px";
  74583. };
  74584. }
  74585. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  74586. if (this._loadingDiv) {
  74587. // Do not add a loading screen if there is already one
  74588. return;
  74589. }
  74590. this._loadingDiv = document.createElement("div");
  74591. this._loadingDiv.id = "babylonjsLoadingDiv";
  74592. this._loadingDiv.style.opacity = "0";
  74593. this._loadingDiv.style.transition = "opacity 1.5s ease";
  74594. this._loadingDiv.style.pointerEvents = "none";
  74595. // Loading text
  74596. this._loadingTextDiv = document.createElement("div");
  74597. this._loadingTextDiv.style.position = "absolute";
  74598. this._loadingTextDiv.style.left = "0";
  74599. this._loadingTextDiv.style.top = "50%";
  74600. this._loadingTextDiv.style.marginTop = "80px";
  74601. this._loadingTextDiv.style.width = "100%";
  74602. this._loadingTextDiv.style.height = "20px";
  74603. this._loadingTextDiv.style.fontFamily = "Arial";
  74604. this._loadingTextDiv.style.fontSize = "14px";
  74605. this._loadingTextDiv.style.color = "white";
  74606. this._loadingTextDiv.style.textAlign = "center";
  74607. this._loadingTextDiv.innerHTML = "Loading";
  74608. this._loadingDiv.appendChild(this._loadingTextDiv);
  74609. //set the predefined text
  74610. this._loadingTextDiv.innerHTML = this._loadingText;
  74611. // Generating keyframes
  74612. var style = document.createElement('style');
  74613. style.type = 'text/css';
  74614. 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 }";
  74615. style.innerHTML = keyFrames;
  74616. document.getElementsByTagName('head')[0].appendChild(style);
  74617. // Loading img
  74618. var imgBack = new Image();
  74619. 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";
  74620. imgBack.style.position = "absolute";
  74621. imgBack.style.left = "50%";
  74622. imgBack.style.top = "50%";
  74623. imgBack.style.marginLeft = "-60px";
  74624. imgBack.style.marginTop = "-60px";
  74625. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  74626. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  74627. imgBack.style.transformOrigin = "50% 50%";
  74628. imgBack.style.webkitTransformOrigin = "50% 50%";
  74629. this._loadingDiv.appendChild(imgBack);
  74630. this._resizeLoadingUI();
  74631. window.addEventListener("resize", this._resizeLoadingUI);
  74632. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  74633. document.body.appendChild(this._loadingDiv);
  74634. this._loadingDiv.style.opacity = "1";
  74635. };
  74636. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  74637. var _this = this;
  74638. if (!this._loadingDiv) {
  74639. return;
  74640. }
  74641. var onTransitionEnd = function () {
  74642. if (!_this._loadingDiv) {
  74643. return;
  74644. }
  74645. document.body.removeChild(_this._loadingDiv);
  74646. window.removeEventListener("resize", _this._resizeLoadingUI);
  74647. _this._loadingDiv = null;
  74648. };
  74649. this._loadingDiv.style.opacity = "0";
  74650. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  74651. };
  74652. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  74653. set: function (text) {
  74654. this._loadingText = text;
  74655. if (this._loadingTextDiv) {
  74656. this._loadingTextDiv.innerHTML = this._loadingText;
  74657. }
  74658. },
  74659. enumerable: true,
  74660. configurable: true
  74661. });
  74662. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  74663. get: function () {
  74664. return this._loadingDivBackgroundColor;
  74665. },
  74666. set: function (color) {
  74667. this._loadingDivBackgroundColor = color;
  74668. if (!this._loadingDiv) {
  74669. return;
  74670. }
  74671. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  74672. },
  74673. enumerable: true,
  74674. configurable: true
  74675. });
  74676. return DefaultLoadingScreen;
  74677. }());
  74678. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  74679. })(BABYLON || (BABYLON = {}));
  74680. //# sourceMappingURL=babylon.loadingScreen.js.map
  74681. var BABYLON;
  74682. (function (BABYLON) {
  74683. var SceneLoaderProgressEvent = /** @class */ (function () {
  74684. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  74685. this.lengthComputable = lengthComputable;
  74686. this.loaded = loaded;
  74687. this.total = total;
  74688. }
  74689. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  74690. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  74691. };
  74692. return SceneLoaderProgressEvent;
  74693. }());
  74694. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  74695. var SceneLoader = /** @class */ (function () {
  74696. function SceneLoader() {
  74697. }
  74698. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  74699. get: function () {
  74700. return 0;
  74701. },
  74702. enumerable: true,
  74703. configurable: true
  74704. });
  74705. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  74706. get: function () {
  74707. return 1;
  74708. },
  74709. enumerable: true,
  74710. configurable: true
  74711. });
  74712. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  74713. get: function () {
  74714. return 2;
  74715. },
  74716. enumerable: true,
  74717. configurable: true
  74718. });
  74719. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  74720. get: function () {
  74721. return 3;
  74722. },
  74723. enumerable: true,
  74724. configurable: true
  74725. });
  74726. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  74727. get: function () {
  74728. return SceneLoader._ForceFullSceneLoadingForIncremental;
  74729. },
  74730. set: function (value) {
  74731. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  74732. },
  74733. enumerable: true,
  74734. configurable: true
  74735. });
  74736. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  74737. get: function () {
  74738. return SceneLoader._ShowLoadingScreen;
  74739. },
  74740. set: function (value) {
  74741. SceneLoader._ShowLoadingScreen = value;
  74742. },
  74743. enumerable: true,
  74744. configurable: true
  74745. });
  74746. Object.defineProperty(SceneLoader, "loggingLevel", {
  74747. get: function () {
  74748. return SceneLoader._loggingLevel;
  74749. },
  74750. set: function (value) {
  74751. SceneLoader._loggingLevel = value;
  74752. },
  74753. enumerable: true,
  74754. configurable: true
  74755. });
  74756. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  74757. get: function () {
  74758. return SceneLoader._CleanBoneMatrixWeights;
  74759. },
  74760. set: function (value) {
  74761. SceneLoader._CleanBoneMatrixWeights = value;
  74762. },
  74763. enumerable: true,
  74764. configurable: true
  74765. });
  74766. SceneLoader._getDefaultPlugin = function () {
  74767. return SceneLoader._registeredPlugins[".babylon"];
  74768. };
  74769. SceneLoader._getPluginForExtension = function (extension) {
  74770. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  74771. if (registeredPlugin) {
  74772. return registeredPlugin;
  74773. }
  74774. 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");
  74775. return SceneLoader._getDefaultPlugin();
  74776. };
  74777. SceneLoader._getPluginForDirectLoad = function (data) {
  74778. for (var extension in SceneLoader._registeredPlugins) {
  74779. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  74780. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  74781. return SceneLoader._registeredPlugins[extension];
  74782. }
  74783. }
  74784. return SceneLoader._getDefaultPlugin();
  74785. };
  74786. SceneLoader._getPluginForFilename = function (sceneFilename) {
  74787. var queryStringPosition = sceneFilename.indexOf("?");
  74788. if (queryStringPosition !== -1) {
  74789. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  74790. }
  74791. var dotPosition = sceneFilename.lastIndexOf(".");
  74792. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  74793. return SceneLoader._getPluginForExtension(extension);
  74794. };
  74795. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  74796. SceneLoader._getDirectLoad = function (sceneFilename) {
  74797. if (sceneFilename.substr(0, 5) === "data:") {
  74798. return sceneFilename.substr(5);
  74799. }
  74800. return null;
  74801. };
  74802. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  74803. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  74804. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  74805. var plugin;
  74806. if (registeredPlugin.plugin.createPlugin) {
  74807. plugin = registeredPlugin.plugin.createPlugin();
  74808. }
  74809. else {
  74810. plugin = registeredPlugin.plugin;
  74811. }
  74812. var useArrayBuffer = registeredPlugin.isBinary;
  74813. var database;
  74814. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  74815. var dataCallback = function (data, responseURL) {
  74816. if (scene.isDisposed) {
  74817. onError("Scene has been disposed");
  74818. return;
  74819. }
  74820. scene.database = database;
  74821. onSuccess(plugin, data, responseURL);
  74822. };
  74823. var request = null;
  74824. var pluginDisposed = false;
  74825. var onDisposeObservable = plugin.onDisposeObservable;
  74826. if (onDisposeObservable) {
  74827. onDisposeObservable.add(function () {
  74828. pluginDisposed = true;
  74829. if (request) {
  74830. request.abort();
  74831. request = null;
  74832. }
  74833. onDispose();
  74834. });
  74835. }
  74836. var manifestChecked = function () {
  74837. if (pluginDisposed) {
  74838. return;
  74839. }
  74840. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  74841. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  74842. } : undefined, database, useArrayBuffer, function (request, exception) {
  74843. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  74844. });
  74845. };
  74846. if (directLoad) {
  74847. dataCallback(directLoad);
  74848. return plugin;
  74849. }
  74850. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  74851. var engine = scene.getEngine();
  74852. var canUseOfflineSupport = engine.enableOfflineSupport;
  74853. if (canUseOfflineSupport) {
  74854. // Also check for exceptions
  74855. var exceptionFound = false;
  74856. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  74857. var regex = _a[_i];
  74858. if (regex.test(fileInfo.url)) {
  74859. exceptionFound = true;
  74860. break;
  74861. }
  74862. }
  74863. canUseOfflineSupport = !exceptionFound;
  74864. }
  74865. if (canUseOfflineSupport) {
  74866. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  74867. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  74868. }
  74869. else {
  74870. manifestChecked();
  74871. }
  74872. }
  74873. // Loading file from disk via input file or drag'n'drop
  74874. else {
  74875. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  74876. if (file) {
  74877. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  74878. }
  74879. else {
  74880. onError("Unable to find file named " + fileInfo.name);
  74881. }
  74882. }
  74883. return plugin;
  74884. };
  74885. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  74886. var url;
  74887. var name;
  74888. if (!sceneFilename) {
  74889. url = rootUrl;
  74890. name = BABYLON.Tools.GetFilename(rootUrl);
  74891. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  74892. }
  74893. else {
  74894. if (sceneFilename.substr(0, 1) === "/") {
  74895. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  74896. return null;
  74897. }
  74898. url = rootUrl + sceneFilename;
  74899. name = sceneFilename;
  74900. }
  74901. ;
  74902. return {
  74903. url: url,
  74904. rootUrl: rootUrl,
  74905. name: name
  74906. };
  74907. };
  74908. // Public functions
  74909. SceneLoader.GetPluginForExtension = function (extension) {
  74910. return SceneLoader._getPluginForExtension(extension).plugin;
  74911. };
  74912. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  74913. return !!SceneLoader._registeredPlugins[extension];
  74914. };
  74915. SceneLoader.RegisterPlugin = function (plugin) {
  74916. if (typeof plugin.extensions === "string") {
  74917. var extension = plugin.extensions;
  74918. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74919. plugin: plugin,
  74920. isBinary: false
  74921. };
  74922. }
  74923. else {
  74924. var extensions = plugin.extensions;
  74925. Object.keys(extensions).forEach(function (extension) {
  74926. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74927. plugin: plugin,
  74928. isBinary: extensions[extension].isBinary
  74929. };
  74930. });
  74931. }
  74932. };
  74933. /**
  74934. * Import meshes into a scene
  74935. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74936. * @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)
  74937. * @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)
  74938. * @param scene the instance of BABYLON.Scene to append to
  74939. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  74940. * @param onProgress a callback with a progress event for each file being loaded
  74941. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74942. * @param pluginExtension the extension used to determine the plugin
  74943. * @returns The loaded plugin
  74944. */
  74945. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74946. if (sceneFilename === void 0) { sceneFilename = ""; }
  74947. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74948. if (onSuccess === void 0) { onSuccess = null; }
  74949. if (onProgress === void 0) { onProgress = null; }
  74950. if (onError === void 0) { onError = null; }
  74951. if (pluginExtension === void 0) { pluginExtension = null; }
  74952. if (!scene) {
  74953. BABYLON.Tools.Error("No scene available to import mesh to");
  74954. return null;
  74955. }
  74956. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74957. if (!fileInfo) {
  74958. return null;
  74959. }
  74960. var loadingToken = {};
  74961. scene._addPendingData(loadingToken);
  74962. var disposeHandler = function () {
  74963. scene._removePendingData(loadingToken);
  74964. };
  74965. var errorHandler = function (message, exception) {
  74966. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  74967. if (onError) {
  74968. onError(scene, errorMessage, exception);
  74969. }
  74970. else {
  74971. BABYLON.Tools.Error(errorMessage);
  74972. // should the exception be thrown?
  74973. }
  74974. disposeHandler();
  74975. };
  74976. var progressHandler = onProgress ? function (event) {
  74977. try {
  74978. onProgress(event);
  74979. }
  74980. catch (e) {
  74981. errorHandler("Error in onProgress callback", e);
  74982. }
  74983. } : undefined;
  74984. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  74985. scene.importedMeshesFiles.push(fileInfo.url);
  74986. if (onSuccess) {
  74987. try {
  74988. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  74989. }
  74990. catch (e) {
  74991. errorHandler("Error in onSuccess callback", e);
  74992. }
  74993. }
  74994. scene._removePendingData(loadingToken);
  74995. };
  74996. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74997. if (plugin.rewriteRootURL) {
  74998. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  74999. }
  75000. if (plugin.importMesh) {
  75001. var syncedPlugin = plugin;
  75002. var meshes = new Array();
  75003. var particleSystems = new Array();
  75004. var skeletons = new Array();
  75005. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  75006. return;
  75007. }
  75008. scene.loadingPluginName = plugin.name;
  75009. successHandler(meshes, particleSystems, skeletons, []);
  75010. }
  75011. else {
  75012. var asyncedPlugin = plugin;
  75013. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  75014. scene.loadingPluginName = plugin.name;
  75015. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  75016. }).catch(function (error) {
  75017. errorHandler(error.message, error);
  75018. });
  75019. }
  75020. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75021. };
  75022. /**
  75023. * Import meshes into a scene
  75024. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75025. * @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)
  75026. * @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)
  75027. * @param scene the instance of BABYLON.Scene to append to
  75028. * @param onProgress a callback with a progress event for each file being loaded
  75029. * @param pluginExtension the extension used to determine the plugin
  75030. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  75031. */
  75032. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75033. if (sceneFilename === void 0) { sceneFilename = ""; }
  75034. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75035. if (onProgress === void 0) { onProgress = null; }
  75036. if (pluginExtension === void 0) { pluginExtension = null; }
  75037. return new Promise(function (resolve, reject) {
  75038. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  75039. resolve({
  75040. meshes: meshes,
  75041. particleSystems: particleSystems,
  75042. skeletons: skeletons,
  75043. animationGroups: animationGroups
  75044. });
  75045. }, onProgress, function (scene, message, exception) {
  75046. reject(exception || new Error(message));
  75047. }, pluginExtension);
  75048. });
  75049. };
  75050. /**
  75051. * Load a scene
  75052. * @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)
  75053. * @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)
  75054. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75055. * @param onSuccess a callback with the scene when import succeeds
  75056. * @param onProgress a callback with a progress event for each file being loaded
  75057. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75058. * @param pluginExtension the extension used to determine the plugin
  75059. * @returns The loaded plugin
  75060. */
  75061. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  75062. if (onSuccess === void 0) { onSuccess = null; }
  75063. if (onProgress === void 0) { onProgress = null; }
  75064. if (onError === void 0) { onError = null; }
  75065. if (pluginExtension === void 0) { pluginExtension = null; }
  75066. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  75067. };
  75068. /**
  75069. * Load a scene
  75070. * @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)
  75071. * @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)
  75072. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75073. * @param onProgress a callback with a progress event for each file being loaded
  75074. * @param pluginExtension the extension used to determine the plugin
  75075. * @returns The loaded scene
  75076. */
  75077. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  75078. if (onProgress === void 0) { onProgress = null; }
  75079. if (pluginExtension === void 0) { pluginExtension = null; }
  75080. return new Promise(function (resolve, reject) {
  75081. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  75082. resolve(scene);
  75083. }, onProgress, function (scene, message, exception) {
  75084. reject(exception || new Error(message));
  75085. }, pluginExtension);
  75086. });
  75087. };
  75088. /**
  75089. * Append a scene
  75090. * @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)
  75091. * @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)
  75092. * @param scene is the instance of BABYLON.Scene to append to
  75093. * @param onSuccess a callback with the scene when import succeeds
  75094. * @param onProgress a callback with a progress event for each file being loaded
  75095. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75096. * @param pluginExtension the extension used to determine the plugin
  75097. * @returns The loaded plugin
  75098. */
  75099. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75100. if (sceneFilename === void 0) { sceneFilename = ""; }
  75101. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75102. if (onSuccess === void 0) { onSuccess = null; }
  75103. if (onProgress === void 0) { onProgress = null; }
  75104. if (onError === void 0) { onError = null; }
  75105. if (pluginExtension === void 0) { pluginExtension = null; }
  75106. if (!scene) {
  75107. BABYLON.Tools.Error("No scene available to append to");
  75108. return null;
  75109. }
  75110. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75111. if (!fileInfo) {
  75112. return null;
  75113. }
  75114. if (SceneLoader.ShowLoadingScreen) {
  75115. scene.getEngine().displayLoadingUI();
  75116. }
  75117. var loadingToken = {};
  75118. scene._addPendingData(loadingToken);
  75119. var disposeHandler = function () {
  75120. scene._removePendingData(loadingToken);
  75121. scene.getEngine().hideLoadingUI();
  75122. };
  75123. var errorHandler = function (message, exception) {
  75124. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  75125. if (onError) {
  75126. onError(scene, errorMessage, exception);
  75127. }
  75128. else {
  75129. BABYLON.Tools.Error(errorMessage);
  75130. // should the exception be thrown?
  75131. }
  75132. disposeHandler();
  75133. };
  75134. var progressHandler = onProgress ? function (event) {
  75135. try {
  75136. onProgress(event);
  75137. }
  75138. catch (e) {
  75139. errorHandler("Error in onProgress callback", e);
  75140. }
  75141. } : undefined;
  75142. var successHandler = function () {
  75143. if (onSuccess) {
  75144. try {
  75145. onSuccess(scene);
  75146. }
  75147. catch (e) {
  75148. errorHandler("Error in onSuccess callback", e);
  75149. }
  75150. }
  75151. scene._removePendingData(loadingToken);
  75152. };
  75153. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75154. if (plugin.load) {
  75155. var syncedPlugin = plugin;
  75156. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  75157. return;
  75158. }
  75159. scene.loadingPluginName = plugin.name;
  75160. successHandler();
  75161. }
  75162. else {
  75163. var asyncedPlugin = plugin;
  75164. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  75165. scene.loadingPluginName = plugin.name;
  75166. successHandler();
  75167. }).catch(function (error) {
  75168. errorHandler(error.message, error);
  75169. });
  75170. }
  75171. if (SceneLoader.ShowLoadingScreen) {
  75172. scene.executeWhenReady(function () {
  75173. scene.getEngine().hideLoadingUI();
  75174. });
  75175. }
  75176. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75177. };
  75178. /**
  75179. * Append a scene
  75180. * @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)
  75181. * @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)
  75182. * @param scene is the instance of BABYLON.Scene to append to
  75183. * @param onProgress a callback with a progress event for each file being loaded
  75184. * @param pluginExtension the extension used to determine the plugin
  75185. * @returns The given scene
  75186. */
  75187. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75188. if (sceneFilename === void 0) { sceneFilename = ""; }
  75189. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75190. if (onProgress === void 0) { onProgress = null; }
  75191. if (pluginExtension === void 0) { pluginExtension = null; }
  75192. return new Promise(function (resolve, reject) {
  75193. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  75194. resolve(scene);
  75195. }, onProgress, function (scene, message, exception) {
  75196. reject(exception || new Error(message));
  75197. }, pluginExtension);
  75198. });
  75199. };
  75200. /**
  75201. * Load a scene into an asset container
  75202. * @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)
  75203. * @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)
  75204. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  75205. * @param onSuccess a callback with the scene when import succeeds
  75206. * @param onProgress a callback with a progress event for each file being loaded
  75207. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75208. * @param pluginExtension the extension used to determine the plugin
  75209. * @returns The loaded plugin
  75210. */
  75211. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75212. if (sceneFilename === void 0) { sceneFilename = ""; }
  75213. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75214. if (onSuccess === void 0) { onSuccess = null; }
  75215. if (onProgress === void 0) { onProgress = null; }
  75216. if (onError === void 0) { onError = null; }
  75217. if (pluginExtension === void 0) { pluginExtension = null; }
  75218. if (!scene) {
  75219. BABYLON.Tools.Error("No scene available to load asset container to");
  75220. return null;
  75221. }
  75222. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75223. if (!fileInfo) {
  75224. return null;
  75225. }
  75226. var loadingToken = {};
  75227. scene._addPendingData(loadingToken);
  75228. var disposeHandler = function () {
  75229. scene._removePendingData(loadingToken);
  75230. };
  75231. var errorHandler = function (message, exception) {
  75232. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  75233. if (onError) {
  75234. onError(scene, errorMessage, exception);
  75235. }
  75236. else {
  75237. BABYLON.Tools.Error(errorMessage);
  75238. // should the exception be thrown?
  75239. }
  75240. disposeHandler();
  75241. };
  75242. var progressHandler = onProgress ? function (event) {
  75243. try {
  75244. onProgress(event);
  75245. }
  75246. catch (e) {
  75247. errorHandler("Error in onProgress callback", e);
  75248. }
  75249. } : undefined;
  75250. var successHandler = function (assets) {
  75251. if (onSuccess) {
  75252. try {
  75253. onSuccess(assets);
  75254. }
  75255. catch (e) {
  75256. errorHandler("Error in onSuccess callback", e);
  75257. }
  75258. }
  75259. scene._removePendingData(loadingToken);
  75260. };
  75261. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75262. if (plugin.loadAssetContainer) {
  75263. var syncedPlugin = plugin;
  75264. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  75265. if (!assetContainer) {
  75266. return;
  75267. }
  75268. scene.loadingPluginName = plugin.name;
  75269. successHandler(assetContainer);
  75270. }
  75271. else if (plugin.loadAssetContainerAsync) {
  75272. var asyncedPlugin = plugin;
  75273. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  75274. scene.loadingPluginName = plugin.name;
  75275. successHandler(assetContainer);
  75276. }).catch(function (error) {
  75277. errorHandler(error.message, error);
  75278. });
  75279. }
  75280. else {
  75281. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  75282. }
  75283. if (SceneLoader.ShowLoadingScreen) {
  75284. scene.executeWhenReady(function () {
  75285. scene.getEngine().hideLoadingUI();
  75286. });
  75287. }
  75288. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75289. };
  75290. /**
  75291. * Load a scene into an asset container
  75292. * @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)
  75293. * @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)
  75294. * @param scene is the instance of BABYLON.Scene to append to
  75295. * @param onProgress a callback with a progress event for each file being loaded
  75296. * @param pluginExtension the extension used to determine the plugin
  75297. * @returns The loaded asset container
  75298. */
  75299. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75300. if (sceneFilename === void 0) { sceneFilename = ""; }
  75301. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75302. if (onProgress === void 0) { onProgress = null; }
  75303. if (pluginExtension === void 0) { pluginExtension = null; }
  75304. return new Promise(function (resolve, reject) {
  75305. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  75306. resolve(assetContainer);
  75307. }, onProgress, function (scene, message, exception) {
  75308. reject(exception || new Error(message));
  75309. }, pluginExtension);
  75310. });
  75311. };
  75312. // Flags
  75313. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  75314. SceneLoader._ShowLoadingScreen = true;
  75315. SceneLoader._CleanBoneMatrixWeights = false;
  75316. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  75317. // Members
  75318. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  75319. SceneLoader._registeredPlugins = {};
  75320. return SceneLoader;
  75321. }());
  75322. BABYLON.SceneLoader = SceneLoader;
  75323. ;
  75324. })(BABYLON || (BABYLON = {}));
  75325. //# sourceMappingURL=babylon.sceneLoader.js.map
  75326. var BABYLON;
  75327. (function (BABYLON) {
  75328. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  75329. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75330. var parsedMaterial = parsedData.materials[index];
  75331. if (parsedMaterial.id === id) {
  75332. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75333. }
  75334. }
  75335. return null;
  75336. };
  75337. var isDescendantOf = function (mesh, names, hierarchyIds) {
  75338. for (var i in names) {
  75339. if (mesh.name === names[i]) {
  75340. hierarchyIds.push(mesh.id);
  75341. return true;
  75342. }
  75343. }
  75344. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  75345. hierarchyIds.push(mesh.id);
  75346. return true;
  75347. }
  75348. return false;
  75349. };
  75350. var logOperation = function (operation, producer) {
  75351. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  75352. };
  75353. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  75354. if (addToScene === void 0) { addToScene = false; }
  75355. var container = new BABYLON.AssetContainer(scene);
  75356. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75357. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75358. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75359. // and avoid problems with multiple concurrent .babylon loads.
  75360. var log = "importScene has failed JSON parse";
  75361. try {
  75362. var parsedData = JSON.parse(data);
  75363. log = "";
  75364. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75365. var index;
  75366. var cache;
  75367. // Lights
  75368. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  75369. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  75370. var parsedLight = parsedData.lights[index];
  75371. var light = BABYLON.Light.Parse(parsedLight, scene);
  75372. if (light) {
  75373. container.lights.push(light);
  75374. log += (index === 0 ? "\n\tLights:" : "");
  75375. log += "\n\t\t" + light.toString(fullDetails);
  75376. }
  75377. }
  75378. }
  75379. // Animations
  75380. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  75381. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  75382. var parsedAnimation = parsedData.animations[index];
  75383. var animation = BABYLON.Animation.Parse(parsedAnimation);
  75384. scene.animations.push(animation);
  75385. container.animations.push(animation);
  75386. log += (index === 0 ? "\n\tAnimations:" : "");
  75387. log += "\n\t\t" + animation.toString(fullDetails);
  75388. }
  75389. }
  75390. // Materials
  75391. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  75392. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75393. var parsedMaterial = parsedData.materials[index];
  75394. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75395. container.materials.push(mat);
  75396. log += (index === 0 ? "\n\tMaterials:" : "");
  75397. log += "\n\t\t" + mat.toString(fullDetails);
  75398. }
  75399. }
  75400. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75401. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  75402. var parsedMultiMaterial = parsedData.multiMaterials[index];
  75403. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75404. container.multiMaterials.push(mmat);
  75405. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  75406. log += "\n\t\t" + mmat.toString(fullDetails);
  75407. }
  75408. }
  75409. // Morph targets
  75410. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75411. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75412. var managerData = _a[_i];
  75413. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  75414. }
  75415. }
  75416. // Skeletons
  75417. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75418. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  75419. var parsedSkeleton = parsedData.skeletons[index];
  75420. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75421. container.skeletons.push(skeleton);
  75422. log += (index === 0 ? "\n\tSkeletons:" : "");
  75423. log += "\n\t\t" + skeleton.toString(fullDetails);
  75424. }
  75425. }
  75426. // Geometries
  75427. var geometries = parsedData.geometries;
  75428. if (geometries !== undefined && geometries !== null) {
  75429. var addedGeometry = new Array();
  75430. // Boxes
  75431. var boxes = geometries.boxes;
  75432. if (boxes !== undefined && boxes !== null) {
  75433. for (index = 0, cache = boxes.length; index < cache; index++) {
  75434. var parsedBox = boxes[index];
  75435. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  75436. }
  75437. }
  75438. // Spheres
  75439. var spheres = geometries.spheres;
  75440. if (spheres !== undefined && spheres !== null) {
  75441. for (index = 0, cache = spheres.length; index < cache; index++) {
  75442. var parsedSphere = spheres[index];
  75443. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  75444. }
  75445. }
  75446. // Cylinders
  75447. var cylinders = geometries.cylinders;
  75448. if (cylinders !== undefined && cylinders !== null) {
  75449. for (index = 0, cache = cylinders.length; index < cache; index++) {
  75450. var parsedCylinder = cylinders[index];
  75451. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  75452. }
  75453. }
  75454. // Toruses
  75455. var toruses = geometries.toruses;
  75456. if (toruses !== undefined && toruses !== null) {
  75457. for (index = 0, cache = toruses.length; index < cache; index++) {
  75458. var parsedTorus = toruses[index];
  75459. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  75460. }
  75461. }
  75462. // Grounds
  75463. var grounds = geometries.grounds;
  75464. if (grounds !== undefined && grounds !== null) {
  75465. for (index = 0, cache = grounds.length; index < cache; index++) {
  75466. var parsedGround = grounds[index];
  75467. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  75468. }
  75469. }
  75470. // Planes
  75471. var planes = geometries.planes;
  75472. if (planes !== undefined && planes !== null) {
  75473. for (index = 0, cache = planes.length; index < cache; index++) {
  75474. var parsedPlane = planes[index];
  75475. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  75476. }
  75477. }
  75478. // TorusKnots
  75479. var torusKnots = geometries.torusKnots;
  75480. if (torusKnots !== undefined && torusKnots !== null) {
  75481. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  75482. var parsedTorusKnot = torusKnots[index];
  75483. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  75484. }
  75485. }
  75486. // VertexData
  75487. var vertexData = geometries.vertexData;
  75488. if (vertexData !== undefined && vertexData !== null) {
  75489. for (index = 0, cache = vertexData.length; index < cache; index++) {
  75490. var parsedVertexData = vertexData[index];
  75491. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  75492. }
  75493. }
  75494. addedGeometry.forEach(function (g) {
  75495. if (g) {
  75496. container.geometries.push(g);
  75497. }
  75498. });
  75499. }
  75500. // Transform nodes
  75501. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  75502. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  75503. var parsedTransformNode = parsedData.transformNodes[index];
  75504. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  75505. container.transformNodes.push(node);
  75506. }
  75507. }
  75508. // Meshes
  75509. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  75510. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  75511. var parsedMesh = parsedData.meshes[index];
  75512. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75513. container.meshes.push(mesh);
  75514. log += (index === 0 ? "\n\tMeshes:" : "");
  75515. log += "\n\t\t" + mesh.toString(fullDetails);
  75516. }
  75517. }
  75518. // Cameras
  75519. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  75520. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  75521. var parsedCamera = parsedData.cameras[index];
  75522. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  75523. container.cameras.push(camera);
  75524. log += (index === 0 ? "\n\tCameras:" : "");
  75525. log += "\n\t\t" + camera.toString(fullDetails);
  75526. }
  75527. }
  75528. // Animation Groups
  75529. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  75530. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  75531. var parsedAnimationGroup = parsedData.animationGroups[index];
  75532. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  75533. container.animationGroups.push(animationGroup);
  75534. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  75535. log += "\n\t\t" + animationGroup.toString(fullDetails);
  75536. }
  75537. }
  75538. // Browsing all the graph to connect the dots
  75539. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  75540. var camera = scene.cameras[index];
  75541. if (camera._waitingParentId) {
  75542. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  75543. camera._waitingParentId = null;
  75544. }
  75545. }
  75546. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  75547. var light_1 = scene.lights[index];
  75548. if (light_1 && light_1._waitingParentId) {
  75549. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  75550. light_1._waitingParentId = null;
  75551. }
  75552. }
  75553. // Connect parents & children and parse actions
  75554. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  75555. var transformNode = scene.transformNodes[index];
  75556. if (transformNode._waitingParentId) {
  75557. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  75558. transformNode._waitingParentId = null;
  75559. }
  75560. }
  75561. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75562. var mesh = scene.meshes[index];
  75563. if (mesh._waitingParentId) {
  75564. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  75565. mesh._waitingParentId = null;
  75566. }
  75567. }
  75568. // freeze world matrix application
  75569. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75570. var currentMesh = scene.meshes[index];
  75571. if (currentMesh._waitingFreezeWorldMatrix) {
  75572. currentMesh.freezeWorldMatrix();
  75573. currentMesh._waitingFreezeWorldMatrix = null;
  75574. }
  75575. else {
  75576. currentMesh.computeWorldMatrix(true);
  75577. }
  75578. }
  75579. // Lights exclusions / inclusions
  75580. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  75581. var light_2 = scene.lights[index];
  75582. // Excluded check
  75583. if (light_2._excludedMeshesIds.length > 0) {
  75584. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  75585. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  75586. if (excludedMesh) {
  75587. light_2.excludedMeshes.push(excludedMesh);
  75588. }
  75589. }
  75590. light_2._excludedMeshesIds = [];
  75591. }
  75592. // Included check
  75593. if (light_2._includedOnlyMeshesIds.length > 0) {
  75594. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  75595. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  75596. if (includedOnlyMesh) {
  75597. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  75598. }
  75599. }
  75600. light_2._includedOnlyMeshesIds = [];
  75601. }
  75602. }
  75603. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  75604. // Actions (scene) Done last as it can access other objects.
  75605. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75606. var mesh = scene.meshes[index];
  75607. if (mesh._waitingActions) {
  75608. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  75609. mesh._waitingActions = null;
  75610. }
  75611. }
  75612. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  75613. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  75614. }
  75615. if (!addToScene) {
  75616. container.removeAllFromScene();
  75617. }
  75618. }
  75619. catch (err) {
  75620. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  75621. if (onError) {
  75622. onError(msg, err);
  75623. }
  75624. else {
  75625. BABYLON.Tools.Log(msg);
  75626. throw err;
  75627. }
  75628. }
  75629. finally {
  75630. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75631. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75632. }
  75633. }
  75634. return container;
  75635. };
  75636. BABYLON.SceneLoader.RegisterPlugin({
  75637. name: "babylon.js",
  75638. extensions: ".babylon",
  75639. canDirectLoad: function (data) {
  75640. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  75641. return true;
  75642. }
  75643. return false;
  75644. },
  75645. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  75646. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75647. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75648. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75649. // and avoid problems with multiple concurrent .babylon loads.
  75650. var log = "importMesh has failed JSON parse";
  75651. try {
  75652. var parsedData = JSON.parse(data);
  75653. log = "";
  75654. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75655. if (!meshesNames) {
  75656. meshesNames = null;
  75657. }
  75658. else if (!Array.isArray(meshesNames)) {
  75659. meshesNames = [meshesNames];
  75660. }
  75661. var hierarchyIds = new Array();
  75662. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  75663. var loadedSkeletonsIds = [];
  75664. var loadedMaterialsIds = [];
  75665. var index;
  75666. var cache;
  75667. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  75668. var parsedMesh = parsedData.meshes[index];
  75669. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  75670. if (meshesNames !== null) {
  75671. // Remove found mesh name from list.
  75672. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  75673. }
  75674. //Geometry?
  75675. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  75676. //does the file contain geometries?
  75677. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  75678. //find the correct geometry and add it to the scene
  75679. var found = false;
  75680. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  75681. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  75682. return;
  75683. }
  75684. else {
  75685. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  75686. if (parsedGeometryData.id === parsedMesh.geometryId) {
  75687. switch (geometryType) {
  75688. case "boxes":
  75689. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  75690. break;
  75691. case "spheres":
  75692. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  75693. break;
  75694. case "cylinders":
  75695. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  75696. break;
  75697. case "toruses":
  75698. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  75699. break;
  75700. case "grounds":
  75701. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  75702. break;
  75703. case "planes":
  75704. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  75705. break;
  75706. case "torusKnots":
  75707. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  75708. break;
  75709. case "vertexData":
  75710. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  75711. break;
  75712. }
  75713. found = true;
  75714. }
  75715. });
  75716. }
  75717. });
  75718. if (found === false) {
  75719. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  75720. }
  75721. }
  75722. }
  75723. // Material ?
  75724. if (parsedMesh.materialId) {
  75725. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  75726. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75727. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  75728. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  75729. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  75730. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  75731. var subMatId = parsedMultiMaterial.materials[matIndex];
  75732. loadedMaterialsIds.push(subMatId);
  75733. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  75734. if (mat) {
  75735. log += "\n\tMaterial " + mat.toString(fullDetails);
  75736. }
  75737. }
  75738. loadedMaterialsIds.push(parsedMultiMaterial.id);
  75739. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75740. if (mmat) {
  75741. materialFound = true;
  75742. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  75743. }
  75744. break;
  75745. }
  75746. }
  75747. }
  75748. if (materialFound === false) {
  75749. loadedMaterialsIds.push(parsedMesh.materialId);
  75750. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  75751. if (!mat) {
  75752. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  75753. }
  75754. else {
  75755. log += "\n\tMaterial " + mat.toString(fullDetails);
  75756. }
  75757. }
  75758. }
  75759. // Skeleton ?
  75760. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75761. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  75762. if (skeletonAlreadyLoaded === false) {
  75763. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  75764. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  75765. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  75766. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75767. skeletons.push(skeleton);
  75768. loadedSkeletonsIds.push(parsedSkeleton.id);
  75769. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  75770. }
  75771. }
  75772. }
  75773. }
  75774. // Morph targets ?
  75775. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75776. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75777. var managerData = _a[_i];
  75778. BABYLON.MorphTargetManager.Parse(managerData, scene);
  75779. }
  75780. }
  75781. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75782. meshes.push(mesh);
  75783. log += "\n\tMesh " + mesh.toString(fullDetails);
  75784. }
  75785. }
  75786. // Connecting parents
  75787. var currentMesh;
  75788. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75789. currentMesh = scene.meshes[index];
  75790. if (currentMesh._waitingParentId) {
  75791. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  75792. currentMesh._waitingParentId = null;
  75793. }
  75794. }
  75795. // freeze and compute world matrix application
  75796. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75797. currentMesh = scene.meshes[index];
  75798. if (currentMesh._waitingFreezeWorldMatrix) {
  75799. currentMesh.freezeWorldMatrix();
  75800. currentMesh._waitingFreezeWorldMatrix = null;
  75801. }
  75802. else {
  75803. currentMesh.computeWorldMatrix(true);
  75804. }
  75805. }
  75806. }
  75807. // Particles
  75808. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  75809. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  75810. if (parser) {
  75811. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  75812. var parsedParticleSystem = parsedData.particleSystems[index];
  75813. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  75814. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  75815. }
  75816. }
  75817. }
  75818. }
  75819. return true;
  75820. }
  75821. catch (err) {
  75822. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  75823. if (onError) {
  75824. onError(msg, err);
  75825. }
  75826. else {
  75827. BABYLON.Tools.Log(msg);
  75828. throw err;
  75829. }
  75830. }
  75831. finally {
  75832. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75833. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75834. }
  75835. }
  75836. return false;
  75837. },
  75838. load: function (scene, data, rootUrl, onError) {
  75839. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75840. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75841. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75842. // and avoid problems with multiple concurrent .babylon loads.
  75843. var log = "importScene has failed JSON parse";
  75844. try {
  75845. var parsedData = JSON.parse(data);
  75846. log = "";
  75847. // Scene
  75848. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  75849. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  75850. }
  75851. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  75852. scene.autoClear = parsedData.autoClear;
  75853. }
  75854. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  75855. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  75856. }
  75857. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  75858. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  75859. }
  75860. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  75861. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  75862. }
  75863. // Fog
  75864. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  75865. scene.fogMode = parsedData.fogMode;
  75866. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  75867. scene.fogStart = parsedData.fogStart;
  75868. scene.fogEnd = parsedData.fogEnd;
  75869. scene.fogDensity = parsedData.fogDensity;
  75870. log += "\tFog mode for scene: ";
  75871. switch (scene.fogMode) {
  75872. // getters not compiling, so using hardcoded
  75873. case 1:
  75874. log += "exp\n";
  75875. break;
  75876. case 2:
  75877. log += "exp2\n";
  75878. break;
  75879. case 3:
  75880. log += "linear\n";
  75881. break;
  75882. }
  75883. }
  75884. //Physics
  75885. if (parsedData.physicsEnabled) {
  75886. var physicsPlugin;
  75887. if (parsedData.physicsEngine === "cannon") {
  75888. physicsPlugin = new BABYLON.CannonJSPlugin();
  75889. }
  75890. else if (parsedData.physicsEngine === "oimo") {
  75891. physicsPlugin = new BABYLON.OimoJSPlugin();
  75892. }
  75893. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  75894. //else - default engine, which is currently oimo
  75895. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  75896. scene.enablePhysics(physicsGravity, physicsPlugin);
  75897. }
  75898. // Metadata
  75899. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  75900. scene.metadata = parsedData.metadata;
  75901. }
  75902. //collisions, if defined. otherwise, default is true
  75903. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  75904. scene.collisionsEnabled = parsedData.collisionsEnabled;
  75905. }
  75906. scene.workerCollisions = !!parsedData.workerCollisions;
  75907. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  75908. if (!container) {
  75909. return false;
  75910. }
  75911. if (parsedData.autoAnimate) {
  75912. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  75913. }
  75914. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  75915. scene.setActiveCameraByID(parsedData.activeCameraID);
  75916. }
  75917. // Environment texture
  75918. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  75919. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  75920. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  75921. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  75922. if (parsedData.environmentTextureRotationY) {
  75923. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  75924. }
  75925. scene.environmentTexture = hdrTexture;
  75926. }
  75927. else {
  75928. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  75929. if (parsedData.environmentTextureRotationY) {
  75930. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  75931. }
  75932. scene.environmentTexture = cubeTexture;
  75933. }
  75934. if (parsedData.createDefaultSkybox === true) {
  75935. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  75936. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  75937. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  75938. }
  75939. }
  75940. // Finish
  75941. return true;
  75942. }
  75943. catch (err) {
  75944. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  75945. if (onError) {
  75946. onError(msg, err);
  75947. }
  75948. else {
  75949. BABYLON.Tools.Log(msg);
  75950. throw err;
  75951. }
  75952. }
  75953. finally {
  75954. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75955. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75956. }
  75957. }
  75958. return false;
  75959. },
  75960. loadAssetContainer: function (scene, data, rootUrl, onError) {
  75961. var container = loadAssetContainer(scene, data, rootUrl, onError);
  75962. return container;
  75963. }
  75964. });
  75965. })(BABYLON || (BABYLON = {}));
  75966. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  75967. var BABYLON;
  75968. (function (BABYLON) {
  75969. /**
  75970. * Class used to help managing file picking and drag'n'drop
  75971. */
  75972. var FilesInput = /** @class */ (function () {
  75973. /**
  75974. * Creates a new FilesInput
  75975. * @param engine defines the rendering engine
  75976. * @param scene defines the hosting scene
  75977. * @param sceneLoadedCallback callback called when scene is loaded
  75978. * @param progressCallback callback called to track progress
  75979. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  75980. * @param textureLoadingCallback callback called when a texture is loading
  75981. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  75982. * @param onReloadCallback callback called when a reload is requested
  75983. * @param errorCallback callback call if an error occurs
  75984. */
  75985. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  75986. /**
  75987. * Callback called when a file is processed
  75988. */
  75989. this.onProcessFileCallback = function () { return true; };
  75990. this._engine = engine;
  75991. this._currentScene = scene;
  75992. this._sceneLoadedCallback = sceneLoadedCallback;
  75993. this._progressCallback = progressCallback;
  75994. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  75995. this._textureLoadingCallback = textureLoadingCallback;
  75996. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  75997. this._onReloadCallback = onReloadCallback;
  75998. this._errorCallback = errorCallback;
  75999. }
  76000. /**
  76001. * Calls this function to listen to drag'n'drop events on a specific DOM element
  76002. * @param elementToMonitor defines the DOM element to track
  76003. */
  76004. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  76005. var _this = this;
  76006. if (elementToMonitor) {
  76007. this._elementToMonitor = elementToMonitor;
  76008. this._dragEnterHandler = function (e) { _this.drag(e); };
  76009. this._dragOverHandler = function (e) { _this.drag(e); };
  76010. this._dropHandler = function (e) { _this.drop(e); };
  76011. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  76012. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  76013. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  76014. }
  76015. };
  76016. /**
  76017. * Release all associated resources
  76018. */
  76019. FilesInput.prototype.dispose = function () {
  76020. if (!this._elementToMonitor) {
  76021. return;
  76022. }
  76023. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  76024. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  76025. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  76026. };
  76027. FilesInput.prototype.renderFunction = function () {
  76028. if (this._additionalRenderLoopLogicCallback) {
  76029. this._additionalRenderLoopLogicCallback();
  76030. }
  76031. if (this._currentScene) {
  76032. if (this._textureLoadingCallback) {
  76033. var remaining = this._currentScene.getWaitingItemsCount();
  76034. if (remaining > 0) {
  76035. this._textureLoadingCallback(remaining);
  76036. }
  76037. }
  76038. this._currentScene.render();
  76039. }
  76040. };
  76041. FilesInput.prototype.drag = function (e) {
  76042. e.stopPropagation();
  76043. e.preventDefault();
  76044. };
  76045. FilesInput.prototype.drop = function (eventDrop) {
  76046. eventDrop.stopPropagation();
  76047. eventDrop.preventDefault();
  76048. this.loadFiles(eventDrop);
  76049. };
  76050. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  76051. var _this = this;
  76052. var reader = folder.createReader();
  76053. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  76054. reader.readEntries(function (entries) {
  76055. remaining.count += entries.length;
  76056. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  76057. var entry = entries_1[_i];
  76058. if (entry.isFile) {
  76059. entry.file(function (file) {
  76060. file.correctName = relativePath + file.name;
  76061. files.push(file);
  76062. if (--remaining.count === 0) {
  76063. callback();
  76064. }
  76065. });
  76066. }
  76067. else if (entry.isDirectory) {
  76068. _this._traverseFolder(entry, files, remaining, callback);
  76069. }
  76070. }
  76071. if (--remaining.count) {
  76072. callback();
  76073. }
  76074. });
  76075. };
  76076. FilesInput.prototype._processFiles = function (files) {
  76077. for (var i = 0; i < files.length; i++) {
  76078. var name = files[i].correctName.toLowerCase();
  76079. var extension = name.split('.').pop();
  76080. if (!this.onProcessFileCallback(files[i], name, extension)) {
  76081. continue;
  76082. }
  76083. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  76084. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  76085. this._sceneFileToLoad = files[i];
  76086. }
  76087. FilesInput.FilesToLoad[name] = files[i];
  76088. }
  76089. };
  76090. /**
  76091. * Load files from a drop event
  76092. * @param event defines the drop event to use as source
  76093. */
  76094. FilesInput.prototype.loadFiles = function (event) {
  76095. var _this = this;
  76096. // Handling data transfer via drag'n'drop
  76097. if (event && event.dataTransfer && event.dataTransfer.files) {
  76098. this._filesToLoad = event.dataTransfer.files;
  76099. }
  76100. // Handling files from input files
  76101. if (event && event.target && event.target.files) {
  76102. this._filesToLoad = event.target.files;
  76103. }
  76104. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  76105. return;
  76106. }
  76107. if (this._startingProcessingFilesCallback) {
  76108. this._startingProcessingFilesCallback(this._filesToLoad);
  76109. }
  76110. if (this._filesToLoad && this._filesToLoad.length > 0) {
  76111. var files_1 = new Array();
  76112. var folders = [];
  76113. var items = event.dataTransfer ? event.dataTransfer.items : null;
  76114. for (var i = 0; i < this._filesToLoad.length; i++) {
  76115. var fileToLoad = this._filesToLoad[i];
  76116. var name_1 = fileToLoad.name.toLowerCase();
  76117. var entry = void 0;
  76118. fileToLoad.correctName = name_1;
  76119. if (items) {
  76120. var item = items[i];
  76121. if (item.getAsEntry) {
  76122. entry = item.getAsEntry();
  76123. }
  76124. else if (item.webkitGetAsEntry) {
  76125. entry = item.webkitGetAsEntry();
  76126. }
  76127. }
  76128. if (!entry) {
  76129. files_1.push(fileToLoad);
  76130. }
  76131. else {
  76132. if (entry.isDirectory) {
  76133. folders.push(entry);
  76134. }
  76135. else {
  76136. files_1.push(fileToLoad);
  76137. }
  76138. }
  76139. }
  76140. if (folders.length === 0) {
  76141. this._processFiles(files_1);
  76142. this._processReload();
  76143. }
  76144. else {
  76145. var remaining = { count: folders.length };
  76146. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  76147. var folder = folders_1[_i];
  76148. this._traverseFolder(folder, files_1, remaining, function () {
  76149. _this._processFiles(files_1);
  76150. if (remaining.count === 0) {
  76151. _this._processReload();
  76152. }
  76153. });
  76154. }
  76155. }
  76156. }
  76157. };
  76158. FilesInput.prototype._processReload = function () {
  76159. if (this._onReloadCallback) {
  76160. this._onReloadCallback(this._sceneFileToLoad);
  76161. }
  76162. else {
  76163. this.reload();
  76164. }
  76165. };
  76166. /**
  76167. * Reload the current scene from the loaded files
  76168. */
  76169. FilesInput.prototype.reload = function () {
  76170. var _this = this;
  76171. // If a scene file has been provided
  76172. if (this._sceneFileToLoad) {
  76173. if (this._currentScene) {
  76174. if (BABYLON.Tools.errorsCount > 0) {
  76175. BABYLON.Tools.ClearLogCache();
  76176. }
  76177. this._engine.stopRenderLoop();
  76178. }
  76179. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  76180. if (_this._progressCallback) {
  76181. _this._progressCallback(progress);
  76182. }
  76183. }).then(function (scene) {
  76184. if (_this._currentScene) {
  76185. _this._currentScene.dispose();
  76186. }
  76187. _this._currentScene = scene;
  76188. if (_this._sceneLoadedCallback) {
  76189. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  76190. }
  76191. // Wait for textures and shaders to be ready
  76192. _this._currentScene.executeWhenReady(function () {
  76193. _this._engine.runRenderLoop(function () {
  76194. _this.renderFunction();
  76195. });
  76196. });
  76197. }).catch(function (error) {
  76198. if (_this._errorCallback) {
  76199. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  76200. }
  76201. });
  76202. }
  76203. else {
  76204. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  76205. }
  76206. };
  76207. /**
  76208. * List of files ready to be loaded
  76209. */
  76210. FilesInput.FilesToLoad = {};
  76211. return FilesInput;
  76212. }());
  76213. BABYLON.FilesInput = FilesInput;
  76214. })(BABYLON || (BABYLON = {}));
  76215. //# sourceMappingURL=babylon.filesInput.js.map
  76216. var BABYLON;
  76217. (function (BABYLON) {
  76218. /**
  76219. * Class used to store custom tags
  76220. */
  76221. var Tags = /** @class */ (function () {
  76222. function Tags() {
  76223. }
  76224. /**
  76225. * Adds support for tags on the given object
  76226. * @param obj defines the object to use
  76227. */
  76228. Tags.EnableFor = function (obj) {
  76229. obj._tags = obj._tags || {};
  76230. obj.hasTags = function () {
  76231. return Tags.HasTags(obj);
  76232. };
  76233. obj.addTags = function (tagsString) {
  76234. return Tags.AddTagsTo(obj, tagsString);
  76235. };
  76236. obj.removeTags = function (tagsString) {
  76237. return Tags.RemoveTagsFrom(obj, tagsString);
  76238. };
  76239. obj.matchesTagsQuery = function (tagsQuery) {
  76240. return Tags.MatchesQuery(obj, tagsQuery);
  76241. };
  76242. };
  76243. /**
  76244. * Removes tags support
  76245. * @param obj defines the object to use
  76246. */
  76247. Tags.DisableFor = function (obj) {
  76248. delete obj._tags;
  76249. delete obj.hasTags;
  76250. delete obj.addTags;
  76251. delete obj.removeTags;
  76252. delete obj.matchesTagsQuery;
  76253. };
  76254. /**
  76255. * Gets a boolean indicating if the given object has tags
  76256. * @param obj defines the object to use
  76257. * @returns a boolean
  76258. */
  76259. Tags.HasTags = function (obj) {
  76260. if (!obj._tags) {
  76261. return false;
  76262. }
  76263. return !BABYLON.Tools.IsEmpty(obj._tags);
  76264. };
  76265. /**
  76266. * Gets the tags available on a given object
  76267. * @param obj defines the object to use
  76268. * @param asString defines if the tags must be returned as a string instead of an array of strings
  76269. * @returns the tags
  76270. */
  76271. Tags.GetTags = function (obj, asString) {
  76272. if (asString === void 0) { asString = true; }
  76273. if (!obj._tags) {
  76274. return null;
  76275. }
  76276. if (asString) {
  76277. var tagsArray = [];
  76278. for (var tag in obj._tags) {
  76279. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  76280. tagsArray.push(tag);
  76281. }
  76282. }
  76283. return tagsArray.join(" ");
  76284. }
  76285. else {
  76286. return obj._tags;
  76287. }
  76288. };
  76289. /**
  76290. * Adds tags to an object
  76291. * @param obj defines the object to use
  76292. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  76293. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  76294. */
  76295. Tags.AddTagsTo = function (obj, tagsString) {
  76296. if (!tagsString) {
  76297. return;
  76298. }
  76299. if (typeof tagsString !== "string") {
  76300. return;
  76301. }
  76302. var tags = tagsString.split(" ");
  76303. tags.forEach(function (tag, index, array) {
  76304. Tags._AddTagTo(obj, tag);
  76305. });
  76306. };
  76307. /**
  76308. * @hidden
  76309. */
  76310. Tags._AddTagTo = function (obj, tag) {
  76311. tag = tag.trim();
  76312. if (tag === "" || tag === "true" || tag === "false") {
  76313. return;
  76314. }
  76315. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  76316. return;
  76317. }
  76318. Tags.EnableFor(obj);
  76319. obj._tags[tag] = true;
  76320. };
  76321. /**
  76322. * Removes specific tags from a specific object
  76323. * @param obj defines the object to use
  76324. * @param tagsString defines the tags to remove
  76325. */
  76326. Tags.RemoveTagsFrom = function (obj, tagsString) {
  76327. if (!Tags.HasTags(obj)) {
  76328. return;
  76329. }
  76330. var tags = tagsString.split(" ");
  76331. for (var t in tags) {
  76332. Tags._RemoveTagFrom(obj, tags[t]);
  76333. }
  76334. };
  76335. /**
  76336. * @hidden
  76337. */
  76338. Tags._RemoveTagFrom = function (obj, tag) {
  76339. delete obj._tags[tag];
  76340. };
  76341. /**
  76342. * Defines if tags hosted on an object match a given query
  76343. * @param obj defines the object to use
  76344. * @param tagsQuery defines the tag query
  76345. * @returns a boolean
  76346. */
  76347. Tags.MatchesQuery = function (obj, tagsQuery) {
  76348. if (tagsQuery === undefined) {
  76349. return true;
  76350. }
  76351. if (tagsQuery === "") {
  76352. return Tags.HasTags(obj);
  76353. }
  76354. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  76355. };
  76356. return Tags;
  76357. }());
  76358. BABYLON.Tags = Tags;
  76359. })(BABYLON || (BABYLON = {}));
  76360. //# sourceMappingURL=babylon.tags.js.map
  76361. var BABYLON;
  76362. (function (BABYLON) {
  76363. /**
  76364. * Class used to evalaute queries containing `and` and `or` operators
  76365. */
  76366. var AndOrNotEvaluator = /** @class */ (function () {
  76367. function AndOrNotEvaluator() {
  76368. }
  76369. /**
  76370. * Evaluate a query
  76371. * @param query defines the query to evaluate
  76372. * @param evaluateCallback defines the callback used to filter result
  76373. * @returns true if the query matches
  76374. */
  76375. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  76376. if (!query.match(/\([^\(\)]*\)/g)) {
  76377. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  76378. }
  76379. else {
  76380. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  76381. // remove parenthesis
  76382. r = r.slice(1, r.length - 1);
  76383. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  76384. });
  76385. }
  76386. if (query === "true") {
  76387. return true;
  76388. }
  76389. if (query === "false") {
  76390. return false;
  76391. }
  76392. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  76393. };
  76394. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  76395. evaluateCallback = evaluateCallback || (function (r) {
  76396. return r === "true" ? true : false;
  76397. });
  76398. var result;
  76399. var or = parenthesisContent.split("||");
  76400. for (var i in or) {
  76401. if (or.hasOwnProperty(i)) {
  76402. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  76403. var and = ori.split("&&");
  76404. if (and.length > 1) {
  76405. for (var j = 0; j < and.length; ++j) {
  76406. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  76407. if (andj !== "true" && andj !== "false") {
  76408. if (andj[0] === "!") {
  76409. result = !evaluateCallback(andj.substring(1));
  76410. }
  76411. else {
  76412. result = evaluateCallback(andj);
  76413. }
  76414. }
  76415. else {
  76416. result = andj === "true" ? true : false;
  76417. }
  76418. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  76419. ori = "false";
  76420. break;
  76421. }
  76422. }
  76423. }
  76424. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  76425. result = true;
  76426. break;
  76427. }
  76428. // result equals false (or undefined)
  76429. if (ori !== "true" && ori !== "false") {
  76430. if (ori[0] === "!") {
  76431. result = !evaluateCallback(ori.substring(1));
  76432. }
  76433. else {
  76434. result = evaluateCallback(ori);
  76435. }
  76436. }
  76437. else {
  76438. result = ori === "true" ? true : false;
  76439. }
  76440. }
  76441. }
  76442. // the whole parenthesis scope is replaced by 'true' or 'false'
  76443. return result ? "true" : "false";
  76444. };
  76445. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  76446. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  76447. // remove whitespaces
  76448. r = r.replace(/[\s]/g, function () { return ""; });
  76449. return r.length % 2 ? "!" : "";
  76450. });
  76451. booleanString = booleanString.trim();
  76452. if (booleanString === "!true") {
  76453. booleanString = "false";
  76454. }
  76455. else if (booleanString === "!false") {
  76456. booleanString = "true";
  76457. }
  76458. return booleanString;
  76459. };
  76460. return AndOrNotEvaluator;
  76461. }());
  76462. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  76463. })(BABYLON || (BABYLON = {}));
  76464. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  76465. var BABYLON;
  76466. (function (BABYLON) {
  76467. /**
  76468. * Class used to enable access to IndexedDB
  76469. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  76470. */
  76471. var Database = /** @class */ (function () {
  76472. /**
  76473. * Creates a new Database
  76474. * @param urlToScene defines the url to load the scene
  76475. * @param callbackManifestChecked defines the callback to use when manifest is checked
  76476. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  76477. */
  76478. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  76479. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  76480. var _this = this;
  76481. // Handling various flavors of prefixed version of IndexedDB
  76482. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  76483. this.callbackManifestChecked = callbackManifestChecked;
  76484. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  76485. this.db = null;
  76486. this._enableSceneOffline = false;
  76487. this._enableTexturesOffline = false;
  76488. this.manifestVersionFound = 0;
  76489. this.mustUpdateRessources = false;
  76490. this.hasReachedQuota = false;
  76491. if (!Database.IDBStorageEnabled) {
  76492. this.callbackManifestChecked(true);
  76493. }
  76494. else {
  76495. if (disableManifestCheck) {
  76496. this._enableSceneOffline = true;
  76497. this._enableTexturesOffline = true;
  76498. this.manifestVersionFound = 1;
  76499. BABYLON.Tools.SetImmediate(function () {
  76500. _this.callbackManifestChecked(true);
  76501. });
  76502. }
  76503. else {
  76504. this._checkManifestFile();
  76505. }
  76506. }
  76507. }
  76508. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  76509. /**
  76510. * Gets a boolean indicating if scene must be saved in the database
  76511. */
  76512. get: function () {
  76513. return this._enableSceneOffline;
  76514. },
  76515. enumerable: true,
  76516. configurable: true
  76517. });
  76518. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  76519. /**
  76520. * Gets a boolean indicating if textures must be saved in the database
  76521. */
  76522. get: function () {
  76523. return this._enableTexturesOffline;
  76524. },
  76525. enumerable: true,
  76526. configurable: true
  76527. });
  76528. Database.prototype._checkManifestFile = function () {
  76529. var _this = this;
  76530. var noManifestFile = function () {
  76531. _this._enableSceneOffline = false;
  76532. _this._enableTexturesOffline = false;
  76533. _this.callbackManifestChecked(false);
  76534. };
  76535. var timeStampUsed = false;
  76536. var manifestURL = this.currentSceneUrl + ".manifest";
  76537. var xhr = new XMLHttpRequest();
  76538. if (navigator.onLine) {
  76539. // Adding a timestamp to by-pass browsers' cache
  76540. timeStampUsed = true;
  76541. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  76542. }
  76543. xhr.open("GET", manifestURL, true);
  76544. xhr.addEventListener("load", function () {
  76545. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76546. try {
  76547. var manifestFile = JSON.parse(xhr.response);
  76548. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  76549. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  76550. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  76551. _this.manifestVersionFound = manifestFile.version;
  76552. }
  76553. if (_this.callbackManifestChecked) {
  76554. _this.callbackManifestChecked(true);
  76555. }
  76556. }
  76557. catch (ex) {
  76558. noManifestFile();
  76559. }
  76560. }
  76561. else {
  76562. noManifestFile();
  76563. }
  76564. }, false);
  76565. xhr.addEventListener("error", function (event) {
  76566. if (timeStampUsed) {
  76567. timeStampUsed = false;
  76568. // Let's retry without the timeStamp
  76569. // It could fail when coupled with HTML5 Offline API
  76570. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  76571. xhr.open("GET", retryManifestURL, true);
  76572. xhr.send();
  76573. }
  76574. else {
  76575. noManifestFile();
  76576. }
  76577. }, false);
  76578. try {
  76579. xhr.send();
  76580. }
  76581. catch (ex) {
  76582. BABYLON.Tools.Error("Error on XHR send request.");
  76583. this.callbackManifestChecked(false);
  76584. }
  76585. };
  76586. /**
  76587. * Open the database and make it available
  76588. * @param successCallback defines the callback to call on success
  76589. * @param errorCallback defines the callback to call on error
  76590. */
  76591. Database.prototype.openAsync = function (successCallback, errorCallback) {
  76592. var _this = this;
  76593. var handleError = function () {
  76594. _this.isSupported = false;
  76595. if (errorCallback)
  76596. errorCallback();
  76597. };
  76598. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  76599. // Your browser doesn't support IndexedDB
  76600. this.isSupported = false;
  76601. if (errorCallback)
  76602. errorCallback();
  76603. }
  76604. else {
  76605. // If the DB hasn't been opened or created yet
  76606. if (!this.db) {
  76607. this.hasReachedQuota = false;
  76608. this.isSupported = true;
  76609. var request = this.idbFactory.open("babylonjs", 1);
  76610. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  76611. request.onerror = function (event) {
  76612. handleError();
  76613. };
  76614. // executes when a version change transaction cannot complete due to other active transactions
  76615. request.onblocked = function (event) {
  76616. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  76617. handleError();
  76618. };
  76619. // DB has been opened successfully
  76620. request.onsuccess = function (event) {
  76621. _this.db = request.result;
  76622. successCallback();
  76623. };
  76624. // Initialization of the DB. Creating Scenes & Textures stores
  76625. request.onupgradeneeded = function (event) {
  76626. _this.db = (event.target).result;
  76627. if (_this.db) {
  76628. try {
  76629. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  76630. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  76631. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  76632. }
  76633. catch (ex) {
  76634. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  76635. handleError();
  76636. }
  76637. }
  76638. };
  76639. }
  76640. // DB has already been created and opened
  76641. else {
  76642. if (successCallback)
  76643. successCallback();
  76644. }
  76645. }
  76646. };
  76647. /**
  76648. * Loads an image from the database
  76649. * @param url defines the url to load from
  76650. * @param image defines the target DOM image
  76651. */
  76652. Database.prototype.loadImageFromDB = function (url, image) {
  76653. var _this = this;
  76654. var completeURL = Database._ReturnFullUrlLocation(url);
  76655. var saveAndLoadImage = function () {
  76656. if (!_this.hasReachedQuota && _this.db !== null) {
  76657. // the texture is not yet in the DB, let's try to save it
  76658. _this._saveImageIntoDBAsync(completeURL, image);
  76659. }
  76660. // If the texture is not in the DB and we've reached the DB quota limit
  76661. // let's load it directly from the web
  76662. else {
  76663. image.src = url;
  76664. }
  76665. };
  76666. if (!this.mustUpdateRessources) {
  76667. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  76668. }
  76669. // First time we're download the images or update requested in the manifest file by a version change
  76670. else {
  76671. saveAndLoadImage();
  76672. }
  76673. };
  76674. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  76675. if (this.isSupported && this.db !== null) {
  76676. var texture;
  76677. var transaction = this.db.transaction(["textures"]);
  76678. transaction.onabort = function (event) {
  76679. image.src = url;
  76680. };
  76681. transaction.oncomplete = function (event) {
  76682. var blobTextureURL;
  76683. if (texture) {
  76684. var URL = window.URL || window.webkitURL;
  76685. blobTextureURL = URL.createObjectURL(texture.data);
  76686. image.onerror = function () {
  76687. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  76688. image.src = url;
  76689. };
  76690. image.src = blobTextureURL;
  76691. }
  76692. else {
  76693. notInDBCallback();
  76694. }
  76695. };
  76696. var getRequest = transaction.objectStore("textures").get(url);
  76697. getRequest.onsuccess = function (event) {
  76698. texture = (event.target).result;
  76699. };
  76700. getRequest.onerror = function (event) {
  76701. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  76702. image.src = url;
  76703. };
  76704. }
  76705. else {
  76706. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76707. image.src = url;
  76708. }
  76709. };
  76710. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  76711. var _this = this;
  76712. if (this.isSupported) {
  76713. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  76714. var generateBlobUrl = function () {
  76715. var blobTextureURL;
  76716. if (blob) {
  76717. var URL = window.URL || window.webkitURL;
  76718. try {
  76719. blobTextureURL = URL.createObjectURL(blob);
  76720. }
  76721. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  76722. catch (ex) {
  76723. blobTextureURL = URL.createObjectURL(blob);
  76724. }
  76725. }
  76726. if (blobTextureURL) {
  76727. image.src = blobTextureURL;
  76728. }
  76729. };
  76730. if (Database.IsUASupportingBlobStorage) { // Create XHR
  76731. var xhr = new XMLHttpRequest(), blob;
  76732. xhr.open("GET", url, true);
  76733. xhr.responseType = "blob";
  76734. xhr.addEventListener("load", function () {
  76735. if (xhr.status === 200 && _this.db) {
  76736. // Blob as response (XHR2)
  76737. blob = xhr.response;
  76738. var transaction = _this.db.transaction(["textures"], "readwrite");
  76739. // the transaction could abort because of a QuotaExceededError error
  76740. transaction.onabort = function (event) {
  76741. try {
  76742. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76743. var srcElement = (event.srcElement || event.target);
  76744. var error = srcElement.error;
  76745. if (error && error.name === "QuotaExceededError") {
  76746. _this.hasReachedQuota = true;
  76747. }
  76748. }
  76749. catch (ex) { }
  76750. generateBlobUrl();
  76751. };
  76752. transaction.oncomplete = function (event) {
  76753. generateBlobUrl();
  76754. };
  76755. var newTexture = { textureUrl: url, data: blob };
  76756. try {
  76757. // Put the blob into the dabase
  76758. var addRequest = transaction.objectStore("textures").put(newTexture);
  76759. addRequest.onsuccess = function (event) {
  76760. };
  76761. addRequest.onerror = function (event) {
  76762. generateBlobUrl();
  76763. };
  76764. }
  76765. catch (ex) {
  76766. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  76767. if (ex.code === 25) {
  76768. Database.IsUASupportingBlobStorage = false;
  76769. }
  76770. image.src = url;
  76771. }
  76772. }
  76773. else {
  76774. image.src = url;
  76775. }
  76776. }, false);
  76777. xhr.addEventListener("error", function (event) {
  76778. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  76779. image.src = url;
  76780. }, false);
  76781. xhr.send();
  76782. }
  76783. else {
  76784. image.src = url;
  76785. }
  76786. }
  76787. else {
  76788. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76789. image.src = url;
  76790. }
  76791. };
  76792. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  76793. var _this = this;
  76794. var updateVersion = function () {
  76795. // the version is not yet in the DB or we need to update it
  76796. _this._saveVersionIntoDBAsync(url, versionLoaded);
  76797. };
  76798. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  76799. };
  76800. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  76801. var _this = this;
  76802. if (this.isSupported && this.db) {
  76803. var version;
  76804. try {
  76805. var transaction = this.db.transaction(["versions"]);
  76806. transaction.oncomplete = function (event) {
  76807. if (version) {
  76808. // If the version in the JSON file is different from the version in DB
  76809. if (_this.manifestVersionFound !== version.data) {
  76810. _this.mustUpdateRessources = true;
  76811. updateInDBCallback();
  76812. }
  76813. else {
  76814. callback(version.data);
  76815. }
  76816. }
  76817. // version was not found in DB
  76818. else {
  76819. _this.mustUpdateRessources = true;
  76820. updateInDBCallback();
  76821. }
  76822. };
  76823. transaction.onabort = function (event) {
  76824. callback(-1);
  76825. };
  76826. var getRequest = transaction.objectStore("versions").get(url);
  76827. getRequest.onsuccess = function (event) {
  76828. version = (event.target).result;
  76829. };
  76830. getRequest.onerror = function (event) {
  76831. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  76832. callback(-1);
  76833. };
  76834. }
  76835. catch (ex) {
  76836. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  76837. callback(-1);
  76838. }
  76839. }
  76840. else {
  76841. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76842. callback(-1);
  76843. }
  76844. };
  76845. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  76846. var _this = this;
  76847. if (this.isSupported && !this.hasReachedQuota && this.db) {
  76848. try {
  76849. // Open a transaction to the database
  76850. var transaction = this.db.transaction(["versions"], "readwrite");
  76851. // the transaction could abort because of a QuotaExceededError error
  76852. transaction.onabort = function (event) {
  76853. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76854. var error = event.srcElement['error'];
  76855. if (error && error.name === "QuotaExceededError") {
  76856. _this.hasReachedQuota = true;
  76857. }
  76858. }
  76859. catch (ex) { }
  76860. callback(-1);
  76861. };
  76862. transaction.oncomplete = function (event) {
  76863. callback(_this.manifestVersionFound);
  76864. };
  76865. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  76866. // Put the scene into the database
  76867. var addRequest = transaction.objectStore("versions").put(newVersion);
  76868. addRequest.onsuccess = function (event) {
  76869. };
  76870. addRequest.onerror = function (event) {
  76871. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  76872. };
  76873. }
  76874. catch (ex) {
  76875. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  76876. callback(-1);
  76877. }
  76878. }
  76879. else {
  76880. callback(-1);
  76881. }
  76882. };
  76883. /**
  76884. * Loads a file from database
  76885. * @param url defines the URL to load from
  76886. * @param sceneLoaded defines a callback to call on success
  76887. * @param progressCallBack defines a callback to call when progress changed
  76888. * @param errorCallback defines a callback to call on error
  76889. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  76890. */
  76891. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  76892. var _this = this;
  76893. var completeUrl = Database._ReturnFullUrlLocation(url);
  76894. var saveAndLoadFile = function () {
  76895. // the scene is not yet in the DB, let's try to save it
  76896. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76897. };
  76898. this._checkVersionFromDB(completeUrl, function (version) {
  76899. if (version !== -1) {
  76900. if (!_this.mustUpdateRessources) {
  76901. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  76902. }
  76903. else {
  76904. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76905. }
  76906. }
  76907. else {
  76908. if (errorCallback) {
  76909. errorCallback();
  76910. }
  76911. }
  76912. });
  76913. };
  76914. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  76915. if (this.isSupported && this.db) {
  76916. var targetStore;
  76917. if (url.indexOf(".babylon") !== -1) {
  76918. targetStore = "scenes";
  76919. }
  76920. else {
  76921. targetStore = "textures";
  76922. }
  76923. var file;
  76924. var transaction = this.db.transaction([targetStore]);
  76925. transaction.oncomplete = function (event) {
  76926. if (file) {
  76927. callback(file.data);
  76928. }
  76929. // file was not found in DB
  76930. else {
  76931. notInDBCallback();
  76932. }
  76933. };
  76934. transaction.onabort = function (event) {
  76935. notInDBCallback();
  76936. };
  76937. var getRequest = transaction.objectStore(targetStore).get(url);
  76938. getRequest.onsuccess = function (event) {
  76939. file = (event.target).result;
  76940. };
  76941. getRequest.onerror = function (event) {
  76942. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  76943. notInDBCallback();
  76944. };
  76945. }
  76946. else {
  76947. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76948. callback();
  76949. }
  76950. };
  76951. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  76952. var _this = this;
  76953. if (this.isSupported) {
  76954. var targetStore;
  76955. if (url.indexOf(".babylon") !== -1) {
  76956. targetStore = "scenes";
  76957. }
  76958. else {
  76959. targetStore = "textures";
  76960. }
  76961. // Create XHR
  76962. var xhr = new XMLHttpRequest();
  76963. var fileData;
  76964. xhr.open("GET", url + "?" + Date.now(), true);
  76965. if (useArrayBuffer) {
  76966. xhr.responseType = "arraybuffer";
  76967. }
  76968. if (progressCallback) {
  76969. xhr.onprogress = progressCallback;
  76970. }
  76971. xhr.addEventListener("load", function () {
  76972. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  76973. // Blob as response (XHR2)
  76974. //fileData = xhr.responseText;
  76975. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  76976. if (!_this.hasReachedQuota && _this.db) {
  76977. // Open a transaction to the database
  76978. var transaction = _this.db.transaction([targetStore], "readwrite");
  76979. // the transaction could abort because of a QuotaExceededError error
  76980. transaction.onabort = function (event) {
  76981. try {
  76982. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76983. var error = event.srcElement['error'];
  76984. if (error && error.name === "QuotaExceededError") {
  76985. _this.hasReachedQuota = true;
  76986. }
  76987. }
  76988. catch (ex) { }
  76989. callback(fileData);
  76990. };
  76991. transaction.oncomplete = function (event) {
  76992. callback(fileData);
  76993. };
  76994. var newFile;
  76995. if (targetStore === "scenes") {
  76996. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  76997. }
  76998. else {
  76999. newFile = { textureUrl: url, data: fileData };
  77000. }
  77001. try {
  77002. // Put the scene into the database
  77003. var addRequest = transaction.objectStore(targetStore).put(newFile);
  77004. addRequest.onsuccess = function (event) {
  77005. };
  77006. addRequest.onerror = function (event) {
  77007. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  77008. };
  77009. }
  77010. catch (ex) {
  77011. callback(fileData);
  77012. }
  77013. }
  77014. else {
  77015. callback(fileData);
  77016. }
  77017. }
  77018. else {
  77019. if (xhr.status >= 400 && errorCallback) {
  77020. errorCallback(xhr);
  77021. }
  77022. else {
  77023. callback();
  77024. }
  77025. }
  77026. }, false);
  77027. xhr.addEventListener("error", function (event) {
  77028. BABYLON.Tools.Error("error on XHR request.");
  77029. callback();
  77030. }, false);
  77031. xhr.send();
  77032. }
  77033. else {
  77034. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77035. callback();
  77036. }
  77037. };
  77038. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  77039. Database.IsUASupportingBlobStorage = true;
  77040. /** Gets a boolean indicating if Database storate is enabled */
  77041. Database.IDBStorageEnabled = true;
  77042. Database._ParseURL = function (url) {
  77043. var a = document.createElement('a');
  77044. a.href = url;
  77045. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  77046. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  77047. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  77048. return absLocation;
  77049. };
  77050. Database._ReturnFullUrlLocation = function (url) {
  77051. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  77052. return (Database._ParseURL(window.location.href) + url);
  77053. }
  77054. else {
  77055. return url;
  77056. }
  77057. };
  77058. return Database;
  77059. }());
  77060. BABYLON.Database = Database;
  77061. })(BABYLON || (BABYLON = {}));
  77062. //# sourceMappingURL=babylon.database.js.map
  77063. var BABYLON;
  77064. (function (BABYLON) {
  77065. /**
  77066. * This represents all the required information to add a fresnel effect on a material:
  77067. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  77068. */
  77069. var FresnelParameters = /** @class */ (function () {
  77070. function FresnelParameters() {
  77071. this._isEnabled = true;
  77072. /**
  77073. * Define the color used on edges (grazing angle)
  77074. */
  77075. this.leftColor = BABYLON.Color3.White();
  77076. /**
  77077. * Define the color used on center
  77078. */
  77079. this.rightColor = BABYLON.Color3.Black();
  77080. /**
  77081. * Define bias applied to computed fresnel term
  77082. */
  77083. this.bias = 0;
  77084. /**
  77085. * Defined the power exponent applied to fresnel term
  77086. */
  77087. this.power = 1;
  77088. }
  77089. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  77090. /**
  77091. * Define if the fresnel effect is enable or not.
  77092. */
  77093. get: function () {
  77094. return this._isEnabled;
  77095. },
  77096. set: function (value) {
  77097. if (this._isEnabled === value) {
  77098. return;
  77099. }
  77100. this._isEnabled = value;
  77101. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  77102. },
  77103. enumerable: true,
  77104. configurable: true
  77105. });
  77106. /**
  77107. * Clones the current fresnel and its valuues
  77108. * @returns a clone fresnel configuration
  77109. */
  77110. FresnelParameters.prototype.clone = function () {
  77111. var newFresnelParameters = new FresnelParameters();
  77112. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  77113. return newFresnelParameters;
  77114. };
  77115. /**
  77116. * Serializes the current fresnel parameters to a JSON representation.
  77117. * @return the JSON serialization
  77118. */
  77119. FresnelParameters.prototype.serialize = function () {
  77120. var serializationObject = {};
  77121. serializationObject.isEnabled = this.isEnabled;
  77122. serializationObject.leftColor = this.leftColor.asArray();
  77123. serializationObject.rightColor = this.rightColor.asArray();
  77124. serializationObject.bias = this.bias;
  77125. serializationObject.power = this.power;
  77126. return serializationObject;
  77127. };
  77128. /**
  77129. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  77130. * @param parsedFresnelParameters Define the JSON representation
  77131. * @returns the parsed parameters
  77132. */
  77133. FresnelParameters.Parse = function (parsedFresnelParameters) {
  77134. var fresnelParameters = new FresnelParameters();
  77135. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  77136. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  77137. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  77138. fresnelParameters.bias = parsedFresnelParameters.bias;
  77139. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  77140. return fresnelParameters;
  77141. };
  77142. return FresnelParameters;
  77143. }());
  77144. BABYLON.FresnelParameters = FresnelParameters;
  77145. })(BABYLON || (BABYLON = {}));
  77146. //# sourceMappingURL=babylon.fresnelParameters.js.map
  77147. var BABYLON;
  77148. (function (BABYLON) {
  77149. /**
  77150. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77151. * separate meshes. This can be use to improve performances.
  77152. * @see http://doc.babylonjs.com/how_to/multi_materials
  77153. */
  77154. var MultiMaterial = /** @class */ (function (_super) {
  77155. __extends(MultiMaterial, _super);
  77156. /**
  77157. * Instantiates a new Multi Material
  77158. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77159. * separate meshes. This can be use to improve performances.
  77160. * @see http://doc.babylonjs.com/how_to/multi_materials
  77161. * @param name Define the name in the scene
  77162. * @param scene Define the scene the material belongs to
  77163. */
  77164. function MultiMaterial(name, scene) {
  77165. var _this = _super.call(this, name, scene, true) || this;
  77166. scene.multiMaterials.push(_this);
  77167. _this.subMaterials = new Array();
  77168. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  77169. return _this;
  77170. }
  77171. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  77172. /**
  77173. * Gets or Sets the list of Materials used within the multi material.
  77174. * They need to be ordered according to the submeshes order in the associated mesh
  77175. */
  77176. get: function () {
  77177. return this._subMaterials;
  77178. },
  77179. set: function (value) {
  77180. this._subMaterials = value;
  77181. this._hookArray(value);
  77182. },
  77183. enumerable: true,
  77184. configurable: true
  77185. });
  77186. MultiMaterial.prototype._hookArray = function (array) {
  77187. var _this = this;
  77188. var oldPush = array.push;
  77189. array.push = function () {
  77190. var items = [];
  77191. for (var _i = 0; _i < arguments.length; _i++) {
  77192. items[_i] = arguments[_i];
  77193. }
  77194. var result = oldPush.apply(array, items);
  77195. _this._markAllSubMeshesAsTexturesDirty();
  77196. return result;
  77197. };
  77198. var oldSplice = array.splice;
  77199. array.splice = function (index, deleteCount) {
  77200. var deleted = oldSplice.apply(array, [index, deleteCount]);
  77201. _this._markAllSubMeshesAsTexturesDirty();
  77202. return deleted;
  77203. };
  77204. };
  77205. /**
  77206. * Get one of the submaterial by its index in the submaterials array
  77207. * @param index The index to look the sub material at
  77208. * @returns The Material if the index has been defined
  77209. */
  77210. MultiMaterial.prototype.getSubMaterial = function (index) {
  77211. if (index < 0 || index >= this.subMaterials.length) {
  77212. return this.getScene().defaultMaterial;
  77213. }
  77214. return this.subMaterials[index];
  77215. };
  77216. /**
  77217. * Get the list of active textures for the whole sub materials list.
  77218. * @returns All the textures that will be used during the rendering
  77219. */
  77220. MultiMaterial.prototype.getActiveTextures = function () {
  77221. var _a;
  77222. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  77223. if (subMaterial) {
  77224. return subMaterial.getActiveTextures();
  77225. }
  77226. else {
  77227. return [];
  77228. }
  77229. }));
  77230. };
  77231. /**
  77232. * Gets the current class name of the material e.g. "MultiMaterial"
  77233. * Mainly use in serialization.
  77234. * @returns the class name
  77235. */
  77236. MultiMaterial.prototype.getClassName = function () {
  77237. return "MultiMaterial";
  77238. };
  77239. /**
  77240. * Checks if the material is ready to render the requested sub mesh
  77241. * @param mesh Define the mesh the submesh belongs to
  77242. * @param subMesh Define the sub mesh to look readyness for
  77243. * @param useInstances Define whether or not the material is used with instances
  77244. * @returns true if ready, otherwise false
  77245. */
  77246. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77247. for (var index = 0; index < this.subMaterials.length; index++) {
  77248. var subMaterial = this.subMaterials[index];
  77249. if (subMaterial) {
  77250. if (subMaterial.storeEffectOnSubMeshes) {
  77251. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  77252. return false;
  77253. }
  77254. continue;
  77255. }
  77256. if (!subMaterial.isReady(mesh)) {
  77257. return false;
  77258. }
  77259. }
  77260. }
  77261. return true;
  77262. };
  77263. /**
  77264. * Clones the current material and its related sub materials
  77265. * @param name Define the name of the newly cloned material
  77266. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  77267. * @returns the cloned material
  77268. */
  77269. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  77270. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  77271. for (var index = 0; index < this.subMaterials.length; index++) {
  77272. var subMaterial = null;
  77273. var current = this.subMaterials[index];
  77274. if (cloneChildren && current) {
  77275. subMaterial = current.clone(name + "-" + current.name);
  77276. }
  77277. else {
  77278. subMaterial = this.subMaterials[index];
  77279. }
  77280. newMultiMaterial.subMaterials.push(subMaterial);
  77281. }
  77282. return newMultiMaterial;
  77283. };
  77284. /**
  77285. * Serializes the materials into a JSON representation.
  77286. * @returns the JSON representation
  77287. */
  77288. MultiMaterial.prototype.serialize = function () {
  77289. var serializationObject = {};
  77290. serializationObject.name = this.name;
  77291. serializationObject.id = this.id;
  77292. if (BABYLON.Tags) {
  77293. serializationObject.tags = BABYLON.Tags.GetTags(this);
  77294. }
  77295. serializationObject.materials = [];
  77296. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  77297. var subMat = this.subMaterials[matIndex];
  77298. if (subMat) {
  77299. serializationObject.materials.push(subMat.id);
  77300. }
  77301. else {
  77302. serializationObject.materials.push(null);
  77303. }
  77304. }
  77305. return serializationObject;
  77306. };
  77307. /**
  77308. * Dispose the material and release its associated resources
  77309. * @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)
  77310. * @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)
  77311. */
  77312. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77313. var scene = this.getScene();
  77314. if (!scene) {
  77315. return;
  77316. }
  77317. var index = scene.multiMaterials.indexOf(this);
  77318. if (index >= 0) {
  77319. scene.multiMaterials.splice(index, 1);
  77320. }
  77321. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  77322. };
  77323. return MultiMaterial;
  77324. }(BABYLON.Material));
  77325. BABYLON.MultiMaterial = MultiMaterial;
  77326. })(BABYLON || (BABYLON = {}));
  77327. //# sourceMappingURL=babylon.multiMaterial.js.map
  77328. var BABYLON;
  77329. (function (BABYLON) {
  77330. /**
  77331. * Manage the touch inputs to control the movement of a free camera.
  77332. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77333. */
  77334. var FreeCameraTouchInput = /** @class */ (function () {
  77335. function FreeCameraTouchInput() {
  77336. /**
  77337. * Defines the touch sensibility for rotation.
  77338. * The higher the faster.
  77339. */
  77340. this.touchAngularSensibility = 200000.0;
  77341. /**
  77342. * Defines the touch sensibility for move.
  77343. * The higher the faster.
  77344. */
  77345. this.touchMoveSensibility = 250.0;
  77346. this._offsetX = null;
  77347. this._offsetY = null;
  77348. this._pointerPressed = new Array();
  77349. }
  77350. /**
  77351. * Attach the input controls to a specific dom element to get the input from.
  77352. * @param element Defines the element the controls should be listened from
  77353. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77354. */
  77355. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  77356. var _this = this;
  77357. var previousPosition = null;
  77358. if (this._pointerInput === undefined) {
  77359. this._onLostFocus = function (evt) {
  77360. _this._offsetX = null;
  77361. _this._offsetY = null;
  77362. };
  77363. this._pointerInput = function (p, s) {
  77364. var evt = p.event;
  77365. if (evt.pointerType === "mouse") {
  77366. return;
  77367. }
  77368. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77369. if (!noPreventDefault) {
  77370. evt.preventDefault();
  77371. }
  77372. _this._pointerPressed.push(evt.pointerId);
  77373. if (_this._pointerPressed.length !== 1) {
  77374. return;
  77375. }
  77376. previousPosition = {
  77377. x: evt.clientX,
  77378. y: evt.clientY
  77379. };
  77380. }
  77381. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  77382. if (!noPreventDefault) {
  77383. evt.preventDefault();
  77384. }
  77385. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77386. if (index === -1) {
  77387. return;
  77388. }
  77389. _this._pointerPressed.splice(index, 1);
  77390. if (index != 0) {
  77391. return;
  77392. }
  77393. previousPosition = null;
  77394. _this._offsetX = null;
  77395. _this._offsetY = null;
  77396. }
  77397. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  77398. if (!noPreventDefault) {
  77399. evt.preventDefault();
  77400. }
  77401. if (!previousPosition) {
  77402. return;
  77403. }
  77404. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77405. if (index != 0) {
  77406. return;
  77407. }
  77408. _this._offsetX = evt.clientX - previousPosition.x;
  77409. _this._offsetY = -(evt.clientY - previousPosition.y);
  77410. }
  77411. };
  77412. }
  77413. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  77414. if (this._onLostFocus) {
  77415. element.addEventListener("blur", this._onLostFocus);
  77416. }
  77417. };
  77418. /**
  77419. * Detach the current controls from the specified dom element.
  77420. * @param element Defines the element to stop listening the inputs from
  77421. */
  77422. FreeCameraTouchInput.prototype.detachControl = function (element) {
  77423. if (this._pointerInput && element) {
  77424. if (this._observer) {
  77425. this.camera.getScene().onPointerObservable.remove(this._observer);
  77426. this._observer = null;
  77427. }
  77428. if (this._onLostFocus) {
  77429. element.removeEventListener("blur", this._onLostFocus);
  77430. this._onLostFocus = null;
  77431. }
  77432. this._pointerPressed = [];
  77433. this._offsetX = null;
  77434. this._offsetY = null;
  77435. }
  77436. };
  77437. /**
  77438. * Update the current camera state depending on the inputs that have been used this frame.
  77439. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77440. */
  77441. FreeCameraTouchInput.prototype.checkInputs = function () {
  77442. if (this._offsetX && this._offsetY) {
  77443. var camera = this.camera;
  77444. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  77445. if (this._pointerPressed.length > 1) {
  77446. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  77447. }
  77448. else {
  77449. var speed = camera._computeLocalCameraSpeed();
  77450. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  77451. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  77452. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  77453. }
  77454. }
  77455. };
  77456. /**
  77457. * Gets the class name of the current intput.
  77458. * @returns the class name
  77459. */
  77460. FreeCameraTouchInput.prototype.getClassName = function () {
  77461. return "FreeCameraTouchInput";
  77462. };
  77463. /**
  77464. * Get the friendly name associated with the input class.
  77465. * @returns the input friendly name
  77466. */
  77467. FreeCameraTouchInput.prototype.getSimpleName = function () {
  77468. return "touch";
  77469. };
  77470. __decorate([
  77471. BABYLON.serialize()
  77472. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  77473. __decorate([
  77474. BABYLON.serialize()
  77475. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  77476. return FreeCameraTouchInput;
  77477. }());
  77478. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  77479. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  77480. })(BABYLON || (BABYLON = {}));
  77481. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  77482. var BABYLON;
  77483. (function (BABYLON) {
  77484. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  77485. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  77486. });
  77487. /**
  77488. * This represents a FPS type of camera controlled by touch.
  77489. * This is like a universal camera minus the Gamepad controls.
  77490. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77491. */
  77492. var TouchCamera = /** @class */ (function (_super) {
  77493. __extends(TouchCamera, _super);
  77494. /**
  77495. * Instantiates a new touch camera.
  77496. * This represents a FPS type of camera controlled by touch.
  77497. * This is like a universal camera minus the Gamepad controls.
  77498. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77499. * @param name Define the name of the camera in the scene
  77500. * @param position Define the start position of the camera in the scene
  77501. * @param scene Define the scene the camera belongs to
  77502. */
  77503. function TouchCamera(name, position, scene) {
  77504. var _this = _super.call(this, name, position, scene) || this;
  77505. _this.inputs.addTouch();
  77506. _this._setupInputs();
  77507. return _this;
  77508. }
  77509. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  77510. /**
  77511. * Defines the touch sensibility for rotation.
  77512. * The higher the faster.
  77513. */
  77514. get: function () {
  77515. var touch = this.inputs.attached["touch"];
  77516. if (touch)
  77517. return touch.touchAngularSensibility;
  77518. return 0;
  77519. },
  77520. set: function (value) {
  77521. var touch = this.inputs.attached["touch"];
  77522. if (touch)
  77523. touch.touchAngularSensibility = value;
  77524. },
  77525. enumerable: true,
  77526. configurable: true
  77527. });
  77528. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  77529. /**
  77530. * Defines the touch sensibility for move.
  77531. * The higher the faster.
  77532. */
  77533. get: function () {
  77534. var touch = this.inputs.attached["touch"];
  77535. if (touch)
  77536. return touch.touchMoveSensibility;
  77537. return 0;
  77538. },
  77539. set: function (value) {
  77540. var touch = this.inputs.attached["touch"];
  77541. if (touch)
  77542. touch.touchMoveSensibility = value;
  77543. },
  77544. enumerable: true,
  77545. configurable: true
  77546. });
  77547. /**
  77548. * Gets the current object class name.
  77549. * @return the class name
  77550. */
  77551. TouchCamera.prototype.getClassName = function () {
  77552. return "TouchCamera";
  77553. };
  77554. /** @hidden */
  77555. TouchCamera.prototype._setupInputs = function () {
  77556. var mouse = this.inputs.attached["mouse"];
  77557. if (mouse) {
  77558. mouse.touchEnabled = false;
  77559. }
  77560. };
  77561. return TouchCamera;
  77562. }(BABYLON.FreeCamera));
  77563. BABYLON.TouchCamera = TouchCamera;
  77564. })(BABYLON || (BABYLON = {}));
  77565. //# sourceMappingURL=babylon.touchCamera.js.map
  77566. var BABYLON;
  77567. (function (BABYLON) {
  77568. var ProceduralTexture = /** @class */ (function (_super) {
  77569. __extends(ProceduralTexture, _super);
  77570. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  77571. if (fallbackTexture === void 0) { fallbackTexture = null; }
  77572. if (generateMipMaps === void 0) { generateMipMaps = true; }
  77573. if (isCube === void 0) { isCube = false; }
  77574. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  77575. _this.isCube = isCube;
  77576. _this.isEnabled = true;
  77577. _this._currentRefreshId = -1;
  77578. _this._refreshRate = 1;
  77579. /**
  77580. * Event raised when the texture is generated
  77581. */
  77582. _this.onGeneratedObservable = new BABYLON.Observable();
  77583. _this._vertexBuffers = {};
  77584. _this._uniforms = new Array();
  77585. _this._samplers = new Array();
  77586. /** @hidden */
  77587. _this._textures = {};
  77588. _this._floats = {};
  77589. _this._ints = {};
  77590. _this._floatsArrays = {};
  77591. _this._colors3 = {};
  77592. _this._colors4 = {};
  77593. _this._vectors2 = {};
  77594. _this._vectors3 = {};
  77595. _this._matrices = {};
  77596. _this._fallbackTextureUsed = false;
  77597. _this._cachedDefines = "";
  77598. _this._contentUpdateId = -1;
  77599. scene = _this.getScene();
  77600. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  77601. if (!component) {
  77602. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  77603. scene._addComponent(component);
  77604. }
  77605. scene.proceduralTextures.push(_this);
  77606. _this._engine = scene.getEngine();
  77607. _this.name = name;
  77608. _this.isRenderTarget = true;
  77609. _this._size = size;
  77610. _this._generateMipMaps = generateMipMaps;
  77611. _this.setFragment(fragment);
  77612. _this._fallbackTexture = fallbackTexture;
  77613. if (isCube) {
  77614. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  77615. _this.setFloat("face", 0);
  77616. }
  77617. else {
  77618. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  77619. }
  77620. // VBO
  77621. var vertices = [];
  77622. vertices.push(1, 1);
  77623. vertices.push(-1, 1);
  77624. vertices.push(-1, -1);
  77625. vertices.push(1, -1);
  77626. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77627. _this._createIndexBuffer();
  77628. return _this;
  77629. }
  77630. /**
  77631. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  77632. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  77633. */
  77634. ProceduralTexture.prototype.getContent = function () {
  77635. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  77636. return this._contentData;
  77637. }
  77638. this._contentData = this.readPixels(0, 0, this._contentData);
  77639. this._contentUpdateId = this._currentRefreshId;
  77640. return this._contentData;
  77641. };
  77642. ProceduralTexture.prototype._createIndexBuffer = function () {
  77643. var engine = this._engine;
  77644. // Indices
  77645. var indices = [];
  77646. indices.push(0);
  77647. indices.push(1);
  77648. indices.push(2);
  77649. indices.push(0);
  77650. indices.push(2);
  77651. indices.push(3);
  77652. this._indexBuffer = engine.createIndexBuffer(indices);
  77653. };
  77654. /** @hidden */
  77655. ProceduralTexture.prototype._rebuild = function () {
  77656. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77657. if (vb) {
  77658. vb._rebuild();
  77659. }
  77660. this._createIndexBuffer();
  77661. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  77662. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  77663. }
  77664. };
  77665. ProceduralTexture.prototype.reset = function () {
  77666. if (this._effect === undefined) {
  77667. return;
  77668. }
  77669. var engine = this._engine;
  77670. engine._releaseEffect(this._effect);
  77671. };
  77672. ProceduralTexture.prototype._getDefines = function () {
  77673. return "";
  77674. };
  77675. ProceduralTexture.prototype.isReady = function () {
  77676. var _this = this;
  77677. var engine = this._engine;
  77678. var shaders;
  77679. if (!this._fragment) {
  77680. return false;
  77681. }
  77682. if (this._fallbackTextureUsed) {
  77683. return true;
  77684. }
  77685. var defines = this._getDefines();
  77686. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  77687. return true;
  77688. }
  77689. if (this._fragment.fragmentElement !== undefined) {
  77690. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  77691. }
  77692. else {
  77693. shaders = { vertex: "procedural", fragment: this._fragment };
  77694. }
  77695. this._cachedDefines = defines;
  77696. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  77697. _this.releaseInternalTexture();
  77698. if (_this._fallbackTexture) {
  77699. _this._texture = _this._fallbackTexture._texture;
  77700. if (_this._texture) {
  77701. _this._texture.incrementReferences();
  77702. }
  77703. }
  77704. _this._fallbackTextureUsed = true;
  77705. });
  77706. return this._effect.isReady();
  77707. };
  77708. ProceduralTexture.prototype.resetRefreshCounter = function () {
  77709. this._currentRefreshId = -1;
  77710. };
  77711. ProceduralTexture.prototype.setFragment = function (fragment) {
  77712. this._fragment = fragment;
  77713. };
  77714. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  77715. get: function () {
  77716. return this._refreshRate;
  77717. },
  77718. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  77719. set: function (value) {
  77720. this._refreshRate = value;
  77721. this.resetRefreshCounter();
  77722. },
  77723. enumerable: true,
  77724. configurable: true
  77725. });
  77726. /** @hidden */
  77727. ProceduralTexture.prototype._shouldRender = function () {
  77728. if (!this.isEnabled || !this.isReady() || !this._texture) {
  77729. if (this._texture) {
  77730. this._texture.isReady = false;
  77731. }
  77732. return false;
  77733. }
  77734. if (this._fallbackTextureUsed) {
  77735. return false;
  77736. }
  77737. if (this._currentRefreshId === -1) { // At least render once
  77738. this._currentRefreshId = 1;
  77739. return true;
  77740. }
  77741. if (this.refreshRate === this._currentRefreshId) {
  77742. this._currentRefreshId = 1;
  77743. return true;
  77744. }
  77745. this._currentRefreshId++;
  77746. return false;
  77747. };
  77748. ProceduralTexture.prototype.getRenderSize = function () {
  77749. return this._size;
  77750. };
  77751. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  77752. if (this._fallbackTextureUsed) {
  77753. return;
  77754. }
  77755. this.releaseInternalTexture();
  77756. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  77757. // Update properties
  77758. this._size = size;
  77759. this._generateMipMaps = generateMipMaps;
  77760. };
  77761. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  77762. if (this._uniforms.indexOf(uniformName) === -1) {
  77763. this._uniforms.push(uniformName);
  77764. }
  77765. };
  77766. ProceduralTexture.prototype.setTexture = function (name, texture) {
  77767. if (this._samplers.indexOf(name) === -1) {
  77768. this._samplers.push(name);
  77769. }
  77770. this._textures[name] = texture;
  77771. return this;
  77772. };
  77773. ProceduralTexture.prototype.setFloat = function (name, value) {
  77774. this._checkUniform(name);
  77775. this._floats[name] = value;
  77776. return this;
  77777. };
  77778. /**
  77779. * Set the value of an uniform to an integer value
  77780. * @param name defines the name of the uniform
  77781. * @param value defines the value to set
  77782. * @returns the current procedural texture
  77783. */
  77784. ProceduralTexture.prototype.setInt = function (name, value) {
  77785. this._checkUniform(name);
  77786. this._ints[name] = value;
  77787. return this;
  77788. };
  77789. ProceduralTexture.prototype.setFloats = function (name, value) {
  77790. this._checkUniform(name);
  77791. this._floatsArrays[name] = value;
  77792. return this;
  77793. };
  77794. ProceduralTexture.prototype.setColor3 = function (name, value) {
  77795. this._checkUniform(name);
  77796. this._colors3[name] = value;
  77797. return this;
  77798. };
  77799. ProceduralTexture.prototype.setColor4 = function (name, value) {
  77800. this._checkUniform(name);
  77801. this._colors4[name] = value;
  77802. return this;
  77803. };
  77804. ProceduralTexture.prototype.setVector2 = function (name, value) {
  77805. this._checkUniform(name);
  77806. this._vectors2[name] = value;
  77807. return this;
  77808. };
  77809. ProceduralTexture.prototype.setVector3 = function (name, value) {
  77810. this._checkUniform(name);
  77811. this._vectors3[name] = value;
  77812. return this;
  77813. };
  77814. ProceduralTexture.prototype.setMatrix = function (name, value) {
  77815. this._checkUniform(name);
  77816. this._matrices[name] = value;
  77817. return this;
  77818. };
  77819. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  77820. var scene = this.getScene();
  77821. if (!scene) {
  77822. return;
  77823. }
  77824. var engine = this._engine;
  77825. // Render
  77826. engine.enableEffect(this._effect);
  77827. engine.setState(false);
  77828. // Texture
  77829. for (var name in this._textures) {
  77830. this._effect.setTexture(name, this._textures[name]);
  77831. }
  77832. // Float
  77833. for (name in this._ints) {
  77834. this._effect.setInt(name, this._ints[name]);
  77835. }
  77836. // Float
  77837. for (name in this._floats) {
  77838. this._effect.setFloat(name, this._floats[name]);
  77839. }
  77840. // Floats
  77841. for (name in this._floatsArrays) {
  77842. this._effect.setArray(name, this._floatsArrays[name]);
  77843. }
  77844. // Color3
  77845. for (name in this._colors3) {
  77846. this._effect.setColor3(name, this._colors3[name]);
  77847. }
  77848. // Color4
  77849. for (name in this._colors4) {
  77850. var color = this._colors4[name];
  77851. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  77852. }
  77853. // Vector2
  77854. for (name in this._vectors2) {
  77855. this._effect.setVector2(name, this._vectors2[name]);
  77856. }
  77857. // Vector3
  77858. for (name in this._vectors3) {
  77859. this._effect.setVector3(name, this._vectors3[name]);
  77860. }
  77861. // Matrix
  77862. for (name in this._matrices) {
  77863. this._effect.setMatrix(name, this._matrices[name]);
  77864. }
  77865. if (!this._texture) {
  77866. return;
  77867. }
  77868. if (this.isCube) {
  77869. for (var face = 0; face < 6; face++) {
  77870. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  77871. // VBOs
  77872. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77873. this._effect.setFloat("face", face);
  77874. // Clear
  77875. engine.clear(scene.clearColor, true, true, true);
  77876. // Draw order
  77877. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77878. // Mipmaps
  77879. if (face === 5) {
  77880. engine.generateMipMapsForCubemap(this._texture);
  77881. }
  77882. }
  77883. }
  77884. else {
  77885. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  77886. // VBOs
  77887. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77888. // Clear
  77889. engine.clear(scene.clearColor, true, true, true);
  77890. // Draw order
  77891. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77892. }
  77893. // Unbind
  77894. engine.unBindFramebuffer(this._texture, this.isCube);
  77895. if (this.onGenerated) {
  77896. this.onGenerated();
  77897. }
  77898. this.onGeneratedObservable.notifyObservers(this);
  77899. };
  77900. ProceduralTexture.prototype.clone = function () {
  77901. var textureSize = this.getSize();
  77902. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  77903. // Base texture
  77904. newTexture.hasAlpha = this.hasAlpha;
  77905. newTexture.level = this.level;
  77906. // RenderTarget Texture
  77907. newTexture.coordinatesMode = this.coordinatesMode;
  77908. return newTexture;
  77909. };
  77910. ProceduralTexture.prototype.dispose = function () {
  77911. var scene = this.getScene();
  77912. if (!scene) {
  77913. return;
  77914. }
  77915. var index = scene.proceduralTextures.indexOf(this);
  77916. if (index >= 0) {
  77917. scene.proceduralTextures.splice(index, 1);
  77918. }
  77919. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77920. if (vertexBuffer) {
  77921. vertexBuffer.dispose();
  77922. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77923. }
  77924. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  77925. this._indexBuffer = null;
  77926. }
  77927. _super.prototype.dispose.call(this);
  77928. };
  77929. __decorate([
  77930. BABYLON.serialize()
  77931. ], ProceduralTexture.prototype, "_size", void 0);
  77932. __decorate([
  77933. BABYLON.serialize()
  77934. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  77935. __decorate([
  77936. BABYLON.serialize()
  77937. ], ProceduralTexture.prototype, "isEnabled", void 0);
  77938. __decorate([
  77939. BABYLON.serialize()
  77940. ], ProceduralTexture.prototype, "refreshRate", null);
  77941. return ProceduralTexture;
  77942. }(BABYLON.Texture));
  77943. BABYLON.ProceduralTexture = ProceduralTexture;
  77944. })(BABYLON || (BABYLON = {}));
  77945. //# sourceMappingURL=babylon.proceduralTexture.js.map
  77946. var BABYLON;
  77947. (function (BABYLON) {
  77948. /**
  77949. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  77950. * in a given scene.
  77951. */
  77952. var ProceduralTextureSceneComponent = /** @class */ (function () {
  77953. /**
  77954. * Creates a new instance of the component for the given scene
  77955. * @param scene Defines the scene to register the component in
  77956. */
  77957. function ProceduralTextureSceneComponent(scene) {
  77958. /**
  77959. * The component name helpfull to identify the component in the list of scene components.
  77960. */
  77961. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  77962. this.scene = scene;
  77963. this.scene.proceduralTextures = new Array();
  77964. scene.layers = new Array();
  77965. }
  77966. /**
  77967. * Registers the component in a given scene
  77968. */
  77969. ProceduralTextureSceneComponent.prototype.register = function () {
  77970. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  77971. };
  77972. /**
  77973. * Rebuilds the elements related to this component in case of
  77974. * context lost for instance.
  77975. */
  77976. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  77977. // Nothing to do here.
  77978. };
  77979. /**
  77980. * Disposes the component and the associated ressources.
  77981. */
  77982. ProceduralTextureSceneComponent.prototype.dispose = function () {
  77983. // Nothing to do here.
  77984. };
  77985. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  77986. if (this.scene.proceduralTexturesEnabled) {
  77987. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  77988. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  77989. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  77990. if (proceduralTexture._shouldRender()) {
  77991. proceduralTexture.render();
  77992. }
  77993. }
  77994. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  77995. }
  77996. };
  77997. return ProceduralTextureSceneComponent;
  77998. }());
  77999. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  78000. })(BABYLON || (BABYLON = {}));
  78001. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  78002. var BABYLON;
  78003. (function (BABYLON) {
  78004. var CustomProceduralTexture = /** @class */ (function (_super) {
  78005. __extends(CustomProceduralTexture, _super);
  78006. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  78007. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  78008. _this._animate = true;
  78009. _this._time = 0;
  78010. _this._texturePath = texturePath;
  78011. //Try to load json
  78012. _this.loadJson(texturePath);
  78013. _this.refreshRate = 1;
  78014. return _this;
  78015. }
  78016. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  78017. var _this = this;
  78018. var noConfigFile = function () {
  78019. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  78020. try {
  78021. _this.setFragment(_this._texturePath);
  78022. }
  78023. catch (ex) {
  78024. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  78025. }
  78026. };
  78027. var configFileUrl = jsonUrl + "/config.json";
  78028. var xhr = new XMLHttpRequest();
  78029. xhr.open("GET", configFileUrl, true);
  78030. xhr.addEventListener("load", function () {
  78031. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78032. try {
  78033. _this._config = JSON.parse(xhr.response);
  78034. _this.updateShaderUniforms();
  78035. _this.updateTextures();
  78036. _this.setFragment(_this._texturePath + "/custom");
  78037. _this._animate = _this._config.animate;
  78038. _this.refreshRate = _this._config.refreshrate;
  78039. }
  78040. catch (ex) {
  78041. noConfigFile();
  78042. }
  78043. }
  78044. else {
  78045. noConfigFile();
  78046. }
  78047. }, false);
  78048. xhr.addEventListener("error", function () {
  78049. noConfigFile();
  78050. }, false);
  78051. try {
  78052. xhr.send();
  78053. }
  78054. catch (ex) {
  78055. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  78056. }
  78057. };
  78058. CustomProceduralTexture.prototype.isReady = function () {
  78059. if (!_super.prototype.isReady.call(this)) {
  78060. return false;
  78061. }
  78062. for (var name in this._textures) {
  78063. var texture = this._textures[name];
  78064. if (!texture.isReady()) {
  78065. return false;
  78066. }
  78067. }
  78068. return true;
  78069. };
  78070. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78071. var scene = this.getScene();
  78072. if (this._animate && scene) {
  78073. this._time += scene.getAnimationRatio() * 0.03;
  78074. this.updateShaderUniforms();
  78075. }
  78076. _super.prototype.render.call(this, useCameraPostProcess);
  78077. };
  78078. CustomProceduralTexture.prototype.updateTextures = function () {
  78079. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  78080. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  78081. }
  78082. };
  78083. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  78084. if (this._config) {
  78085. for (var j = 0; j < this._config.uniforms.length; j++) {
  78086. var uniform = this._config.uniforms[j];
  78087. switch (uniform.type) {
  78088. case "float":
  78089. this.setFloat(uniform.name, uniform.value);
  78090. break;
  78091. case "color3":
  78092. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  78093. break;
  78094. case "color4":
  78095. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  78096. break;
  78097. case "vector2":
  78098. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  78099. break;
  78100. case "vector3":
  78101. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  78102. break;
  78103. }
  78104. }
  78105. }
  78106. this.setFloat("time", this._time);
  78107. };
  78108. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  78109. get: function () {
  78110. return this._animate;
  78111. },
  78112. set: function (value) {
  78113. this._animate = value;
  78114. },
  78115. enumerable: true,
  78116. configurable: true
  78117. });
  78118. return CustomProceduralTexture;
  78119. }(BABYLON.ProceduralTexture));
  78120. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  78121. })(BABYLON || (BABYLON = {}));
  78122. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  78123. var BABYLON;
  78124. (function (BABYLON) {
  78125. /**
  78126. * Manage the gamepad inputs to control a free camera.
  78127. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78128. */
  78129. var FreeCameraGamepadInput = /** @class */ (function () {
  78130. function FreeCameraGamepadInput() {
  78131. /**
  78132. * Defines the gamepad rotation sensiblity.
  78133. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78134. */
  78135. this.gamepadAngularSensibility = 200;
  78136. /**
  78137. * Defines the gamepad move sensiblity.
  78138. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78139. */
  78140. this.gamepadMoveSensibility = 40;
  78141. this._cameraTransform = BABYLON.Matrix.Identity();
  78142. this._deltaTransform = BABYLON.Vector3.Zero();
  78143. this._vector3 = BABYLON.Vector3.Zero();
  78144. this._vector2 = BABYLON.Vector2.Zero();
  78145. }
  78146. /**
  78147. * Attach the input controls to a specific dom element to get the input from.
  78148. * @param element Defines the element the controls should be listened from
  78149. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78150. */
  78151. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78152. var _this = this;
  78153. var manager = this.camera.getScene().gamepadManager;
  78154. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78155. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78156. // prioritize XBOX gamepads.
  78157. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78158. _this.gamepad = gamepad;
  78159. }
  78160. }
  78161. });
  78162. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78163. if (_this.gamepad === gamepad) {
  78164. _this.gamepad = null;
  78165. }
  78166. });
  78167. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78168. };
  78169. /**
  78170. * Detach the current controls from the specified dom element.
  78171. * @param element Defines the element to stop listening the inputs from
  78172. */
  78173. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  78174. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78175. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78176. this.gamepad = null;
  78177. };
  78178. /**
  78179. * Update the current camera state depending on the inputs that have been used this frame.
  78180. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78181. */
  78182. FreeCameraGamepadInput.prototype.checkInputs = function () {
  78183. if (this.gamepad && this.gamepad.leftStick) {
  78184. var camera = this.camera;
  78185. var LSValues = this.gamepad.leftStick;
  78186. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  78187. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78188. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  78189. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  78190. var RSValues = this.gamepad.rightStick;
  78191. if (RSValues) {
  78192. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  78193. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  78194. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  78195. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  78196. }
  78197. else {
  78198. RSValues = { x: 0, y: 0 };
  78199. }
  78200. if (!camera.rotationQuaternion) {
  78201. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  78202. }
  78203. else {
  78204. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  78205. }
  78206. var speed = camera._computeLocalCameraSpeed() * 50.0;
  78207. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  78208. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  78209. camera.cameraDirection.addInPlace(this._deltaTransform);
  78210. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  78211. camera.cameraRotation.addInPlace(this._vector2);
  78212. }
  78213. };
  78214. /**
  78215. * Gets the class name of the current intput.
  78216. * @returns the class name
  78217. */
  78218. FreeCameraGamepadInput.prototype.getClassName = function () {
  78219. return "FreeCameraGamepadInput";
  78220. };
  78221. /**
  78222. * Get the friendly name associated with the input class.
  78223. * @returns the input friendly name
  78224. */
  78225. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  78226. return "gamepad";
  78227. };
  78228. __decorate([
  78229. BABYLON.serialize()
  78230. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  78231. __decorate([
  78232. BABYLON.serialize()
  78233. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78234. return FreeCameraGamepadInput;
  78235. }());
  78236. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  78237. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  78238. })(BABYLON || (BABYLON = {}));
  78239. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  78240. var BABYLON;
  78241. (function (BABYLON) {
  78242. /**
  78243. * Manage the gamepad inputs to control an arc rotate camera.
  78244. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78245. */
  78246. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  78247. function ArcRotateCameraGamepadInput() {
  78248. /**
  78249. * Defines the gamepad rotation sensiblity.
  78250. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78251. */
  78252. this.gamepadRotationSensibility = 80;
  78253. /**
  78254. * Defines the gamepad move sensiblity.
  78255. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78256. */
  78257. this.gamepadMoveSensibility = 40;
  78258. }
  78259. /**
  78260. * Attach the input controls to a specific dom element to get the input from.
  78261. * @param element Defines the element the controls should be listened from
  78262. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78263. */
  78264. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78265. var _this = this;
  78266. var manager = this.camera.getScene().gamepadManager;
  78267. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78268. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78269. // prioritize XBOX gamepads.
  78270. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78271. _this.gamepad = gamepad;
  78272. }
  78273. }
  78274. });
  78275. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78276. if (_this.gamepad === gamepad) {
  78277. _this.gamepad = null;
  78278. }
  78279. });
  78280. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78281. };
  78282. /**
  78283. * Detach the current controls from the specified dom element.
  78284. * @param element Defines the element to stop listening the inputs from
  78285. */
  78286. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  78287. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78288. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78289. this.gamepad = null;
  78290. };
  78291. /**
  78292. * Update the current camera state depending on the inputs that have been used this frame.
  78293. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78294. */
  78295. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  78296. if (this.gamepad) {
  78297. var camera = this.camera;
  78298. var RSValues = this.gamepad.rightStick;
  78299. if (RSValues) {
  78300. if (RSValues.x != 0) {
  78301. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  78302. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  78303. camera.inertialAlphaOffset += normalizedRX;
  78304. }
  78305. }
  78306. if (RSValues.y != 0) {
  78307. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  78308. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  78309. camera.inertialBetaOffset += normalizedRY;
  78310. }
  78311. }
  78312. }
  78313. var LSValues = this.gamepad.leftStick;
  78314. if (LSValues && LSValues.y != 0) {
  78315. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78316. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  78317. this.camera.inertialRadiusOffset -= normalizedLY;
  78318. }
  78319. }
  78320. }
  78321. };
  78322. /**
  78323. * Gets the class name of the current intput.
  78324. * @returns the class name
  78325. */
  78326. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  78327. return "ArcRotateCameraGamepadInput";
  78328. };
  78329. /**
  78330. * Get the friendly name associated with the input class.
  78331. * @returns the input friendly name
  78332. */
  78333. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  78334. return "gamepad";
  78335. };
  78336. __decorate([
  78337. BABYLON.serialize()
  78338. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  78339. __decorate([
  78340. BABYLON.serialize()
  78341. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78342. return ArcRotateCameraGamepadInput;
  78343. }());
  78344. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  78345. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  78346. })(BABYLON || (BABYLON = {}));
  78347. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  78348. var BABYLON;
  78349. (function (BABYLON) {
  78350. /**
  78351. * Manager for handling gamepads
  78352. */
  78353. var GamepadManager = /** @class */ (function () {
  78354. /**
  78355. * Initializes the gamepad manager
  78356. * @param _scene BabylonJS scene
  78357. */
  78358. function GamepadManager(_scene) {
  78359. var _this = this;
  78360. this._scene = _scene;
  78361. this._babylonGamepads = [];
  78362. this._oneGamepadConnected = false;
  78363. /** @hidden */
  78364. this._isMonitoring = false;
  78365. /**
  78366. * observable to be triggered when the gamepad controller has been disconnected
  78367. */
  78368. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  78369. if (!BABYLON.Tools.IsWindowObjectExist()) {
  78370. this._gamepadEventSupported = false;
  78371. }
  78372. else {
  78373. this._gamepadEventSupported = 'GamepadEvent' in window;
  78374. this._gamepadSupport = (navigator.getGamepads ||
  78375. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  78376. }
  78377. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  78378. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  78379. for (var i in _this._babylonGamepads) {
  78380. var gamepad = _this._babylonGamepads[i];
  78381. if (gamepad && gamepad._isConnected) {
  78382. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  78383. }
  78384. }
  78385. });
  78386. this._onGamepadConnectedEvent = function (evt) {
  78387. var gamepad = evt.gamepad;
  78388. if (gamepad.index in _this._babylonGamepads) {
  78389. if (_this._babylonGamepads[gamepad.index].isConnected) {
  78390. return;
  78391. }
  78392. }
  78393. var newGamepad;
  78394. if (_this._babylonGamepads[gamepad.index]) {
  78395. newGamepad = _this._babylonGamepads[gamepad.index];
  78396. newGamepad.browserGamepad = gamepad;
  78397. newGamepad._isConnected = true;
  78398. }
  78399. else {
  78400. newGamepad = _this._addNewGamepad(gamepad);
  78401. }
  78402. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  78403. _this._startMonitoringGamepads();
  78404. };
  78405. this._onGamepadDisconnectedEvent = function (evt) {
  78406. var gamepad = evt.gamepad;
  78407. // Remove the gamepad from the list of gamepads to monitor.
  78408. for (var i in _this._babylonGamepads) {
  78409. if (_this._babylonGamepads[i].index === gamepad.index) {
  78410. var disconnectedGamepad = _this._babylonGamepads[i];
  78411. disconnectedGamepad._isConnected = false;
  78412. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  78413. break;
  78414. }
  78415. }
  78416. };
  78417. if (this._gamepadSupport) {
  78418. //first add already-connected gamepads
  78419. this._updateGamepadObjects();
  78420. if (this._babylonGamepads.length) {
  78421. this._startMonitoringGamepads();
  78422. }
  78423. // Checking if the gamepad connected event is supported (like in Firefox)
  78424. if (this._gamepadEventSupported) {
  78425. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  78426. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  78427. }
  78428. else {
  78429. this._startMonitoringGamepads();
  78430. }
  78431. }
  78432. }
  78433. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  78434. /**
  78435. * The gamepads in the game pad manager
  78436. */
  78437. get: function () {
  78438. return this._babylonGamepads;
  78439. },
  78440. enumerable: true,
  78441. configurable: true
  78442. });
  78443. /**
  78444. * Get the gamepad controllers based on type
  78445. * @param type The type of gamepad controller
  78446. * @returns Nullable gamepad
  78447. */
  78448. GamepadManager.prototype.getGamepadByType = function (type) {
  78449. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  78450. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  78451. var gamepad = _a[_i];
  78452. if (gamepad && gamepad.type === type) {
  78453. return gamepad;
  78454. }
  78455. }
  78456. return null;
  78457. };
  78458. /**
  78459. * Disposes the gamepad manager
  78460. */
  78461. GamepadManager.prototype.dispose = function () {
  78462. if (this._gamepadEventSupported) {
  78463. if (this._onGamepadConnectedEvent) {
  78464. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  78465. }
  78466. if (this._onGamepadDisconnectedEvent) {
  78467. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  78468. }
  78469. this._onGamepadConnectedEvent = null;
  78470. this._onGamepadDisconnectedEvent = null;
  78471. }
  78472. this._babylonGamepads.forEach(function (gamepad) {
  78473. gamepad.dispose();
  78474. });
  78475. this.onGamepadConnectedObservable.clear();
  78476. this.onGamepadDisconnectedObservable.clear();
  78477. this._oneGamepadConnected = false;
  78478. this._stopMonitoringGamepads();
  78479. this._babylonGamepads = [];
  78480. };
  78481. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  78482. if (!this._oneGamepadConnected) {
  78483. this._oneGamepadConnected = true;
  78484. }
  78485. var newGamepad;
  78486. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  78487. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  78488. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  78489. }
  78490. // if pose is supported, use the (WebVR) pose enabled controller
  78491. else if (gamepad.pose) {
  78492. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  78493. }
  78494. else {
  78495. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  78496. }
  78497. this._babylonGamepads[newGamepad.index] = newGamepad;
  78498. return newGamepad;
  78499. };
  78500. GamepadManager.prototype._startMonitoringGamepads = function () {
  78501. if (!this._isMonitoring) {
  78502. this._isMonitoring = true;
  78503. //back-comp
  78504. if (!this._scene) {
  78505. this._checkGamepadsStatus();
  78506. }
  78507. }
  78508. };
  78509. GamepadManager.prototype._stopMonitoringGamepads = function () {
  78510. this._isMonitoring = false;
  78511. };
  78512. /** @hidden */
  78513. GamepadManager.prototype._checkGamepadsStatus = function () {
  78514. var _this = this;
  78515. // Hack to be compatible Chrome
  78516. this._updateGamepadObjects();
  78517. for (var i in this._babylonGamepads) {
  78518. var gamepad = this._babylonGamepads[i];
  78519. if (!gamepad || !gamepad.isConnected) {
  78520. continue;
  78521. }
  78522. gamepad.update();
  78523. }
  78524. if (this._isMonitoring && !this._scene) {
  78525. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  78526. }
  78527. };
  78528. // This function is called only on Chrome, which does not properly support
  78529. // connection/disconnection events and forces you to recopy again the gamepad object
  78530. GamepadManager.prototype._updateGamepadObjects = function () {
  78531. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  78532. for (var i = 0; i < gamepads.length; i++) {
  78533. var gamepad = gamepads[i];
  78534. if (gamepad) {
  78535. if (!this._babylonGamepads[gamepad.index]) {
  78536. var newGamepad = this._addNewGamepad(gamepad);
  78537. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  78538. }
  78539. else {
  78540. // Forced to copy again this object for Chrome for unknown reason
  78541. this._babylonGamepads[i].browserGamepad = gamepad;
  78542. if (!this._babylonGamepads[i].isConnected) {
  78543. this._babylonGamepads[i]._isConnected = true;
  78544. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  78545. }
  78546. }
  78547. }
  78548. }
  78549. };
  78550. return GamepadManager;
  78551. }());
  78552. BABYLON.GamepadManager = GamepadManager;
  78553. })(BABYLON || (BABYLON = {}));
  78554. //# sourceMappingURL=babylon.gamepadManager.js.map
  78555. var BABYLON;
  78556. (function (BABYLON) {
  78557. /**
  78558. * Represents a gamepad control stick position
  78559. */
  78560. var StickValues = /** @class */ (function () {
  78561. /**
  78562. * Initializes the gamepad x and y control stick values
  78563. * @param x The x component of the gamepad control stick value
  78564. * @param y The y component of the gamepad control stick value
  78565. */
  78566. function StickValues(
  78567. /**
  78568. * The x component of the control stick
  78569. */
  78570. x,
  78571. /**
  78572. * The y component of the control stick
  78573. */
  78574. y) {
  78575. this.x = x;
  78576. this.y = y;
  78577. }
  78578. return StickValues;
  78579. }());
  78580. BABYLON.StickValues = StickValues;
  78581. /**
  78582. * Represents a gamepad
  78583. */
  78584. var Gamepad = /** @class */ (function () {
  78585. /**
  78586. * Initializes the gamepad
  78587. * @param id The id of the gamepad
  78588. * @param index The index of the gamepad
  78589. * @param browserGamepad The browser gamepad
  78590. * @param leftStickX The x component of the left joystick
  78591. * @param leftStickY The y component of the left joystick
  78592. * @param rightStickX The x component of the right joystick
  78593. * @param rightStickY The y component of the right joystick
  78594. */
  78595. function Gamepad(
  78596. /**
  78597. * The id of the gamepad
  78598. */
  78599. id,
  78600. /**
  78601. * The index of the gamepad
  78602. */
  78603. index,
  78604. /**
  78605. * The browser gamepad
  78606. */
  78607. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  78608. if (leftStickX === void 0) { leftStickX = 0; }
  78609. if (leftStickY === void 0) { leftStickY = 1; }
  78610. if (rightStickX === void 0) { rightStickX = 2; }
  78611. if (rightStickY === void 0) { rightStickY = 3; }
  78612. this.id = id;
  78613. this.index = index;
  78614. this.browserGamepad = browserGamepad;
  78615. this._leftStick = { x: 0, y: 0 };
  78616. this._rightStick = { x: 0, y: 0 };
  78617. /** @hidden */
  78618. this._isConnected = true;
  78619. /**
  78620. * Specifies whether the left control stick should be Y-inverted
  78621. */
  78622. this._invertLeftStickY = false;
  78623. this.type = Gamepad.GAMEPAD;
  78624. this._leftStickAxisX = leftStickX;
  78625. this._leftStickAxisY = leftStickY;
  78626. this._rightStickAxisX = rightStickX;
  78627. this._rightStickAxisY = rightStickY;
  78628. if (this.browserGamepad.axes.length >= 2) {
  78629. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  78630. }
  78631. if (this.browserGamepad.axes.length >= 4) {
  78632. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  78633. }
  78634. }
  78635. Object.defineProperty(Gamepad.prototype, "isConnected", {
  78636. /**
  78637. * Specifies if the gamepad has been connected
  78638. */
  78639. get: function () {
  78640. return this._isConnected;
  78641. },
  78642. enumerable: true,
  78643. configurable: true
  78644. });
  78645. /**
  78646. * Callback triggered when the left joystick has changed
  78647. * @param callback
  78648. */
  78649. Gamepad.prototype.onleftstickchanged = function (callback) {
  78650. this._onleftstickchanged = callback;
  78651. };
  78652. /**
  78653. * Callback triggered when the right joystick has changed
  78654. * @param callback
  78655. */
  78656. Gamepad.prototype.onrightstickchanged = function (callback) {
  78657. this._onrightstickchanged = callback;
  78658. };
  78659. Object.defineProperty(Gamepad.prototype, "leftStick", {
  78660. /**
  78661. * Gets the left joystick
  78662. */
  78663. get: function () {
  78664. return this._leftStick;
  78665. },
  78666. /**
  78667. * Sets the left joystick values
  78668. */
  78669. set: function (newValues) {
  78670. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  78671. this._onleftstickchanged(newValues);
  78672. }
  78673. this._leftStick = newValues;
  78674. },
  78675. enumerable: true,
  78676. configurable: true
  78677. });
  78678. Object.defineProperty(Gamepad.prototype, "rightStick", {
  78679. /**
  78680. * Gets the right joystick
  78681. */
  78682. get: function () {
  78683. return this._rightStick;
  78684. },
  78685. /**
  78686. * Sets the right joystick value
  78687. */
  78688. set: function (newValues) {
  78689. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  78690. this._onrightstickchanged(newValues);
  78691. }
  78692. this._rightStick = newValues;
  78693. },
  78694. enumerable: true,
  78695. configurable: true
  78696. });
  78697. /**
  78698. * Updates the gamepad joystick positions
  78699. */
  78700. Gamepad.prototype.update = function () {
  78701. if (this._leftStick) {
  78702. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  78703. if (this._invertLeftStickY) {
  78704. this.leftStick.y *= -1;
  78705. }
  78706. }
  78707. if (this._rightStick) {
  78708. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  78709. }
  78710. };
  78711. /**
  78712. * Disposes the gamepad
  78713. */
  78714. Gamepad.prototype.dispose = function () {
  78715. };
  78716. /**
  78717. * Represents a gamepad controller
  78718. */
  78719. Gamepad.GAMEPAD = 0;
  78720. /**
  78721. * Represents a generic controller
  78722. */
  78723. Gamepad.GENERIC = 1;
  78724. /**
  78725. * Represents an XBox controller
  78726. */
  78727. Gamepad.XBOX = 2;
  78728. /**
  78729. * Represents a pose-enabled controller
  78730. */
  78731. Gamepad.POSE_ENABLED = 3;
  78732. return Gamepad;
  78733. }());
  78734. BABYLON.Gamepad = Gamepad;
  78735. /**
  78736. * Represents a generic gamepad
  78737. */
  78738. var GenericPad = /** @class */ (function (_super) {
  78739. __extends(GenericPad, _super);
  78740. /**
  78741. * Initializes the generic gamepad
  78742. * @param id The id of the generic gamepad
  78743. * @param index The index of the generic gamepad
  78744. * @param browserGamepad The browser gamepad
  78745. */
  78746. function GenericPad(id, index, browserGamepad) {
  78747. var _this = _super.call(this, id, index, browserGamepad) || this;
  78748. /**
  78749. * Observable triggered when a button has been pressed
  78750. */
  78751. _this.onButtonDownObservable = new BABYLON.Observable();
  78752. /**
  78753. * Observable triggered when a button has been released
  78754. */
  78755. _this.onButtonUpObservable = new BABYLON.Observable();
  78756. _this.type = Gamepad.GENERIC;
  78757. _this._buttons = new Array(browserGamepad.buttons.length);
  78758. return _this;
  78759. }
  78760. /**
  78761. * Callback triggered when a button has been pressed
  78762. * @param callback Called when a button has been pressed
  78763. */
  78764. GenericPad.prototype.onbuttondown = function (callback) {
  78765. this._onbuttondown = callback;
  78766. };
  78767. /**
  78768. * Callback triggered when a button has been released
  78769. * @param callback Called when a button has been released
  78770. */
  78771. GenericPad.prototype.onbuttonup = function (callback) {
  78772. this._onbuttonup = callback;
  78773. };
  78774. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  78775. if (newValue !== currentValue) {
  78776. if (newValue === 1) {
  78777. if (this._onbuttondown) {
  78778. this._onbuttondown(buttonIndex);
  78779. }
  78780. this.onButtonDownObservable.notifyObservers(buttonIndex);
  78781. }
  78782. if (newValue === 0) {
  78783. if (this._onbuttonup) {
  78784. this._onbuttonup(buttonIndex);
  78785. }
  78786. this.onButtonUpObservable.notifyObservers(buttonIndex);
  78787. }
  78788. }
  78789. return newValue;
  78790. };
  78791. /**
  78792. * Updates the generic gamepad
  78793. */
  78794. GenericPad.prototype.update = function () {
  78795. _super.prototype.update.call(this);
  78796. for (var index = 0; index < this._buttons.length; index++) {
  78797. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  78798. }
  78799. };
  78800. /**
  78801. * Disposes the generic gamepad
  78802. */
  78803. GenericPad.prototype.dispose = function () {
  78804. _super.prototype.dispose.call(this);
  78805. this.onButtonDownObservable.clear();
  78806. this.onButtonUpObservable.clear();
  78807. };
  78808. return GenericPad;
  78809. }(Gamepad));
  78810. BABYLON.GenericPad = GenericPad;
  78811. })(BABYLON || (BABYLON = {}));
  78812. //# sourceMappingURL=babylon.gamepad.js.map
  78813. var BABYLON;
  78814. (function (BABYLON) {
  78815. /**
  78816. * Defines supported buttons for XBox360 compatible gamepads
  78817. */
  78818. var Xbox360Button;
  78819. (function (Xbox360Button) {
  78820. /** A */
  78821. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  78822. /** B */
  78823. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  78824. /** X */
  78825. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  78826. /** Y */
  78827. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  78828. /** Start */
  78829. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  78830. /** Back */
  78831. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  78832. /** Left button */
  78833. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  78834. /** Right button */
  78835. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  78836. /** Left stick */
  78837. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  78838. /** Right stick */
  78839. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  78840. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  78841. /** Defines values for XBox360 DPad */
  78842. var Xbox360Dpad;
  78843. (function (Xbox360Dpad) {
  78844. /** Up */
  78845. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  78846. /** Down */
  78847. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  78848. /** Left */
  78849. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  78850. /** Right */
  78851. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  78852. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  78853. /**
  78854. * Defines a XBox360 gamepad
  78855. */
  78856. var Xbox360Pad = /** @class */ (function (_super) {
  78857. __extends(Xbox360Pad, _super);
  78858. /**
  78859. * Creates a new XBox360 gamepad object
  78860. * @param id defines the id of this gamepad
  78861. * @param index defines its index
  78862. * @param gamepad defines the internal HTML gamepad object
  78863. * @param xboxOne defines if it is a XBox One gamepad
  78864. */
  78865. function Xbox360Pad(id, index, gamepad, xboxOne) {
  78866. if (xboxOne === void 0) { xboxOne = false; }
  78867. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  78868. _this._leftTrigger = 0;
  78869. _this._rightTrigger = 0;
  78870. /** Observable raised when a button is pressed */
  78871. _this.onButtonDownObservable = new BABYLON.Observable();
  78872. /** Observable raised when a button is released */
  78873. _this.onButtonUpObservable = new BABYLON.Observable();
  78874. /** Observable raised when a pad is pressed */
  78875. _this.onPadDownObservable = new BABYLON.Observable();
  78876. /** Observable raised when a pad is released */
  78877. _this.onPadUpObservable = new BABYLON.Observable();
  78878. _this._buttonA = 0;
  78879. _this._buttonB = 0;
  78880. _this._buttonX = 0;
  78881. _this._buttonY = 0;
  78882. _this._buttonBack = 0;
  78883. _this._buttonStart = 0;
  78884. _this._buttonLB = 0;
  78885. _this._buttonRB = 0;
  78886. _this._buttonLeftStick = 0;
  78887. _this._buttonRightStick = 0;
  78888. _this._dPadUp = 0;
  78889. _this._dPadDown = 0;
  78890. _this._dPadLeft = 0;
  78891. _this._dPadRight = 0;
  78892. _this._isXboxOnePad = false;
  78893. _this.type = BABYLON.Gamepad.XBOX;
  78894. _this._isXboxOnePad = xboxOne;
  78895. return _this;
  78896. }
  78897. /**
  78898. * Defines the callback to call when left trigger is pressed
  78899. * @param callback defines the callback to use
  78900. */
  78901. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  78902. this._onlefttriggerchanged = callback;
  78903. };
  78904. /**
  78905. * Defines the callback to call when right trigger is pressed
  78906. * @param callback defines the callback to use
  78907. */
  78908. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  78909. this._onrighttriggerchanged = callback;
  78910. };
  78911. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  78912. /**
  78913. * Gets the left trigger value
  78914. */
  78915. get: function () {
  78916. return this._leftTrigger;
  78917. },
  78918. /**
  78919. * Sets the left trigger value
  78920. */
  78921. set: function (newValue) {
  78922. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  78923. this._onlefttriggerchanged(newValue);
  78924. }
  78925. this._leftTrigger = newValue;
  78926. },
  78927. enumerable: true,
  78928. configurable: true
  78929. });
  78930. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  78931. /**
  78932. * Gets the right trigger value
  78933. */
  78934. get: function () {
  78935. return this._rightTrigger;
  78936. },
  78937. /**
  78938. * Sets the right trigger value
  78939. */
  78940. set: function (newValue) {
  78941. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  78942. this._onrighttriggerchanged(newValue);
  78943. }
  78944. this._rightTrigger = newValue;
  78945. },
  78946. enumerable: true,
  78947. configurable: true
  78948. });
  78949. /**
  78950. * Defines the callback to call when a button is pressed
  78951. * @param callback defines the callback to use
  78952. */
  78953. Xbox360Pad.prototype.onbuttondown = function (callback) {
  78954. this._onbuttondown = callback;
  78955. };
  78956. /**
  78957. * Defines the callback to call when a button is released
  78958. * @param callback defines the callback to use
  78959. */
  78960. Xbox360Pad.prototype.onbuttonup = function (callback) {
  78961. this._onbuttonup = callback;
  78962. };
  78963. /**
  78964. * Defines the callback to call when a pad is pressed
  78965. * @param callback defines the callback to use
  78966. */
  78967. Xbox360Pad.prototype.ondpaddown = function (callback) {
  78968. this._ondpaddown = callback;
  78969. };
  78970. /**
  78971. * Defines the callback to call when a pad is released
  78972. * @param callback defines the callback to use
  78973. */
  78974. Xbox360Pad.prototype.ondpadup = function (callback) {
  78975. this._ondpadup = callback;
  78976. };
  78977. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  78978. if (newValue !== currentValue) {
  78979. if (newValue === 1) {
  78980. if (this._onbuttondown) {
  78981. this._onbuttondown(buttonType);
  78982. }
  78983. this.onButtonDownObservable.notifyObservers(buttonType);
  78984. }
  78985. if (newValue === 0) {
  78986. if (this._onbuttonup) {
  78987. this._onbuttonup(buttonType);
  78988. }
  78989. this.onButtonUpObservable.notifyObservers(buttonType);
  78990. }
  78991. }
  78992. return newValue;
  78993. };
  78994. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  78995. if (newValue !== currentValue) {
  78996. if (newValue === 1) {
  78997. if (this._ondpaddown) {
  78998. this._ondpaddown(buttonType);
  78999. }
  79000. this.onPadDownObservable.notifyObservers(buttonType);
  79001. }
  79002. if (newValue === 0) {
  79003. if (this._ondpadup) {
  79004. this._ondpadup(buttonType);
  79005. }
  79006. this.onPadUpObservable.notifyObservers(buttonType);
  79007. }
  79008. }
  79009. return newValue;
  79010. };
  79011. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  79012. /**
  79013. * Gets the value of the `A` button
  79014. */
  79015. get: function () {
  79016. return this._buttonA;
  79017. },
  79018. /**
  79019. * Sets the value of the `A` button
  79020. */
  79021. set: function (value) {
  79022. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  79023. },
  79024. enumerable: true,
  79025. configurable: true
  79026. });
  79027. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  79028. /**
  79029. * Gets the value of the `B` button
  79030. */
  79031. get: function () {
  79032. return this._buttonB;
  79033. },
  79034. /**
  79035. * Sets the value of the `B` button
  79036. */
  79037. set: function (value) {
  79038. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  79039. },
  79040. enumerable: true,
  79041. configurable: true
  79042. });
  79043. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  79044. /**
  79045. * Gets the value of the `X` button
  79046. */
  79047. get: function () {
  79048. return this._buttonX;
  79049. },
  79050. /**
  79051. * Sets the value of the `X` button
  79052. */
  79053. set: function (value) {
  79054. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  79055. },
  79056. enumerable: true,
  79057. configurable: true
  79058. });
  79059. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  79060. /**
  79061. * Gets the value of the `Y` button
  79062. */
  79063. get: function () {
  79064. return this._buttonY;
  79065. },
  79066. /**
  79067. * Sets the value of the `Y` button
  79068. */
  79069. set: function (value) {
  79070. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  79071. },
  79072. enumerable: true,
  79073. configurable: true
  79074. });
  79075. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  79076. /**
  79077. * Gets the value of the `Start` button
  79078. */
  79079. get: function () {
  79080. return this._buttonStart;
  79081. },
  79082. /**
  79083. * Sets the value of the `Start` button
  79084. */
  79085. set: function (value) {
  79086. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  79087. },
  79088. enumerable: true,
  79089. configurable: true
  79090. });
  79091. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  79092. /**
  79093. * Gets the value of the `Back` button
  79094. */
  79095. get: function () {
  79096. return this._buttonBack;
  79097. },
  79098. /**
  79099. * Sets the value of the `Back` button
  79100. */
  79101. set: function (value) {
  79102. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  79103. },
  79104. enumerable: true,
  79105. configurable: true
  79106. });
  79107. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  79108. /**
  79109. * Gets the value of the `Left` button
  79110. */
  79111. get: function () {
  79112. return this._buttonLB;
  79113. },
  79114. /**
  79115. * Sets the value of the `Left` button
  79116. */
  79117. set: function (value) {
  79118. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  79119. },
  79120. enumerable: true,
  79121. configurable: true
  79122. });
  79123. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  79124. /**
  79125. * Gets the value of the `Right` button
  79126. */
  79127. get: function () {
  79128. return this._buttonRB;
  79129. },
  79130. /**
  79131. * Sets the value of the `Right` button
  79132. */
  79133. set: function (value) {
  79134. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  79135. },
  79136. enumerable: true,
  79137. configurable: true
  79138. });
  79139. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  79140. /**
  79141. * Gets the value of the Left joystick
  79142. */
  79143. get: function () {
  79144. return this._buttonLeftStick;
  79145. },
  79146. /**
  79147. * Sets the value of the Left joystick
  79148. */
  79149. set: function (value) {
  79150. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  79151. },
  79152. enumerable: true,
  79153. configurable: true
  79154. });
  79155. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  79156. /**
  79157. * Gets the value of the Right joystick
  79158. */
  79159. get: function () {
  79160. return this._buttonRightStick;
  79161. },
  79162. /**
  79163. * Sets the value of the Right joystick
  79164. */
  79165. set: function (value) {
  79166. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  79167. },
  79168. enumerable: true,
  79169. configurable: true
  79170. });
  79171. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  79172. /**
  79173. * Gets the value of D-pad up
  79174. */
  79175. get: function () {
  79176. return this._dPadUp;
  79177. },
  79178. /**
  79179. * Sets the value of D-pad up
  79180. */
  79181. set: function (value) {
  79182. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  79183. },
  79184. enumerable: true,
  79185. configurable: true
  79186. });
  79187. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  79188. /**
  79189. * Gets the value of D-pad down
  79190. */
  79191. get: function () {
  79192. return this._dPadDown;
  79193. },
  79194. /**
  79195. * Sets the value of D-pad down
  79196. */
  79197. set: function (value) {
  79198. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  79199. },
  79200. enumerable: true,
  79201. configurable: true
  79202. });
  79203. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  79204. /**
  79205. * Gets the value of D-pad left
  79206. */
  79207. get: function () {
  79208. return this._dPadLeft;
  79209. },
  79210. /**
  79211. * Sets the value of D-pad left
  79212. */
  79213. set: function (value) {
  79214. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  79215. },
  79216. enumerable: true,
  79217. configurable: true
  79218. });
  79219. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  79220. /**
  79221. * Gets the value of D-pad right
  79222. */
  79223. get: function () {
  79224. return this._dPadRight;
  79225. },
  79226. /**
  79227. * Sets the value of D-pad right
  79228. */
  79229. set: function (value) {
  79230. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  79231. },
  79232. enumerable: true,
  79233. configurable: true
  79234. });
  79235. /**
  79236. * Force the gamepad to synchronize with device values
  79237. */
  79238. Xbox360Pad.prototype.update = function () {
  79239. _super.prototype.update.call(this);
  79240. if (this._isXboxOnePad) {
  79241. this.buttonA = this.browserGamepad.buttons[0].value;
  79242. this.buttonB = this.browserGamepad.buttons[1].value;
  79243. this.buttonX = this.browserGamepad.buttons[2].value;
  79244. this.buttonY = this.browserGamepad.buttons[3].value;
  79245. this.buttonLB = this.browserGamepad.buttons[4].value;
  79246. this.buttonRB = this.browserGamepad.buttons[5].value;
  79247. this.leftTrigger = this.browserGamepad.axes[2];
  79248. this.rightTrigger = this.browserGamepad.axes[5];
  79249. this.buttonBack = this.browserGamepad.buttons[9].value;
  79250. this.buttonStart = this.browserGamepad.buttons[8].value;
  79251. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  79252. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  79253. this.dPadUp = this.browserGamepad.buttons[11].value;
  79254. this.dPadDown = this.browserGamepad.buttons[12].value;
  79255. this.dPadLeft = this.browserGamepad.buttons[13].value;
  79256. this.dPadRight = this.browserGamepad.buttons[14].value;
  79257. }
  79258. else {
  79259. this.buttonA = this.browserGamepad.buttons[0].value;
  79260. this.buttonB = this.browserGamepad.buttons[1].value;
  79261. this.buttonX = this.browserGamepad.buttons[2].value;
  79262. this.buttonY = this.browserGamepad.buttons[3].value;
  79263. this.buttonLB = this.browserGamepad.buttons[4].value;
  79264. this.buttonRB = this.browserGamepad.buttons[5].value;
  79265. this.leftTrigger = this.browserGamepad.buttons[6].value;
  79266. this.rightTrigger = this.browserGamepad.buttons[7].value;
  79267. this.buttonBack = this.browserGamepad.buttons[8].value;
  79268. this.buttonStart = this.browserGamepad.buttons[9].value;
  79269. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  79270. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  79271. this.dPadUp = this.browserGamepad.buttons[12].value;
  79272. this.dPadDown = this.browserGamepad.buttons[13].value;
  79273. this.dPadLeft = this.browserGamepad.buttons[14].value;
  79274. this.dPadRight = this.browserGamepad.buttons[15].value;
  79275. }
  79276. };
  79277. /**
  79278. * Disposes the gamepad
  79279. */
  79280. Xbox360Pad.prototype.dispose = function () {
  79281. _super.prototype.dispose.call(this);
  79282. this.onButtonDownObservable.clear();
  79283. this.onButtonUpObservable.clear();
  79284. this.onPadDownObservable.clear();
  79285. this.onPadUpObservable.clear();
  79286. };
  79287. return Xbox360Pad;
  79288. }(BABYLON.Gamepad));
  79289. BABYLON.Xbox360Pad = Xbox360Pad;
  79290. })(BABYLON || (BABYLON = {}));
  79291. //# sourceMappingURL=babylon.xboxGamepad.js.map
  79292. var BABYLON;
  79293. (function (BABYLON) {
  79294. /**
  79295. * Defines the types of pose enabled controllers that are supported
  79296. */
  79297. var PoseEnabledControllerType;
  79298. (function (PoseEnabledControllerType) {
  79299. /**
  79300. * HTC Vive
  79301. */
  79302. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  79303. /**
  79304. * Oculus Rift
  79305. */
  79306. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  79307. /**
  79308. * Windows mixed reality
  79309. */
  79310. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  79311. /**
  79312. * Samsung gear VR
  79313. */
  79314. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  79315. /**
  79316. * Google Daydream
  79317. */
  79318. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  79319. /**
  79320. * Generic
  79321. */
  79322. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  79323. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  79324. /**
  79325. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79326. */
  79327. var PoseEnabledControllerHelper = /** @class */ (function () {
  79328. function PoseEnabledControllerHelper() {
  79329. }
  79330. /**
  79331. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79332. * @param vrGamepad the gamepad to initialized
  79333. * @returns a vr controller of the type the gamepad identified as
  79334. */
  79335. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  79336. // Oculus Touch
  79337. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  79338. return new BABYLON.OculusTouchController(vrGamepad);
  79339. }
  79340. // Windows Mixed Reality controllers
  79341. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  79342. return new BABYLON.WindowsMotionController(vrGamepad);
  79343. }
  79344. // HTC Vive
  79345. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  79346. return new BABYLON.ViveController(vrGamepad);
  79347. }
  79348. // Samsung/Oculus Gear VR or Oculus Go
  79349. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  79350. return new BABYLON.GearVRController(vrGamepad);
  79351. }
  79352. // Google Daydream
  79353. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  79354. return new BABYLON.DaydreamController(vrGamepad);
  79355. }
  79356. // Generic
  79357. else {
  79358. return new BABYLON.GenericController(vrGamepad);
  79359. }
  79360. };
  79361. return PoseEnabledControllerHelper;
  79362. }());
  79363. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  79364. /**
  79365. * Defines the PoseEnabledController object that contains state of a vr capable controller
  79366. */
  79367. var PoseEnabledController = /** @class */ (function (_super) {
  79368. __extends(PoseEnabledController, _super);
  79369. /**
  79370. * Creates a new PoseEnabledController from a gamepad
  79371. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  79372. */
  79373. function PoseEnabledController(browserGamepad) {
  79374. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  79375. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79376. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79377. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  79378. /**
  79379. * The device position in babylon space
  79380. */
  79381. _this.devicePosition = BABYLON.Vector3.Zero();
  79382. /**
  79383. * The device rotation in babylon space
  79384. */
  79385. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  79386. /**
  79387. * The scale factor of the device in babylon space
  79388. */
  79389. _this.deviceScaleFactor = 1;
  79390. // Used to convert 6dof controllers to 3dof
  79391. _this._trackPosition = true;
  79392. _this._maxRotationDistFromHeadset = Math.PI / 5;
  79393. _this._draggedRoomRotation = 0;
  79394. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  79395. /**
  79396. * Internal, matrix used to convert room space to babylon space
  79397. * @hidden
  79398. */
  79399. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79400. /**
  79401. * Node to be used when casting a ray from the controller
  79402. * @hidden
  79403. */
  79404. _this._pointingPoseNode = null;
  79405. _this._workingMatrix = BABYLON.Matrix.Identity();
  79406. /**
  79407. * @hidden
  79408. */
  79409. _this._meshAttachedObservable = new BABYLON.Observable();
  79410. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  79411. _this.controllerType = PoseEnabledControllerType.GENERIC;
  79412. _this.position = BABYLON.Vector3.Zero();
  79413. _this.rotationQuaternion = new BABYLON.Quaternion();
  79414. _this._calculatedPosition = BABYLON.Vector3.Zero();
  79415. _this._calculatedRotation = new BABYLON.Quaternion();
  79416. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  79417. return _this;
  79418. }
  79419. /**
  79420. * @hidden
  79421. */
  79422. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  79423. if (this._trackPosition) {
  79424. this._calculatedPosition.copyFrom(fixedPosition);
  79425. this._trackPosition = false;
  79426. }
  79427. };
  79428. /**
  79429. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  79430. */
  79431. PoseEnabledController.prototype.update = function () {
  79432. _super.prototype.update.call(this);
  79433. this._updatePoseAndMesh();
  79434. };
  79435. /**
  79436. * Updates only the pose device and mesh without doing any button event checking
  79437. */
  79438. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  79439. var pose = this.browserGamepad.pose;
  79440. this.updateFromDevice(pose);
  79441. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  79442. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  79443. camera._computeDevicePosition();
  79444. this._deviceToWorld.setTranslation(camera.devicePosition);
  79445. if (camera.deviceRotationQuaternion) {
  79446. var camera = camera;
  79447. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  79448. // Find the radian distance away that the headset is from the controllers rotation
  79449. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  79450. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  79451. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  79452. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  79453. this._draggedRoomRotation += rotationAmount;
  79454. // Rotate controller around headset
  79455. var sin = Math.sin(-rotationAmount);
  79456. var cos = Math.cos(-rotationAmount);
  79457. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  79458. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  79459. }
  79460. }
  79461. }
  79462. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  79463. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  79464. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79465. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  79466. if (this._mesh) {
  79467. this._mesh.position.copyFrom(this.devicePosition);
  79468. if (this._mesh.rotationQuaternion) {
  79469. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  79470. }
  79471. }
  79472. };
  79473. /**
  79474. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  79475. * @param poseData raw pose fromthe device
  79476. */
  79477. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  79478. if (poseData) {
  79479. this.rawPose = poseData;
  79480. if (poseData.position) {
  79481. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  79482. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  79483. this._deviceRoomPosition.z *= -1;
  79484. }
  79485. if (this._trackPosition) {
  79486. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  79487. }
  79488. this._calculatedPosition.addInPlace(this.position);
  79489. }
  79490. var pose = this.rawPose;
  79491. if (poseData.orientation && pose.orientation) {
  79492. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  79493. if (this._mesh) {
  79494. if (this._mesh.getScene().useRightHandedSystem) {
  79495. this._deviceRoomRotationQuaternion.z *= -1;
  79496. this._deviceRoomRotationQuaternion.w *= -1;
  79497. }
  79498. else {
  79499. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  79500. }
  79501. }
  79502. // if the camera is set, rotate to the camera's rotation
  79503. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  79504. }
  79505. }
  79506. };
  79507. /**
  79508. * Attaches a mesh to the controller
  79509. * @param mesh the mesh to be attached
  79510. */
  79511. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  79512. if (this._mesh) {
  79513. this._mesh.parent = null;
  79514. }
  79515. this._mesh = mesh;
  79516. if (this._poseControlledCamera) {
  79517. this._mesh.parent = this._poseControlledCamera;
  79518. }
  79519. if (!this._mesh.rotationQuaternion) {
  79520. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  79521. }
  79522. // 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
  79523. this._updatePoseAndMesh();
  79524. if (this._pointingPoseNode) {
  79525. var parents = [];
  79526. var obj = this._pointingPoseNode;
  79527. while (obj.parent) {
  79528. parents.push(obj.parent);
  79529. obj = obj.parent;
  79530. }
  79531. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  79532. }
  79533. this._meshAttachedObservable.notifyObservers(mesh);
  79534. };
  79535. /**
  79536. * Attaches the controllers mesh to a camera
  79537. * @param camera the camera the mesh should be attached to
  79538. */
  79539. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  79540. this._poseControlledCamera = camera;
  79541. if (this._mesh) {
  79542. this._mesh.parent = this._poseControlledCamera;
  79543. }
  79544. };
  79545. /**
  79546. * Disposes of the controller
  79547. */
  79548. PoseEnabledController.prototype.dispose = function () {
  79549. if (this._mesh) {
  79550. this._mesh.dispose();
  79551. }
  79552. this._mesh = null;
  79553. _super.prototype.dispose.call(this);
  79554. };
  79555. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  79556. /**
  79557. * The mesh that is attached to the controller
  79558. */
  79559. get: function () {
  79560. return this._mesh;
  79561. },
  79562. enumerable: true,
  79563. configurable: true
  79564. });
  79565. /**
  79566. * Gets the ray of the controller in the direction the controller is pointing
  79567. * @param length the length the resulting ray should be
  79568. * @returns a ray in the direction the controller is pointing
  79569. */
  79570. PoseEnabledController.prototype.getForwardRay = function (length) {
  79571. if (length === void 0) { length = 100; }
  79572. if (!this.mesh) {
  79573. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  79574. }
  79575. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  79576. var origin = m.getTranslation();
  79577. var forward = new BABYLON.Vector3(0, 0, -1);
  79578. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79579. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79580. return new BABYLON.Ray(origin, direction, length);
  79581. };
  79582. /**
  79583. * Name of the child mesh that can be used to cast a ray from the controller
  79584. */
  79585. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  79586. return PoseEnabledController;
  79587. }(BABYLON.Gamepad));
  79588. BABYLON.PoseEnabledController = PoseEnabledController;
  79589. })(BABYLON || (BABYLON = {}));
  79590. //# sourceMappingURL=babylon.poseEnabledController.js.map
  79591. var BABYLON;
  79592. (function (BABYLON) {
  79593. /**
  79594. * Defines the WebVRController object that represents controllers tracked in 3D space
  79595. */
  79596. var WebVRController = /** @class */ (function (_super) {
  79597. __extends(WebVRController, _super);
  79598. /**
  79599. * Creates a new WebVRController from a gamepad
  79600. * @param vrGamepad the gamepad that the WebVRController should be created from
  79601. */
  79602. function WebVRController(vrGamepad) {
  79603. var _this = _super.call(this, vrGamepad) || this;
  79604. // Observables
  79605. /**
  79606. * Fired when the trigger state has changed
  79607. */
  79608. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  79609. /**
  79610. * Fired when the main button state has changed
  79611. */
  79612. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  79613. /**
  79614. * Fired when the secondary button state has changed
  79615. */
  79616. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  79617. /**
  79618. * Fired when the pad state has changed
  79619. */
  79620. _this.onPadStateChangedObservable = new BABYLON.Observable();
  79621. /**
  79622. * Fired when controllers stick values have changed
  79623. */
  79624. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  79625. /**
  79626. * X and Y axis corrisponding to the controllers joystick
  79627. */
  79628. _this.pad = { x: 0, y: 0 };
  79629. // avoid GC, store state in a tmp object
  79630. _this._changes = {
  79631. pressChanged: false,
  79632. touchChanged: false,
  79633. valueChanged: false,
  79634. changed: false
  79635. };
  79636. _this._buttons = new Array(vrGamepad.buttons.length);
  79637. _this.hand = vrGamepad.hand;
  79638. return _this;
  79639. }
  79640. /**
  79641. * Fired when a controller button's state has changed
  79642. * @param callback the callback containing the button that was modified
  79643. */
  79644. WebVRController.prototype.onButtonStateChange = function (callback) {
  79645. this._onButtonStateChange = callback;
  79646. };
  79647. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  79648. /**
  79649. * The default controller model for the controller
  79650. */
  79651. get: function () {
  79652. return this._defaultModel;
  79653. },
  79654. enumerable: true,
  79655. configurable: true
  79656. });
  79657. /**
  79658. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  79659. */
  79660. WebVRController.prototype.update = function () {
  79661. _super.prototype.update.call(this);
  79662. for (var index = 0; index < this._buttons.length; index++) {
  79663. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  79664. }
  79665. ;
  79666. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  79667. this.pad.x = this.leftStick.x;
  79668. this.pad.y = this.leftStick.y;
  79669. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  79670. }
  79671. };
  79672. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  79673. if (!newState) {
  79674. newState = {
  79675. pressed: false,
  79676. touched: false,
  79677. value: 0
  79678. };
  79679. }
  79680. if (!currentState) {
  79681. this._buttons[buttonIndex] = {
  79682. pressed: newState.pressed,
  79683. touched: newState.touched,
  79684. value: newState.value
  79685. };
  79686. return;
  79687. }
  79688. this._checkChanges(newState, currentState);
  79689. if (this._changes.changed) {
  79690. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  79691. this._handleButtonChange(buttonIndex, newState, this._changes);
  79692. }
  79693. this._buttons[buttonIndex].pressed = newState.pressed;
  79694. this._buttons[buttonIndex].touched = newState.touched;
  79695. // oculus triggers are never 0, thou not touched.
  79696. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  79697. };
  79698. WebVRController.prototype._checkChanges = function (newState, currentState) {
  79699. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  79700. this._changes.touchChanged = newState.touched !== currentState.touched;
  79701. this._changes.valueChanged = newState.value !== currentState.value;
  79702. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  79703. return this._changes;
  79704. };
  79705. /**
  79706. * Disposes of th webVRCOntroller
  79707. */
  79708. WebVRController.prototype.dispose = function () {
  79709. _super.prototype.dispose.call(this);
  79710. this.onTriggerStateChangedObservable.clear();
  79711. this.onMainButtonStateChangedObservable.clear();
  79712. this.onSecondaryButtonStateChangedObservable.clear();
  79713. this.onPadStateChangedObservable.clear();
  79714. this.onPadValuesChangedObservable.clear();
  79715. };
  79716. return WebVRController;
  79717. }(BABYLON.PoseEnabledController));
  79718. BABYLON.WebVRController = WebVRController;
  79719. })(BABYLON || (BABYLON = {}));
  79720. //# sourceMappingURL=babylon.webVRController.js.map
  79721. var BABYLON;
  79722. (function (BABYLON) {
  79723. /**
  79724. * Oculus Touch Controller
  79725. */
  79726. var OculusTouchController = /** @class */ (function (_super) {
  79727. __extends(OculusTouchController, _super);
  79728. /**
  79729. * Creates a new OculusTouchController from a gamepad
  79730. * @param vrGamepad the gamepad that the controller should be created from
  79731. */
  79732. function OculusTouchController(vrGamepad) {
  79733. var _this = _super.call(this, vrGamepad) || this;
  79734. /**
  79735. * Fired when the secondary trigger on this controller is modified
  79736. */
  79737. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  79738. /**
  79739. * Fired when the thumb rest on this controller is modified
  79740. */
  79741. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  79742. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  79743. return _this;
  79744. }
  79745. /**
  79746. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79747. * @param scene scene in which to add meshes
  79748. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79749. */
  79750. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79751. var _this = this;
  79752. var meshName;
  79753. // Hand
  79754. if (this.hand === 'left') {
  79755. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  79756. }
  79757. else { // Right is the default if no hand is specified
  79758. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  79759. }
  79760. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  79761. /*
  79762. Parent Mesh name: oculus_touch_left
  79763. - body
  79764. - trigger
  79765. - thumbstick
  79766. - grip
  79767. - button_y
  79768. - button_x
  79769. - button_enter
  79770. */
  79771. _this._defaultModel = newMeshes[1];
  79772. _this.attachToMesh(_this._defaultModel);
  79773. if (meshLoaded) {
  79774. meshLoaded(_this._defaultModel);
  79775. }
  79776. });
  79777. };
  79778. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  79779. /**
  79780. * Fired when the A button on this controller is modified
  79781. */
  79782. get: function () {
  79783. if (this.hand === 'right') {
  79784. return this.onMainButtonStateChangedObservable;
  79785. }
  79786. else {
  79787. throw new Error('No A button on left hand');
  79788. }
  79789. },
  79790. enumerable: true,
  79791. configurable: true
  79792. });
  79793. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  79794. /**
  79795. * Fired when the B button on this controller is modified
  79796. */
  79797. get: function () {
  79798. if (this.hand === 'right') {
  79799. return this.onSecondaryButtonStateChangedObservable;
  79800. }
  79801. else {
  79802. throw new Error('No B button on left hand');
  79803. }
  79804. },
  79805. enumerable: true,
  79806. configurable: true
  79807. });
  79808. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  79809. /**
  79810. * Fired when the X button on this controller is modified
  79811. */
  79812. get: function () {
  79813. if (this.hand === 'left') {
  79814. return this.onMainButtonStateChangedObservable;
  79815. }
  79816. else {
  79817. throw new Error('No X button on right hand');
  79818. }
  79819. },
  79820. enumerable: true,
  79821. configurable: true
  79822. });
  79823. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  79824. /**
  79825. * Fired when the Y button on this controller is modified
  79826. */
  79827. get: function () {
  79828. if (this.hand === 'left') {
  79829. return this.onSecondaryButtonStateChangedObservable;
  79830. }
  79831. else {
  79832. throw new Error('No Y button on right hand');
  79833. }
  79834. },
  79835. enumerable: true,
  79836. configurable: true
  79837. });
  79838. /**
  79839. * Called once for each button that changed state since the last frame
  79840. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  79841. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  79842. * 2) secondary trigger (same)
  79843. * 3) A (right) X (left), touch, pressed = value
  79844. * 4) B / Y
  79845. * 5) thumb rest
  79846. * @param buttonIdx Which button index changed
  79847. * @param state New state of the button
  79848. * @param changes Which properties on the state changed since last frame
  79849. */
  79850. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79851. var notifyObject = state; //{ state: state, changes: changes };
  79852. var triggerDirection = this.hand === 'right' ? -1 : 1;
  79853. switch (buttonIdx) {
  79854. case 0:
  79855. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  79856. return;
  79857. case 1: // index trigger
  79858. if (this._defaultModel) {
  79859. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  79860. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  79861. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  79862. }
  79863. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  79864. return;
  79865. case 2: // secondary trigger
  79866. if (this._defaultModel) {
  79867. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  79868. }
  79869. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  79870. return;
  79871. case 3:
  79872. if (this._defaultModel) {
  79873. if (notifyObject.pressed) {
  79874. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  79875. }
  79876. else {
  79877. (this._defaultModel.getChildren()[1]).position.y = 0;
  79878. }
  79879. }
  79880. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  79881. return;
  79882. case 4:
  79883. if (this._defaultModel) {
  79884. if (notifyObject.pressed) {
  79885. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  79886. }
  79887. else {
  79888. (this._defaultModel.getChildren()[2]).position.y = 0;
  79889. }
  79890. }
  79891. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  79892. return;
  79893. case 5:
  79894. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  79895. return;
  79896. }
  79897. };
  79898. /**
  79899. * Base Url for the controller model.
  79900. */
  79901. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  79902. /**
  79903. * File name for the left controller model.
  79904. */
  79905. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  79906. /**
  79907. * File name for the right controller model.
  79908. */
  79909. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  79910. return OculusTouchController;
  79911. }(BABYLON.WebVRController));
  79912. BABYLON.OculusTouchController = OculusTouchController;
  79913. })(BABYLON || (BABYLON = {}));
  79914. //# sourceMappingURL=babylon.oculusTouchController.js.map
  79915. var BABYLON;
  79916. (function (BABYLON) {
  79917. /**
  79918. * Vive Controller
  79919. */
  79920. var ViveController = /** @class */ (function (_super) {
  79921. __extends(ViveController, _super);
  79922. /**
  79923. * Creates a new ViveController from a gamepad
  79924. * @param vrGamepad the gamepad that the controller should be created from
  79925. */
  79926. function ViveController(vrGamepad) {
  79927. var _this = _super.call(this, vrGamepad) || this;
  79928. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  79929. _this._invertLeftStickY = true;
  79930. return _this;
  79931. }
  79932. /**
  79933. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79934. * @param scene scene in which to add meshes
  79935. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79936. */
  79937. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79938. var _this = this;
  79939. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  79940. /*
  79941. Parent Mesh name: ViveWand
  79942. - body
  79943. - r_gripper
  79944. - l_gripper
  79945. - menu_button
  79946. - system_button
  79947. - trackpad
  79948. - trigger
  79949. - LED
  79950. */
  79951. _this._defaultModel = newMeshes[1];
  79952. _this.attachToMesh(_this._defaultModel);
  79953. if (meshLoaded) {
  79954. meshLoaded(_this._defaultModel);
  79955. }
  79956. });
  79957. };
  79958. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  79959. /**
  79960. * Fired when the left button on this controller is modified
  79961. */
  79962. get: function () {
  79963. return this.onMainButtonStateChangedObservable;
  79964. },
  79965. enumerable: true,
  79966. configurable: true
  79967. });
  79968. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  79969. /**
  79970. * Fired when the right button on this controller is modified
  79971. */
  79972. get: function () {
  79973. return this.onMainButtonStateChangedObservable;
  79974. },
  79975. enumerable: true,
  79976. configurable: true
  79977. });
  79978. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  79979. /**
  79980. * Fired when the menu button on this controller is modified
  79981. */
  79982. get: function () {
  79983. return this.onSecondaryButtonStateChangedObservable;
  79984. },
  79985. enumerable: true,
  79986. configurable: true
  79987. });
  79988. /**
  79989. * Called once for each button that changed state since the last frame
  79990. * Vive mapping:
  79991. * 0: touchpad
  79992. * 1: trigger
  79993. * 2: left AND right buttons
  79994. * 3: menu button
  79995. * @param buttonIdx Which button index changed
  79996. * @param state New state of the button
  79997. * @param changes Which properties on the state changed since last frame
  79998. */
  79999. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80000. var notifyObject = state; //{ state: state, changes: changes };
  80001. switch (buttonIdx) {
  80002. case 0:
  80003. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80004. return;
  80005. case 1: // index trigger
  80006. if (this._defaultModel) {
  80007. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  80008. }
  80009. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80010. return;
  80011. case 2: // left AND right button
  80012. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80013. return;
  80014. case 3:
  80015. if (this._defaultModel) {
  80016. if (notifyObject.pressed) {
  80017. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80018. }
  80019. else {
  80020. (this._defaultModel.getChildren()[2]).position.y = 0;
  80021. }
  80022. }
  80023. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80024. return;
  80025. }
  80026. };
  80027. /**
  80028. * Base Url for the controller model.
  80029. */
  80030. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  80031. /**
  80032. * File name for the controller model.
  80033. */
  80034. ViveController.MODEL_FILENAME = 'wand.babylon';
  80035. return ViveController;
  80036. }(BABYLON.WebVRController));
  80037. BABYLON.ViveController = ViveController;
  80038. })(BABYLON || (BABYLON = {}));
  80039. //# sourceMappingURL=babylon.viveController.js.map
  80040. var BABYLON;
  80041. (function (BABYLON) {
  80042. /**
  80043. * Generic Controller
  80044. */
  80045. var GenericController = /** @class */ (function (_super) {
  80046. __extends(GenericController, _super);
  80047. /**
  80048. * Creates a new GenericController from a gamepad
  80049. * @param vrGamepad the gamepad that the controller should be created from
  80050. */
  80051. function GenericController(vrGamepad) {
  80052. return _super.call(this, vrGamepad) || this;
  80053. }
  80054. /**
  80055. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80056. * @param scene scene in which to add meshes
  80057. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80058. */
  80059. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80060. var _this = this;
  80061. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  80062. _this._defaultModel = newMeshes[1];
  80063. _this.attachToMesh(_this._defaultModel);
  80064. if (meshLoaded) {
  80065. meshLoaded(_this._defaultModel);
  80066. }
  80067. });
  80068. };
  80069. /**
  80070. * Called once for each button that changed state since the last frame
  80071. * @param buttonIdx Which button index changed
  80072. * @param state New state of the button
  80073. * @param changes Which properties on the state changed since last frame
  80074. */
  80075. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80076. console.log("Button id: " + buttonIdx + "state: ");
  80077. console.dir(state);
  80078. };
  80079. /**
  80080. * Base Url for the controller model.
  80081. */
  80082. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80083. /**
  80084. * File name for the controller model.
  80085. */
  80086. GenericController.MODEL_FILENAME = 'generic.babylon';
  80087. return GenericController;
  80088. }(BABYLON.WebVRController));
  80089. BABYLON.GenericController = GenericController;
  80090. })(BABYLON || (BABYLON = {}));
  80091. //# sourceMappingURL=babylon.genericController.js.map
  80092. var BABYLON;
  80093. (function (BABYLON) {
  80094. /**
  80095. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  80096. */
  80097. var LoadedMeshInfo = /** @class */ (function () {
  80098. function LoadedMeshInfo() {
  80099. /**
  80100. * Map of the button meshes contained in the controller
  80101. */
  80102. this.buttonMeshes = {};
  80103. /**
  80104. * Map of the axis meshes contained in the controller
  80105. */
  80106. this.axisMeshes = {};
  80107. }
  80108. return LoadedMeshInfo;
  80109. }());
  80110. /**
  80111. * Defines the WindowsMotionController object that the state of the windows motion controller
  80112. */
  80113. var WindowsMotionController = /** @class */ (function (_super) {
  80114. __extends(WindowsMotionController, _super);
  80115. /**
  80116. * Creates a new WindowsMotionController from a gamepad
  80117. * @param vrGamepad the gamepad that the controller should be created from
  80118. */
  80119. function WindowsMotionController(vrGamepad) {
  80120. var _this = _super.call(this, vrGamepad) || this;
  80121. _this._mapping = {
  80122. // Semantic button names
  80123. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  80124. // A mapping of the button name to glTF model node name
  80125. // that should be transformed by button value.
  80126. buttonMeshNames: {
  80127. 'trigger': 'SELECT',
  80128. 'menu': 'MENU',
  80129. 'grip': 'GRASP',
  80130. 'thumbstick': 'THUMBSTICK_PRESS',
  80131. 'trackpad': 'TOUCHPAD_PRESS'
  80132. },
  80133. // This mapping is used to translate from the Motion Controller to Babylon semantics
  80134. buttonObservableNames: {
  80135. 'trigger': 'onTriggerStateChangedObservable',
  80136. 'menu': 'onSecondaryButtonStateChangedObservable',
  80137. 'grip': 'onMainButtonStateChangedObservable',
  80138. 'thumbstick': 'onPadStateChangedObservable',
  80139. 'trackpad': 'onTrackpadChangedObservable'
  80140. },
  80141. // A mapping of the axis name to glTF model node name
  80142. // that should be transformed by axis value.
  80143. // This array mirrors the browserGamepad.axes array, such that
  80144. // the mesh corresponding to axis 0 is in this array index 0.
  80145. axisMeshNames: [
  80146. 'THUMBSTICK_X',
  80147. 'THUMBSTICK_Y',
  80148. 'TOUCHPAD_TOUCH_X',
  80149. 'TOUCHPAD_TOUCH_Y'
  80150. ],
  80151. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  80152. };
  80153. /**
  80154. * Fired when the trackpad on this controller is clicked
  80155. */
  80156. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  80157. /**
  80158. * Fired when the trackpad on this controller is modified
  80159. */
  80160. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  80161. /**
  80162. * The current x and y values of this controller's trackpad
  80163. */
  80164. _this.trackpad = { x: 0, y: 0 };
  80165. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  80166. _this._loadedMeshInfo = null;
  80167. return _this;
  80168. }
  80169. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  80170. /**
  80171. * Fired when the trigger on this controller is modified
  80172. */
  80173. get: function () {
  80174. return this.onTriggerStateChangedObservable;
  80175. },
  80176. enumerable: true,
  80177. configurable: true
  80178. });
  80179. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  80180. /**
  80181. * Fired when the menu button on this controller is modified
  80182. */
  80183. get: function () {
  80184. return this.onSecondaryButtonStateChangedObservable;
  80185. },
  80186. enumerable: true,
  80187. configurable: true
  80188. });
  80189. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  80190. /**
  80191. * Fired when the grip button on this controller is modified
  80192. */
  80193. get: function () {
  80194. return this.onMainButtonStateChangedObservable;
  80195. },
  80196. enumerable: true,
  80197. configurable: true
  80198. });
  80199. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  80200. /**
  80201. * Fired when the thumbstick button on this controller is modified
  80202. */
  80203. get: function () {
  80204. return this.onPadStateChangedObservable;
  80205. },
  80206. enumerable: true,
  80207. configurable: true
  80208. });
  80209. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  80210. /**
  80211. * Fired when the touchpad button on this controller is modified
  80212. */
  80213. get: function () {
  80214. return this.onTrackpadChangedObservable;
  80215. },
  80216. enumerable: true,
  80217. configurable: true
  80218. });
  80219. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  80220. /**
  80221. * Fired when the touchpad values on this controller are modified
  80222. */
  80223. get: function () {
  80224. return this.onTrackpadValuesChangedObservable;
  80225. },
  80226. enumerable: true,
  80227. configurable: true
  80228. });
  80229. WindowsMotionController.prototype._updateTrackpad = function () {
  80230. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  80231. this.trackpad.x = this.browserGamepad["axes"][2];
  80232. this.trackpad.y = this.browserGamepad["axes"][3];
  80233. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  80234. }
  80235. };
  80236. /**
  80237. * Called once per frame by the engine.
  80238. */
  80239. WindowsMotionController.prototype.update = function () {
  80240. _super.prototype.update.call(this);
  80241. if (this.browserGamepad.axes) {
  80242. this._updateTrackpad();
  80243. // Only need to animate axes if there is a loaded mesh
  80244. if (this._loadedMeshInfo) {
  80245. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  80246. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  80247. }
  80248. }
  80249. }
  80250. };
  80251. /**
  80252. * Called once for each button that changed state since the last frame
  80253. * @param buttonIdx Which button index changed
  80254. * @param state New state of the button
  80255. * @param changes Which properties on the state changed since last frame
  80256. */
  80257. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80258. var buttonName = this._mapping.buttons[buttonIdx];
  80259. if (!buttonName) {
  80260. return;
  80261. }
  80262. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  80263. this._updateTrackpad();
  80264. // Only emit events for buttons that we know how to map from index to name
  80265. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  80266. if (observable) {
  80267. observable.notifyObservers(state);
  80268. }
  80269. this._lerpButtonTransform(buttonName, state.value);
  80270. };
  80271. /**
  80272. * Moves the buttons on the controller mesh based on their current state
  80273. * @param buttonName the name of the button to move
  80274. * @param buttonValue the value of the button which determines the buttons new position
  80275. */
  80276. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  80277. // If there is no loaded mesh, there is nothing to transform.
  80278. if (!this._loadedMeshInfo) {
  80279. return;
  80280. }
  80281. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  80282. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80283. return;
  80284. }
  80285. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  80286. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  80287. };
  80288. /**
  80289. * Moves the axis on the controller mesh based on its current state
  80290. * @param axis the index of the axis
  80291. * @param axisValue the value of the axis which determines the meshes new position
  80292. * @hidden
  80293. */
  80294. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  80295. if (!this._loadedMeshInfo) {
  80296. return;
  80297. }
  80298. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  80299. if (!meshInfo) {
  80300. return;
  80301. }
  80302. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80303. return;
  80304. }
  80305. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  80306. var lerpValue = axisValue * 0.5 + 0.5;
  80307. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  80308. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  80309. };
  80310. /**
  80311. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80312. * @param scene scene in which to add meshes
  80313. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80314. */
  80315. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  80316. var _this = this;
  80317. if (forceDefault === void 0) { forceDefault = false; }
  80318. var path;
  80319. var filename;
  80320. // Checking if GLB loader is present
  80321. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  80322. // Determine the device specific folder based on the ID suffix
  80323. var device = 'default';
  80324. if (this.id && !forceDefault) {
  80325. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  80326. device = ((match && match[0]) || device);
  80327. }
  80328. // Hand
  80329. if (this.hand === 'left') {
  80330. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  80331. }
  80332. else { // Right is the default if no hand is specified
  80333. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  80334. }
  80335. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  80336. }
  80337. else {
  80338. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  80339. path = BABYLON.GenericController.MODEL_BASE_URL;
  80340. filename = BABYLON.GenericController.MODEL_FILENAME;
  80341. }
  80342. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  80343. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  80344. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  80345. if (!_this._loadedMeshInfo) {
  80346. return;
  80347. }
  80348. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  80349. _this.attachToMesh(_this._defaultModel);
  80350. if (meshLoaded) {
  80351. meshLoaded(_this._defaultModel);
  80352. }
  80353. }, null, function (scene, message) {
  80354. BABYLON.Tools.Log(message);
  80355. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  80356. if (!forceDefault) {
  80357. _this.initControllerMesh(scene, meshLoaded, true);
  80358. }
  80359. });
  80360. };
  80361. /**
  80362. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  80363. * can be transformed by button presses and axes values, based on this._mapping.
  80364. *
  80365. * @param scene scene in which the meshes exist
  80366. * @param meshes list of meshes that make up the controller model to process
  80367. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  80368. */
  80369. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  80370. var loadedMeshInfo = null;
  80371. // Create a new mesh to contain the glTF hierarchy
  80372. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  80373. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  80374. var childMesh = null;
  80375. for (var i = 0; i < meshes.length; i++) {
  80376. var mesh = meshes[i];
  80377. if (!mesh.parent) {
  80378. // Exclude controller meshes from picking results
  80379. mesh.isPickable = false;
  80380. // Handle root node, attach to the new parentMesh
  80381. childMesh = mesh;
  80382. break;
  80383. }
  80384. }
  80385. if (childMesh) {
  80386. childMesh.setParent(parentMesh);
  80387. // Create our mesh info. Note that this method will always return non-null.
  80388. loadedMeshInfo = this.createMeshInfo(parentMesh);
  80389. }
  80390. else {
  80391. BABYLON.Tools.Warn('Could not find root node in model file.');
  80392. }
  80393. return loadedMeshInfo;
  80394. };
  80395. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  80396. var loadedMeshInfo = new LoadedMeshInfo();
  80397. var i;
  80398. loadedMeshInfo.rootNode = rootNode;
  80399. // Reset the caches
  80400. loadedMeshInfo.buttonMeshes = {};
  80401. loadedMeshInfo.axisMeshes = {};
  80402. // Button Meshes
  80403. for (i = 0; i < this._mapping.buttons.length; i++) {
  80404. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  80405. if (!buttonMeshName) {
  80406. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  80407. continue;
  80408. }
  80409. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  80410. if (!buttonMesh) {
  80411. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  80412. continue;
  80413. }
  80414. var buttonMeshInfo = {
  80415. index: i,
  80416. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  80417. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  80418. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  80419. };
  80420. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  80421. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  80422. }
  80423. else {
  80424. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  80425. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  80426. '(VALUE: ' + !!buttonMeshInfo.value +
  80427. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  80428. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  80429. ')');
  80430. }
  80431. }
  80432. // Axis Meshes
  80433. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  80434. var axisMeshName = this._mapping.axisMeshNames[i];
  80435. if (!axisMeshName) {
  80436. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  80437. continue;
  80438. }
  80439. var axisMesh = getChildByName(rootNode, axisMeshName);
  80440. if (!axisMesh) {
  80441. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  80442. continue;
  80443. }
  80444. var axisMeshInfo = {
  80445. index: i,
  80446. value: getImmediateChildByName(axisMesh, 'VALUE'),
  80447. min: getImmediateChildByName(axisMesh, 'MIN'),
  80448. max: getImmediateChildByName(axisMesh, 'MAX')
  80449. };
  80450. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  80451. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  80452. }
  80453. else {
  80454. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  80455. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  80456. '(VALUE: ' + !!axisMeshInfo.value +
  80457. ', MIN: ' + !!axisMeshInfo.min +
  80458. ', MAX:' + !!axisMeshInfo.max +
  80459. ')');
  80460. }
  80461. }
  80462. // Pointing Ray
  80463. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  80464. if (!loadedMeshInfo.pointingPoseNode) {
  80465. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  80466. }
  80467. else {
  80468. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  80469. }
  80470. return loadedMeshInfo;
  80471. // Look through all children recursively. This will return null if no mesh exists with the given name.
  80472. function getChildByName(node, name) {
  80473. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  80474. }
  80475. // Look through only immediate children. This will return null if no mesh exists with the given name.
  80476. function getImmediateChildByName(node, name) {
  80477. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  80478. }
  80479. };
  80480. /**
  80481. * Gets the ray of the controller in the direction the controller is pointing
  80482. * @param length the length the resulting ray should be
  80483. * @returns a ray in the direction the controller is pointing
  80484. */
  80485. WindowsMotionController.prototype.getForwardRay = function (length) {
  80486. if (length === void 0) { length = 100; }
  80487. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  80488. return _super.prototype.getForwardRay.call(this, length);
  80489. }
  80490. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  80491. var origin = m.getTranslation();
  80492. var forward = new BABYLON.Vector3(0, 0, -1);
  80493. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  80494. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  80495. return new BABYLON.Ray(origin, direction, length);
  80496. };
  80497. /**
  80498. * Disposes of the controller
  80499. */
  80500. WindowsMotionController.prototype.dispose = function () {
  80501. _super.prototype.dispose.call(this);
  80502. this.onTrackpadChangedObservable.clear();
  80503. };
  80504. /**
  80505. * The base url used to load the left and right controller models
  80506. */
  80507. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  80508. /**
  80509. * The name of the left controller model file
  80510. */
  80511. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  80512. /**
  80513. * The name of the right controller model file
  80514. */
  80515. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  80516. /**
  80517. * The controller name prefix for this controller type
  80518. */
  80519. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  80520. /**
  80521. * The controller id pattern for this controller type
  80522. */
  80523. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  80524. return WindowsMotionController;
  80525. }(BABYLON.WebVRController));
  80526. BABYLON.WindowsMotionController = WindowsMotionController;
  80527. })(BABYLON || (BABYLON = {}));
  80528. //# sourceMappingURL=babylon.windowsMotionController.js.map
  80529. var BABYLON;
  80530. (function (BABYLON) {
  80531. /**
  80532. * Gear VR Controller
  80533. */
  80534. var GearVRController = /** @class */ (function (_super) {
  80535. __extends(GearVRController, _super);
  80536. /**
  80537. * Creates a new GearVRController from a gamepad
  80538. * @param vrGamepad the gamepad that the controller should be created from
  80539. */
  80540. function GearVRController(vrGamepad) {
  80541. var _this = _super.call(this, vrGamepad) || this;
  80542. _this._buttonIndexToObservableNameMap = [
  80543. 'onTrackpadChangedObservable',
  80544. 'onTriggerStateChangedObservable' // Trigger
  80545. ];
  80546. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  80547. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  80548. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  80549. _this._disableTrackPosition(_this._calculatedPosition);
  80550. return _this;
  80551. }
  80552. /**
  80553. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80554. * @param scene scene in which to add meshes
  80555. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80556. */
  80557. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80558. var _this = this;
  80559. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  80560. // Offset the controller so it will rotate around the users wrist
  80561. var mesh = new BABYLON.Mesh("", scene);
  80562. newMeshes[1].parent = mesh;
  80563. newMeshes[1].position.z = -0.15;
  80564. _this._defaultModel = mesh;
  80565. _this.attachToMesh(_this._defaultModel);
  80566. if (meshLoaded) {
  80567. meshLoaded(_this._defaultModel);
  80568. }
  80569. });
  80570. };
  80571. /**
  80572. * Called once for each button that changed state since the last frame
  80573. * @param buttonIdx Which button index changed
  80574. * @param state New state of the button
  80575. * @param changes Which properties on the state changed since last frame
  80576. */
  80577. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80578. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  80579. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  80580. // Only emit events for buttons that we know how to map from index to observable
  80581. var observable = this[observableName];
  80582. if (observable) {
  80583. observable.notifyObservers(state);
  80584. }
  80585. }
  80586. };
  80587. /**
  80588. * Base Url for the controller model.
  80589. */
  80590. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80591. /**
  80592. * File name for the controller model.
  80593. */
  80594. GearVRController.MODEL_FILENAME = 'generic.babylon';
  80595. /**
  80596. * Gamepad Id prefix used to identify this controller.
  80597. */
  80598. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  80599. return GearVRController;
  80600. }(BABYLON.WebVRController));
  80601. BABYLON.GearVRController = GearVRController;
  80602. })(BABYLON || (BABYLON = {}));
  80603. //# sourceMappingURL=babylon.gearVRController.js.map
  80604. var BABYLON;
  80605. (function (BABYLON) {
  80606. /**
  80607. * Google Daydream controller
  80608. */
  80609. var DaydreamController = /** @class */ (function (_super) {
  80610. __extends(DaydreamController, _super);
  80611. /**
  80612. * Creates a new DaydreamController from a gamepad
  80613. * @param vrGamepad the gamepad that the controller should be created from
  80614. */
  80615. function DaydreamController(vrGamepad) {
  80616. var _this = _super.call(this, vrGamepad) || this;
  80617. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  80618. return _this;
  80619. }
  80620. /**
  80621. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80622. * @param scene scene in which to add meshes
  80623. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80624. */
  80625. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80626. var _this = this;
  80627. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  80628. _this._defaultModel = newMeshes[1];
  80629. _this.attachToMesh(_this._defaultModel);
  80630. if (meshLoaded) {
  80631. meshLoaded(_this._defaultModel);
  80632. }
  80633. });
  80634. };
  80635. /**
  80636. * Called once for each button that changed state since the last frame
  80637. * @param buttonIdx Which button index changed
  80638. * @param state New state of the button
  80639. * @param changes Which properties on the state changed since last frame
  80640. */
  80641. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80642. // Daydream controller only has 1 GamepadButton (on the trackpad).
  80643. if (buttonIdx === 0) {
  80644. var observable = this.onTriggerStateChangedObservable;
  80645. if (observable) {
  80646. observable.notifyObservers(state);
  80647. }
  80648. }
  80649. else {
  80650. // If the app or home buttons are ever made available
  80651. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  80652. }
  80653. };
  80654. /**
  80655. * Base Url for the controller model.
  80656. */
  80657. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80658. /**
  80659. * File name for the controller model.
  80660. */
  80661. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  80662. /**
  80663. * Gamepad Id prefix used to identify Daydream Controller.
  80664. */
  80665. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  80666. return DaydreamController;
  80667. }(BABYLON.WebVRController));
  80668. BABYLON.DaydreamController = DaydreamController;
  80669. })(BABYLON || (BABYLON = {}));
  80670. //# sourceMappingURL=babylon.daydreamController.js.map
  80671. var BABYLON;
  80672. (function (BABYLON) {
  80673. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  80674. get: function () {
  80675. if (!this._gamepadManager) {
  80676. this._gamepadManager = new BABYLON.GamepadManager(this);
  80677. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  80678. if (!component) {
  80679. component = new GamepadSystemSceneComponent(this);
  80680. this._addComponent(component);
  80681. }
  80682. }
  80683. return this._gamepadManager;
  80684. },
  80685. enumerable: true,
  80686. configurable: true
  80687. });
  80688. /**
  80689. * Adds a gamepad to the free camera inputs manager
  80690. */
  80691. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  80692. this.add(new BABYLON.FreeCameraGamepadInput());
  80693. return this;
  80694. };
  80695. /**
  80696. * Adds a gamepad to the arc rotate camera inputs manager
  80697. */
  80698. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  80699. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  80700. return this;
  80701. };
  80702. /**
  80703. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  80704. */
  80705. var GamepadSystemSceneComponent = /** @class */ (function () {
  80706. /**
  80707. * Creates a new instance of the component for the given scene
  80708. * @param scene Defines the scene to register the component in
  80709. */
  80710. function GamepadSystemSceneComponent(scene) {
  80711. /**
  80712. * The component name helpfull to identify the component in the list of scene components.
  80713. */
  80714. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  80715. this.scene = scene;
  80716. }
  80717. /**
  80718. * Registers the component in a given scene
  80719. */
  80720. GamepadSystemSceneComponent.prototype.register = function () {
  80721. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  80722. };
  80723. /**
  80724. * Rebuilds the elements related to this component in case of
  80725. * context lost for instance.
  80726. */
  80727. GamepadSystemSceneComponent.prototype.rebuild = function () {
  80728. // Nothing to do for gamepads
  80729. };
  80730. /**
  80731. * Disposes the component and the associated ressources
  80732. */
  80733. GamepadSystemSceneComponent.prototype.dispose = function () {
  80734. var gamepadManager = this.scene._gamepadManager;
  80735. if (gamepadManager) {
  80736. gamepadManager.dispose();
  80737. this.scene._gamepadManager = null;
  80738. }
  80739. };
  80740. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  80741. var gamepadManager = this.scene._gamepadManager;
  80742. if (gamepadManager && gamepadManager._isMonitoring) {
  80743. gamepadManager._checkGamepadsStatus();
  80744. }
  80745. };
  80746. return GamepadSystemSceneComponent;
  80747. }());
  80748. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  80749. })(BABYLON || (BABYLON = {}));
  80750. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  80751. var BABYLON;
  80752. (function (BABYLON) {
  80753. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  80754. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  80755. });
  80756. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  80757. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  80758. });
  80759. /**
  80760. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  80761. * an arc rotate version arcFollowCamera are available.
  80762. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80763. */
  80764. var FollowCamera = /** @class */ (function (_super) {
  80765. __extends(FollowCamera, _super);
  80766. /**
  80767. * Instantiates the follow camera.
  80768. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80769. * @param name Define the name of the camera in the scene
  80770. * @param position Define the position of the camera
  80771. * @param scene Define the scene the camera belong to
  80772. * @param lockedTarget Define the target of the camera
  80773. */
  80774. function FollowCamera(name, position, scene, lockedTarget) {
  80775. if (lockedTarget === void 0) { lockedTarget = null; }
  80776. var _this = _super.call(this, name, position, scene) || this;
  80777. /**
  80778. * Distance the follow camera should follow an object at
  80779. */
  80780. _this.radius = 12;
  80781. /**
  80782. * Define a rotation offset between the camera and the object it follows
  80783. */
  80784. _this.rotationOffset = 0;
  80785. /**
  80786. * Define a height offset between the camera and the object it follows.
  80787. * It can help following an object from the top (like a car chaing a plane)
  80788. */
  80789. _this.heightOffset = 4;
  80790. /**
  80791. * Define how fast the camera can accelerate to follow it s target.
  80792. */
  80793. _this.cameraAcceleration = 0.05;
  80794. /**
  80795. * Define the speed limit of the camera following an object.
  80796. */
  80797. _this.maxCameraSpeed = 20;
  80798. _this.lockedTarget = lockedTarget;
  80799. return _this;
  80800. }
  80801. FollowCamera.prototype._follow = function (cameraTarget) {
  80802. if (!cameraTarget)
  80803. return;
  80804. var yRotation;
  80805. if (cameraTarget.rotationQuaternion) {
  80806. var rotMatrix = new BABYLON.Matrix();
  80807. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  80808. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  80809. }
  80810. else {
  80811. yRotation = cameraTarget.rotation.y;
  80812. }
  80813. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  80814. var targetPosition = cameraTarget.getAbsolutePosition();
  80815. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  80816. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  80817. var dx = targetX - this.position.x;
  80818. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  80819. var dz = (targetZ) - this.position.z;
  80820. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  80821. var vy = dy * this.cameraAcceleration;
  80822. var vz = dz * this.cameraAcceleration * 2;
  80823. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  80824. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80825. }
  80826. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  80827. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80828. }
  80829. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  80830. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80831. }
  80832. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  80833. this.setTarget(targetPosition);
  80834. };
  80835. /** @hidden */
  80836. FollowCamera.prototype._checkInputs = function () {
  80837. _super.prototype._checkInputs.call(this);
  80838. if (this.lockedTarget) {
  80839. this._follow(this.lockedTarget);
  80840. }
  80841. };
  80842. /**
  80843. * Gets the camera class name.
  80844. * @returns the class name
  80845. */
  80846. FollowCamera.prototype.getClassName = function () {
  80847. return "FollowCamera";
  80848. };
  80849. __decorate([
  80850. BABYLON.serialize()
  80851. ], FollowCamera.prototype, "radius", void 0);
  80852. __decorate([
  80853. BABYLON.serialize()
  80854. ], FollowCamera.prototype, "rotationOffset", void 0);
  80855. __decorate([
  80856. BABYLON.serialize()
  80857. ], FollowCamera.prototype, "heightOffset", void 0);
  80858. __decorate([
  80859. BABYLON.serialize()
  80860. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  80861. __decorate([
  80862. BABYLON.serialize()
  80863. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  80864. __decorate([
  80865. BABYLON.serializeAsMeshReference("lockedTargetId")
  80866. ], FollowCamera.prototype, "lockedTarget", void 0);
  80867. return FollowCamera;
  80868. }(BABYLON.TargetCamera));
  80869. BABYLON.FollowCamera = FollowCamera;
  80870. /**
  80871. * Arc Rotate version of the follow camera.
  80872. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  80873. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80874. */
  80875. var ArcFollowCamera = /** @class */ (function (_super) {
  80876. __extends(ArcFollowCamera, _super);
  80877. /**
  80878. * Instantiates a new ArcFollowCamera
  80879. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80880. * @param name Define the name of the camera
  80881. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  80882. * @param beta Define the rotation angle of the camera around the elevation axis
  80883. * @param radius Define the radius of the camera from its target point
  80884. * @param target Define the target of the camera
  80885. * @param scene Define the scene the camera belongs to
  80886. */
  80887. function ArcFollowCamera(name,
  80888. /** The longitudinal angle of the camera */
  80889. alpha,
  80890. /** The latitudinal angle of the camera */
  80891. beta,
  80892. /** The radius of the camera from its target */
  80893. radius,
  80894. /** Define the camera target (the messh it should follow) */
  80895. target, scene) {
  80896. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  80897. _this.alpha = alpha;
  80898. _this.beta = beta;
  80899. _this.radius = radius;
  80900. _this.target = target;
  80901. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  80902. _this._follow();
  80903. return _this;
  80904. }
  80905. ArcFollowCamera.prototype._follow = function () {
  80906. if (!this.target) {
  80907. return;
  80908. }
  80909. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  80910. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  80911. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  80912. var targetPosition = this.target.getAbsolutePosition();
  80913. this.position = targetPosition.add(this._cartesianCoordinates);
  80914. this.setTarget(targetPosition);
  80915. };
  80916. /** @hidden */
  80917. ArcFollowCamera.prototype._checkInputs = function () {
  80918. _super.prototype._checkInputs.call(this);
  80919. this._follow();
  80920. };
  80921. /**
  80922. * Returns the class name of the object.
  80923. * It is mostly used internally for serialization purposes.
  80924. */
  80925. ArcFollowCamera.prototype.getClassName = function () {
  80926. return "ArcFollowCamera";
  80927. };
  80928. return ArcFollowCamera;
  80929. }(BABYLON.TargetCamera));
  80930. BABYLON.ArcFollowCamera = ArcFollowCamera;
  80931. })(BABYLON || (BABYLON = {}));
  80932. //# sourceMappingURL=babylon.followCamera.js.map
  80933. var BABYLON;
  80934. (function (BABYLON) {
  80935. /**
  80936. * 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,
  80937. * which still works and will still be found in many Playgrounds.
  80938. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80939. */
  80940. var UniversalCamera = /** @class */ (function (_super) {
  80941. __extends(UniversalCamera, _super);
  80942. /**
  80943. * 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,
  80944. * which still works and will still be found in many Playgrounds.
  80945. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80946. * @param name Define the name of the camera in the scene
  80947. * @param position Define the start position of the camera in the scene
  80948. * @param scene Define the scene the camera belongs to
  80949. */
  80950. function UniversalCamera(name, position, scene) {
  80951. var _this = _super.call(this, name, position, scene) || this;
  80952. _this.inputs.addGamepad();
  80953. return _this;
  80954. }
  80955. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  80956. /**
  80957. * Defines the gamepad rotation sensiblity.
  80958. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80959. */
  80960. get: function () {
  80961. var gamepad = this.inputs.attached["gamepad"];
  80962. if (gamepad)
  80963. return gamepad.gamepadAngularSensibility;
  80964. return 0;
  80965. },
  80966. set: function (value) {
  80967. var gamepad = this.inputs.attached["gamepad"];
  80968. if (gamepad)
  80969. gamepad.gamepadAngularSensibility = value;
  80970. },
  80971. enumerable: true,
  80972. configurable: true
  80973. });
  80974. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  80975. /**
  80976. * Defines the gamepad move sensiblity.
  80977. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80978. */
  80979. get: function () {
  80980. var gamepad = this.inputs.attached["gamepad"];
  80981. if (gamepad)
  80982. return gamepad.gamepadMoveSensibility;
  80983. return 0;
  80984. },
  80985. set: function (value) {
  80986. var gamepad = this.inputs.attached["gamepad"];
  80987. if (gamepad)
  80988. gamepad.gamepadMoveSensibility = value;
  80989. },
  80990. enumerable: true,
  80991. configurable: true
  80992. });
  80993. /**
  80994. * Gets the current object class name.
  80995. * @return the class name
  80996. */
  80997. UniversalCamera.prototype.getClassName = function () {
  80998. return "UniversalCamera";
  80999. };
  81000. return UniversalCamera;
  81001. }(BABYLON.TouchCamera));
  81002. BABYLON.UniversalCamera = UniversalCamera;
  81003. })(BABYLON || (BABYLON = {}));
  81004. //# sourceMappingURL=babylon.universalCamera.js.map
  81005. var BABYLON;
  81006. (function (BABYLON) {
  81007. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  81008. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  81009. });
  81010. /**
  81011. * This represents a FPS type of camera. This is only here for back compat purpose.
  81012. * Please use the UniversalCamera instead as both are identical.
  81013. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81014. */
  81015. var GamepadCamera = /** @class */ (function (_super) {
  81016. __extends(GamepadCamera, _super);
  81017. /**
  81018. * Instantiates a new Gamepad Camera
  81019. * This represents a FPS type of camera. This is only here for back compat purpose.
  81020. * Please use the UniversalCamera instead as both are identical.
  81021. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81022. * @param name Define the name of the camera in the scene
  81023. * @param position Define the start position of the camera in the scene
  81024. * @param scene Define the scene the camera belongs to
  81025. */
  81026. function GamepadCamera(name, position, scene) {
  81027. return _super.call(this, name, position, scene) || this;
  81028. }
  81029. /**
  81030. * Gets the current object class name.
  81031. * @return the class name
  81032. */
  81033. GamepadCamera.prototype.getClassName = function () {
  81034. return "GamepadCamera";
  81035. };
  81036. return GamepadCamera;
  81037. }(BABYLON.UniversalCamera));
  81038. BABYLON.GamepadCamera = GamepadCamera;
  81039. })(BABYLON || (BABYLON = {}));
  81040. //# sourceMappingURL=babylon.gamepadCamera.js.map
  81041. var BABYLON;
  81042. (function (BABYLON) {
  81043. var PostProcessRenderPipelineManager = /** @class */ (function () {
  81044. function PostProcessRenderPipelineManager() {
  81045. this._renderPipelines = {};
  81046. }
  81047. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  81048. this._renderPipelines[renderPipeline._name] = renderPipeline;
  81049. };
  81050. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  81051. if (unique === void 0) { unique = false; }
  81052. var renderPipeline = this._renderPipelines[renderPipelineName];
  81053. if (!renderPipeline) {
  81054. return;
  81055. }
  81056. renderPipeline._attachCameras(cameras, unique);
  81057. };
  81058. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  81059. var renderPipeline = this._renderPipelines[renderPipelineName];
  81060. if (!renderPipeline) {
  81061. return;
  81062. }
  81063. renderPipeline._detachCameras(cameras);
  81064. };
  81065. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81066. var renderPipeline = this._renderPipelines[renderPipelineName];
  81067. if (!renderPipeline) {
  81068. return;
  81069. }
  81070. renderPipeline._enableEffect(renderEffectName, cameras);
  81071. };
  81072. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81073. var renderPipeline = this._renderPipelines[renderPipelineName];
  81074. if (!renderPipeline) {
  81075. return;
  81076. }
  81077. renderPipeline._disableEffect(renderEffectName, cameras);
  81078. };
  81079. PostProcessRenderPipelineManager.prototype.update = function () {
  81080. for (var renderPipelineName in this._renderPipelines) {
  81081. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81082. var pipeline = this._renderPipelines[renderPipelineName];
  81083. if (!pipeline.isSupported) {
  81084. pipeline.dispose();
  81085. delete this._renderPipelines[renderPipelineName];
  81086. }
  81087. else {
  81088. pipeline._update();
  81089. }
  81090. }
  81091. }
  81092. };
  81093. /** @hidden */
  81094. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  81095. for (var renderPipelineName in this._renderPipelines) {
  81096. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81097. var pipeline = this._renderPipelines[renderPipelineName];
  81098. pipeline._rebuild();
  81099. }
  81100. }
  81101. };
  81102. PostProcessRenderPipelineManager.prototype.dispose = function () {
  81103. for (var renderPipelineName in this._renderPipelines) {
  81104. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81105. var pipeline = this._renderPipelines[renderPipelineName];
  81106. pipeline.dispose();
  81107. }
  81108. }
  81109. };
  81110. return PostProcessRenderPipelineManager;
  81111. }());
  81112. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  81113. })(BABYLON || (BABYLON = {}));
  81114. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  81115. var BABYLON;
  81116. (function (BABYLON) {
  81117. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  81118. get: function () {
  81119. if (!this._postProcessRenderPipelineManager) {
  81120. // Register the G Buffer component to the scene.
  81121. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  81122. if (!component) {
  81123. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  81124. this._addComponent(component);
  81125. }
  81126. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  81127. }
  81128. return this._postProcessRenderPipelineManager;
  81129. },
  81130. enumerable: true,
  81131. configurable: true
  81132. });
  81133. /**
  81134. * Defines the Render Pipeline scene component responsible to rendering pipelines
  81135. */
  81136. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  81137. /**
  81138. * Creates a new instance of the component for the given scene
  81139. * @param scene Defines the scene to register the component in
  81140. */
  81141. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  81142. /**
  81143. * The component name helpfull to identify the component in the list of scene components.
  81144. */
  81145. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  81146. this.scene = scene;
  81147. }
  81148. /**
  81149. * Registers the component in a given scene
  81150. */
  81151. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  81152. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  81153. };
  81154. /**
  81155. * Rebuilds the elements related to this component in case of
  81156. * context lost for instance.
  81157. */
  81158. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  81159. if (this.scene._postProcessRenderPipelineManager) {
  81160. this.scene._postProcessRenderPipelineManager._rebuild();
  81161. }
  81162. };
  81163. /**
  81164. * Disposes the component and the associated ressources
  81165. */
  81166. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  81167. if (this.scene._postProcessRenderPipelineManager) {
  81168. this.scene._postProcessRenderPipelineManager.dispose();
  81169. }
  81170. };
  81171. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81172. if (this.scene._postProcessRenderPipelineManager) {
  81173. this.scene._postProcessRenderPipelineManager.update();
  81174. }
  81175. };
  81176. return PostProcessRenderPipelineManagerSceneComponent;
  81177. }());
  81178. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  81179. })(BABYLON || (BABYLON = {}));
  81180. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  81181. var BABYLON;
  81182. (function (BABYLON) {
  81183. /**
  81184. * This represents a set of one or more post processes in Babylon.
  81185. * A post process can be used to apply a shader to a texture after it is rendered.
  81186. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81187. */
  81188. var PostProcessRenderEffect = /** @class */ (function () {
  81189. /**
  81190. * Instantiates a post process render effect.
  81191. * A post process can be used to apply a shader to a texture after it is rendered.
  81192. * @param engine The engine the effect is tied to
  81193. * @param name The name of the effect
  81194. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  81195. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  81196. */
  81197. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  81198. this._name = name;
  81199. this._singleInstance = singleInstance || true;
  81200. this._getPostProcesses = getPostProcesses;
  81201. this._cameras = {};
  81202. this._indicesForCamera = {};
  81203. this._postProcesses = {};
  81204. }
  81205. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  81206. /**
  81207. * Checks if all the post processes in the effect are supported.
  81208. */
  81209. get: function () {
  81210. for (var index in this._postProcesses) {
  81211. if (this._postProcesses.hasOwnProperty(index)) {
  81212. var pps = this._postProcesses[index];
  81213. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  81214. if (!pps[ppIndex].isSupported) {
  81215. return false;
  81216. }
  81217. }
  81218. }
  81219. }
  81220. return true;
  81221. },
  81222. enumerable: true,
  81223. configurable: true
  81224. });
  81225. /**
  81226. * Updates the current state of the effect
  81227. * @hidden
  81228. */
  81229. PostProcessRenderEffect.prototype._update = function () {
  81230. };
  81231. /**
  81232. * Attaches the effect on cameras
  81233. * @param cameras The camera to attach to.
  81234. * @hidden
  81235. */
  81236. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  81237. var _this = this;
  81238. var cameraKey;
  81239. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81240. if (!cams) {
  81241. return;
  81242. }
  81243. for (var i = 0; i < cams.length; i++) {
  81244. var camera = cams[i];
  81245. var cameraName = camera.name;
  81246. if (this._singleInstance) {
  81247. cameraKey = 0;
  81248. }
  81249. else {
  81250. cameraKey = cameraName;
  81251. }
  81252. if (!this._postProcesses[cameraKey]) {
  81253. var postProcess = this._getPostProcesses();
  81254. if (postProcess) {
  81255. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  81256. }
  81257. }
  81258. if (!this._indicesForCamera[cameraName]) {
  81259. this._indicesForCamera[cameraName] = [];
  81260. }
  81261. this._postProcesses[cameraKey].forEach(function (postProcess) {
  81262. var index = camera.attachPostProcess(postProcess);
  81263. _this._indicesForCamera[cameraName].push(index);
  81264. });
  81265. if (!this._cameras[cameraName]) {
  81266. this._cameras[cameraName] = camera;
  81267. }
  81268. }
  81269. };
  81270. /**
  81271. * Detatches the effect on cameras
  81272. * @param cameras The camera to detatch from.
  81273. * @hidden
  81274. */
  81275. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  81276. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81277. if (!cams) {
  81278. return;
  81279. }
  81280. for (var i = 0; i < cams.length; i++) {
  81281. var camera = cams[i];
  81282. var cameraName = camera.name;
  81283. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81284. camera.detachPostProcess(postProcess);
  81285. });
  81286. if (this._cameras[cameraName]) {
  81287. //this._indicesForCamera.splice(index, 1);
  81288. this._cameras[cameraName] = null;
  81289. }
  81290. }
  81291. };
  81292. /**
  81293. * Enables the effect on given cameras
  81294. * @param cameras The camera to enable.
  81295. * @hidden
  81296. */
  81297. PostProcessRenderEffect.prototype._enable = function (cameras) {
  81298. var _this = this;
  81299. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81300. if (!cams) {
  81301. return;
  81302. }
  81303. for (var i = 0; i < cams.length; i++) {
  81304. var camera = cams[i];
  81305. var cameraName = camera.name;
  81306. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  81307. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  81308. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81309. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  81310. });
  81311. }
  81312. }
  81313. }
  81314. };
  81315. /**
  81316. * Disables the effect on the given cameras
  81317. * @param cameras The camera to disable.
  81318. * @hidden
  81319. */
  81320. PostProcessRenderEffect.prototype._disable = function (cameras) {
  81321. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81322. if (!cams) {
  81323. return;
  81324. }
  81325. for (var i = 0; i < cams.length; i++) {
  81326. var camera = cams[i];
  81327. var cameraName = camera.name;
  81328. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81329. camera.detachPostProcess(postProcess);
  81330. });
  81331. }
  81332. };
  81333. /**
  81334. * Gets a list of the post processes contained in the effect.
  81335. * @param camera The camera to get the post processes on.
  81336. * @returns The list of the post processes in the effect.
  81337. */
  81338. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  81339. if (this._singleInstance) {
  81340. return this._postProcesses[0];
  81341. }
  81342. else {
  81343. if (!camera) {
  81344. return null;
  81345. }
  81346. return this._postProcesses[camera.name];
  81347. }
  81348. };
  81349. return PostProcessRenderEffect;
  81350. }());
  81351. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  81352. })(BABYLON || (BABYLON = {}));
  81353. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  81354. var BABYLON;
  81355. (function (BABYLON) {
  81356. var PostProcessRenderPipeline = /** @class */ (function () {
  81357. function PostProcessRenderPipeline(engine, name) {
  81358. this.engine = engine;
  81359. this._name = name;
  81360. this._renderEffects = {};
  81361. this._renderEffectsForIsolatedPass = new Array();
  81362. this._cameras = [];
  81363. }
  81364. PostProcessRenderPipeline.prototype.getClassName = function () {
  81365. return "PostProcessRenderPipeline";
  81366. };
  81367. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  81368. get: function () {
  81369. for (var renderEffectName in this._renderEffects) {
  81370. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81371. if (!this._renderEffects[renderEffectName].isSupported) {
  81372. return false;
  81373. }
  81374. }
  81375. }
  81376. return true;
  81377. },
  81378. enumerable: true,
  81379. configurable: true
  81380. });
  81381. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  81382. this._renderEffects[renderEffect._name] = renderEffect;
  81383. };
  81384. // private
  81385. /** @hidden */
  81386. PostProcessRenderPipeline.prototype._rebuild = function () {
  81387. };
  81388. /** @hidden */
  81389. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  81390. var renderEffects = this._renderEffects[renderEffectName];
  81391. if (!renderEffects) {
  81392. return;
  81393. }
  81394. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  81395. };
  81396. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  81397. var renderEffects = this._renderEffects[renderEffectName];
  81398. if (!renderEffects) {
  81399. return;
  81400. }
  81401. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  81402. };
  81403. /** @hidden */
  81404. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  81405. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81406. if (!cams) {
  81407. return;
  81408. }
  81409. var indicesToDelete = [];
  81410. var i;
  81411. for (i = 0; i < cams.length; i++) {
  81412. var camera = cams[i];
  81413. var cameraName = camera.name;
  81414. if (this._cameras.indexOf(camera) === -1) {
  81415. this._cameras[cameraName] = camera;
  81416. }
  81417. else if (unique) {
  81418. indicesToDelete.push(i);
  81419. }
  81420. }
  81421. for (i = 0; i < indicesToDelete.length; i++) {
  81422. cameras.splice(indicesToDelete[i], 1);
  81423. }
  81424. for (var renderEffectName in this._renderEffects) {
  81425. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81426. this._renderEffects[renderEffectName]._attachCameras(cams);
  81427. }
  81428. }
  81429. };
  81430. /** @hidden */
  81431. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  81432. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81433. if (!cams) {
  81434. return;
  81435. }
  81436. for (var renderEffectName in this._renderEffects) {
  81437. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81438. this._renderEffects[renderEffectName]._detachCameras(cams);
  81439. }
  81440. }
  81441. for (var i = 0; i < cams.length; i++) {
  81442. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  81443. }
  81444. };
  81445. /** @hidden */
  81446. PostProcessRenderPipeline.prototype._update = function () {
  81447. for (var renderEffectName in this._renderEffects) {
  81448. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81449. this._renderEffects[renderEffectName]._update();
  81450. }
  81451. }
  81452. for (var i = 0; i < this._cameras.length; i++) {
  81453. var cameraName = this._cameras[i].name;
  81454. if (this._renderEffectsForIsolatedPass[cameraName]) {
  81455. this._renderEffectsForIsolatedPass[cameraName]._update();
  81456. }
  81457. }
  81458. };
  81459. /** @hidden */
  81460. PostProcessRenderPipeline.prototype._reset = function () {
  81461. this._renderEffects = {};
  81462. this._renderEffectsForIsolatedPass = new Array();
  81463. };
  81464. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  81465. // 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)
  81466. var effectKeys = Object.keys(this._renderEffects);
  81467. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  81468. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  81469. if (postProcesses) {
  81470. postProcesses[0].samples = sampleCount;
  81471. return true;
  81472. }
  81473. }
  81474. return false;
  81475. };
  81476. PostProcessRenderPipeline.prototype.dispose = function () {
  81477. // Must be implemented by children
  81478. };
  81479. __decorate([
  81480. BABYLON.serialize()
  81481. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  81482. return PostProcessRenderPipeline;
  81483. }());
  81484. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  81485. })(BABYLON || (BABYLON = {}));
  81486. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  81487. var BABYLON;
  81488. (function (BABYLON) {
  81489. /**
  81490. * This represents a depth renderer in Babylon.
  81491. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  81492. */
  81493. var DepthRenderer = /** @class */ (function () {
  81494. /**
  81495. * Instantiates a depth renderer
  81496. * @param scene The scene the renderer belongs to
  81497. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  81498. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  81499. */
  81500. function DepthRenderer(scene, type, camera) {
  81501. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  81502. if (camera === void 0) { camera = null; }
  81503. var _this = this;
  81504. /**
  81505. * Specifiess that the depth renderer will only be used within
  81506. * the camera it is created for.
  81507. * This can help forcing its rendering during the camera processing.
  81508. */
  81509. this.useOnlyInActiveCamera = false;
  81510. this._scene = scene;
  81511. // Register the G Buffer component to the scene.
  81512. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  81513. if (!component) {
  81514. component = new BABYLON.DepthRendererSceneComponent(scene);
  81515. scene._addComponent(component);
  81516. }
  81517. this._camera = camera;
  81518. var engine = scene.getEngine();
  81519. // Render target
  81520. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  81521. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81522. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81523. this._depthMap.refreshRate = 1;
  81524. this._depthMap.renderParticles = false;
  81525. this._depthMap.renderList = null;
  81526. // Camera to get depth map from to support multiple concurrent cameras
  81527. this._depthMap.activeCamera = this._camera;
  81528. this._depthMap.ignoreCameraViewport = true;
  81529. this._depthMap.useCameraPostProcesses = false;
  81530. // set default depth value to 1.0 (far away)
  81531. this._depthMap.onClearObservable.add(function (engine) {
  81532. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  81533. });
  81534. // Custom render function
  81535. var renderSubMesh = function (subMesh) {
  81536. var mesh = subMesh.getRenderingMesh();
  81537. var scene = _this._scene;
  81538. var engine = scene.getEngine();
  81539. var material = subMesh.getMaterial();
  81540. if (!material) {
  81541. return;
  81542. }
  81543. // Culling and reverse (right handed system)
  81544. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  81545. // Managing instances
  81546. var batch = mesh._getInstancesRenderList(subMesh._id);
  81547. if (batch.mustReturn) {
  81548. return;
  81549. }
  81550. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81551. var camera = _this._camera || scene.activeCamera;
  81552. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  81553. engine.enableEffect(_this._effect);
  81554. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  81555. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81556. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  81557. // Alpha test
  81558. if (material && material.needAlphaTesting()) {
  81559. var alphaTexture = material.getAlphaTestTexture();
  81560. if (alphaTexture) {
  81561. _this._effect.setTexture("diffuseSampler", alphaTexture);
  81562. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81563. }
  81564. }
  81565. // Bones
  81566. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81567. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81568. }
  81569. // Draw
  81570. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  81571. }
  81572. };
  81573. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81574. var index;
  81575. if (depthOnlySubMeshes.length) {
  81576. engine.setColorWrite(false);
  81577. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81578. renderSubMesh(depthOnlySubMeshes.data[index]);
  81579. }
  81580. engine.setColorWrite(true);
  81581. }
  81582. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81583. renderSubMesh(opaqueSubMeshes.data[index]);
  81584. }
  81585. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81586. renderSubMesh(alphaTestSubMeshes.data[index]);
  81587. }
  81588. };
  81589. }
  81590. /**
  81591. * Creates the depth rendering effect and checks if the effect is ready.
  81592. * @param subMesh The submesh to be used to render the depth map of
  81593. * @param useInstances If multiple world instances should be used
  81594. * @returns if the depth renderer is ready to render the depth map
  81595. */
  81596. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  81597. var material = subMesh.getMaterial();
  81598. if (material.disableDepthWrite) {
  81599. return false;
  81600. }
  81601. var defines = [];
  81602. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81603. var mesh = subMesh.getMesh();
  81604. // Alpha test
  81605. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  81606. defines.push("#define ALPHATEST");
  81607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81608. attribs.push(BABYLON.VertexBuffer.UVKind);
  81609. defines.push("#define UV1");
  81610. }
  81611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81612. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81613. defines.push("#define UV2");
  81614. }
  81615. }
  81616. // Bones
  81617. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81620. if (mesh.numBoneInfluencers > 4) {
  81621. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81622. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81623. }
  81624. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81625. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81626. }
  81627. else {
  81628. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81629. }
  81630. // Instances
  81631. if (useInstances) {
  81632. defines.push("#define INSTANCES");
  81633. attribs.push("world0");
  81634. attribs.push("world1");
  81635. attribs.push("world2");
  81636. attribs.push("world3");
  81637. }
  81638. // Get correct effect
  81639. var join = defines.join("\n");
  81640. if (this._cachedDefines !== join) {
  81641. this._cachedDefines = join;
  81642. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  81643. }
  81644. return this._effect.isReady();
  81645. };
  81646. /**
  81647. * Gets the texture which the depth map will be written to.
  81648. * @returns The depth map texture
  81649. */
  81650. DepthRenderer.prototype.getDepthMap = function () {
  81651. return this._depthMap;
  81652. };
  81653. /**
  81654. * Disposes of the depth renderer.
  81655. */
  81656. DepthRenderer.prototype.dispose = function () {
  81657. this._depthMap.dispose();
  81658. };
  81659. return DepthRenderer;
  81660. }());
  81661. BABYLON.DepthRenderer = DepthRenderer;
  81662. })(BABYLON || (BABYLON = {}));
  81663. //# sourceMappingURL=babylon.depthRenderer.js.map
  81664. var BABYLON;
  81665. (function (BABYLON) {
  81666. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  81667. camera = camera || this.activeCamera;
  81668. if (!camera) {
  81669. throw "No camera available to enable depth renderer";
  81670. }
  81671. if (!this._depthRenderer) {
  81672. this._depthRenderer = {};
  81673. }
  81674. if (!this._depthRenderer[camera.id]) {
  81675. var textureType = 0;
  81676. if (this.getEngine().getCaps().textureHalfFloatRender) {
  81677. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81678. }
  81679. else if (this.getEngine().getCaps().textureFloatRender) {
  81680. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81681. }
  81682. else {
  81683. throw "Depth renderer does not support int texture type";
  81684. }
  81685. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  81686. }
  81687. return this._depthRenderer[camera.id];
  81688. };
  81689. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  81690. camera = camera || this.activeCamera;
  81691. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  81692. return;
  81693. }
  81694. this._depthRenderer[camera.id].dispose();
  81695. delete this._depthRenderer[camera.id];
  81696. };
  81697. /**
  81698. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  81699. * in several rendering techniques.
  81700. */
  81701. var DepthRendererSceneComponent = /** @class */ (function () {
  81702. /**
  81703. * Creates a new instance of the component for the given scene
  81704. * @param scene Defines the scene to register the component in
  81705. */
  81706. function DepthRendererSceneComponent(scene) {
  81707. /**
  81708. * The component name helpfull to identify the component in the list of scene components.
  81709. */
  81710. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  81711. this.scene = scene;
  81712. }
  81713. /**
  81714. * Registers the component in a given scene
  81715. */
  81716. DepthRendererSceneComponent.prototype.register = function () {
  81717. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  81718. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  81719. };
  81720. /**
  81721. * Rebuilds the elements related to this component in case of
  81722. * context lost for instance.
  81723. */
  81724. DepthRendererSceneComponent.prototype.rebuild = function () {
  81725. // Nothing to do for this component
  81726. };
  81727. /**
  81728. * Disposes the component and the associated ressources
  81729. */
  81730. DepthRendererSceneComponent.prototype.dispose = function () {
  81731. for (var key in this.scene._depthRenderer) {
  81732. this.scene._depthRenderer[key].dispose();
  81733. }
  81734. };
  81735. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81736. if (this.scene._depthRenderer) {
  81737. for (var key in this.scene._depthRenderer) {
  81738. var depthRenderer = this.scene._depthRenderer[key];
  81739. if (!depthRenderer.useOnlyInActiveCamera) {
  81740. renderTargets.push(depthRenderer.getDepthMap());
  81741. }
  81742. }
  81743. }
  81744. };
  81745. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  81746. if (this.scene._depthRenderer) {
  81747. for (var key in this.scene._depthRenderer) {
  81748. var depthRenderer = this.scene._depthRenderer[key];
  81749. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  81750. renderTargets.push(depthRenderer.getDepthMap());
  81751. }
  81752. }
  81753. }
  81754. };
  81755. return DepthRendererSceneComponent;
  81756. }());
  81757. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  81758. })(BABYLON || (BABYLON = {}));
  81759. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  81760. var BABYLON;
  81761. (function (BABYLON) {
  81762. /**
  81763. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  81764. */
  81765. var GeometryBufferRenderer = /** @class */ (function () {
  81766. /**
  81767. * Creates a new G Buffer for the scene
  81768. * @param scene The scene the buffer belongs to
  81769. * @param ratio How big is the buffer related to the main canvas.
  81770. */
  81771. function GeometryBufferRenderer(scene, ratio) {
  81772. if (ratio === void 0) { ratio = 1; }
  81773. this._enablePosition = false;
  81774. this._scene = scene;
  81775. this._ratio = ratio;
  81776. // Register the G Buffer component to the scene.
  81777. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  81778. if (!component) {
  81779. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  81780. scene._addComponent(component);
  81781. }
  81782. // Render target
  81783. this._createRenderTargets();
  81784. }
  81785. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  81786. /**
  81787. * Set the render list (meshes to be rendered) used in the G buffer.
  81788. */
  81789. set: function (meshes) {
  81790. this._multiRenderTarget.renderList = meshes;
  81791. },
  81792. enumerable: true,
  81793. configurable: true
  81794. });
  81795. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  81796. /**
  81797. * Gets wether or not G buffer are supported by the running hardware.
  81798. * This requires draw buffer supports
  81799. */
  81800. get: function () {
  81801. return this._multiRenderTarget.isSupported;
  81802. },
  81803. enumerable: true,
  81804. configurable: true
  81805. });
  81806. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  81807. /**
  81808. * Gets wether or not position are enabled for the G buffer.
  81809. */
  81810. get: function () {
  81811. return this._enablePosition;
  81812. },
  81813. /**
  81814. * Sets wether or not position are enabled for the G buffer.
  81815. */
  81816. set: function (enable) {
  81817. this._enablePosition = enable;
  81818. this.dispose();
  81819. this._createRenderTargets();
  81820. },
  81821. enumerable: true,
  81822. configurable: true
  81823. });
  81824. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  81825. /**
  81826. * Gets the scene associated with the buffer.
  81827. */
  81828. get: function () {
  81829. return this._scene;
  81830. },
  81831. enumerable: true,
  81832. configurable: true
  81833. });
  81834. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  81835. /**
  81836. * Gets the ratio used by the buffer during its creation.
  81837. * How big is the buffer related to the main canvas.
  81838. */
  81839. get: function () {
  81840. return this._ratio;
  81841. },
  81842. enumerable: true,
  81843. configurable: true
  81844. });
  81845. /**
  81846. * Checks wether everything is ready to render a submesh to the G buffer.
  81847. * @param subMesh the submesh to check readiness for
  81848. * @param useInstances is the mesh drawn using instance or not
  81849. * @returns true if ready otherwise false
  81850. */
  81851. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  81852. var material = subMesh.getMaterial();
  81853. if (material && material.disableDepthWrite) {
  81854. return false;
  81855. }
  81856. var defines = [];
  81857. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81858. var mesh = subMesh.getMesh();
  81859. // Alpha test
  81860. if (material && material.needAlphaTesting()) {
  81861. defines.push("#define ALPHATEST");
  81862. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81863. attribs.push(BABYLON.VertexBuffer.UVKind);
  81864. defines.push("#define UV1");
  81865. }
  81866. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81867. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81868. defines.push("#define UV2");
  81869. }
  81870. }
  81871. // Buffers
  81872. if (this._enablePosition) {
  81873. defines.push("#define POSITION");
  81874. }
  81875. // Bones
  81876. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81877. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81878. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81879. if (mesh.numBoneInfluencers > 4) {
  81880. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81881. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81882. }
  81883. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81884. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81885. }
  81886. else {
  81887. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81888. }
  81889. // Instances
  81890. if (useInstances) {
  81891. defines.push("#define INSTANCES");
  81892. attribs.push("world0");
  81893. attribs.push("world1");
  81894. attribs.push("world2");
  81895. attribs.push("world3");
  81896. }
  81897. // Get correct effect
  81898. var join = defines.join("\n");
  81899. if (this._cachedDefines !== join) {
  81900. this._cachedDefines = join;
  81901. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  81902. }
  81903. return this._effect.isReady();
  81904. };
  81905. /**
  81906. * Gets the current underlying G Buffer.
  81907. * @returns the buffer
  81908. */
  81909. GeometryBufferRenderer.prototype.getGBuffer = function () {
  81910. return this._multiRenderTarget;
  81911. };
  81912. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  81913. /**
  81914. * Gets the number of samples used to render the buffer (anti aliasing).
  81915. */
  81916. get: function () {
  81917. return this._multiRenderTarget.samples;
  81918. },
  81919. /**
  81920. * Sets the number of samples used to render the buffer (anti aliasing).
  81921. */
  81922. set: function (value) {
  81923. this._multiRenderTarget.samples = value;
  81924. },
  81925. enumerable: true,
  81926. configurable: true
  81927. });
  81928. /**
  81929. * Disposes the renderer and frees up associated resources.
  81930. */
  81931. GeometryBufferRenderer.prototype.dispose = function () {
  81932. this.getGBuffer().dispose();
  81933. };
  81934. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  81935. var _this = this;
  81936. var engine = this._scene.getEngine();
  81937. var count = this._enablePosition ? 3 : 2;
  81938. 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 });
  81939. if (!this.isSupported) {
  81940. return;
  81941. }
  81942. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81943. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81944. this._multiRenderTarget.refreshRate = 1;
  81945. this._multiRenderTarget.renderParticles = false;
  81946. this._multiRenderTarget.renderList = null;
  81947. // set default depth value to 1.0 (far away)
  81948. this._multiRenderTarget.onClearObservable.add(function (engine) {
  81949. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  81950. });
  81951. // Custom render function
  81952. var renderSubMesh = function (subMesh) {
  81953. var mesh = subMesh.getRenderingMesh();
  81954. var scene = _this._scene;
  81955. var engine = scene.getEngine();
  81956. var material = subMesh.getMaterial();
  81957. if (!material) {
  81958. return;
  81959. }
  81960. // Culling
  81961. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  81962. // Managing instances
  81963. var batch = mesh._getInstancesRenderList(subMesh._id);
  81964. if (batch.mustReturn) {
  81965. return;
  81966. }
  81967. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81968. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  81969. engine.enableEffect(_this._effect);
  81970. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  81971. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81972. _this._effect.setMatrix("view", scene.getViewMatrix());
  81973. // Alpha test
  81974. if (material && material.needAlphaTesting()) {
  81975. var alphaTexture = material.getAlphaTestTexture();
  81976. if (alphaTexture) {
  81977. _this._effect.setTexture("diffuseSampler", alphaTexture);
  81978. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81979. }
  81980. }
  81981. // Bones
  81982. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81983. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81984. }
  81985. // Draw
  81986. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  81987. }
  81988. };
  81989. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81990. var index;
  81991. if (depthOnlySubMeshes.length) {
  81992. engine.setColorWrite(false);
  81993. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81994. renderSubMesh(depthOnlySubMeshes.data[index]);
  81995. }
  81996. engine.setColorWrite(true);
  81997. }
  81998. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81999. renderSubMesh(opaqueSubMeshes.data[index]);
  82000. }
  82001. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82002. renderSubMesh(alphaTestSubMeshes.data[index]);
  82003. }
  82004. };
  82005. };
  82006. return GeometryBufferRenderer;
  82007. }());
  82008. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  82009. })(BABYLON || (BABYLON = {}));
  82010. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  82011. var BABYLON;
  82012. (function (BABYLON) {
  82013. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  82014. get: function () {
  82015. this._geometryBufferRenderer;
  82016. },
  82017. set: function (value) {
  82018. if (value && value.isSupported) {
  82019. this._geometryBufferRenderer = value;
  82020. }
  82021. ;
  82022. },
  82023. enumerable: true,
  82024. configurable: true
  82025. });
  82026. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  82027. if (ratio === void 0) { ratio = 1; }
  82028. if (this._geometryBufferRenderer) {
  82029. return this._geometryBufferRenderer;
  82030. }
  82031. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  82032. if (!this._geometryBufferRenderer.isSupported) {
  82033. this._geometryBufferRenderer = null;
  82034. }
  82035. return this._geometryBufferRenderer;
  82036. };
  82037. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  82038. if (!this._geometryBufferRenderer) {
  82039. return;
  82040. }
  82041. this._geometryBufferRenderer.dispose();
  82042. this._geometryBufferRenderer = null;
  82043. };
  82044. /**
  82045. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  82046. * in several rendering techniques.
  82047. */
  82048. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  82049. /**
  82050. * Creates a new instance of the component for the given scene
  82051. * @param scene Defines the scene to register the component in
  82052. */
  82053. function GeometryBufferRendererSceneComponent(scene) {
  82054. /**
  82055. * The component name helpful to identify the component in the list of scene components.
  82056. */
  82057. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  82058. this.scene = scene;
  82059. }
  82060. /**
  82061. * Registers the component in a given scene
  82062. */
  82063. GeometryBufferRendererSceneComponent.prototype.register = function () {
  82064. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  82065. };
  82066. /**
  82067. * Rebuilds the elements related to this component in case of
  82068. * context lost for instance.
  82069. */
  82070. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  82071. // Nothing to do for this component
  82072. };
  82073. /**
  82074. * Disposes the component and the associated ressources
  82075. */
  82076. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  82077. // Nothing to do for this component
  82078. };
  82079. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82080. if (this.scene._geometryBufferRenderer) {
  82081. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  82082. }
  82083. };
  82084. return GeometryBufferRendererSceneComponent;
  82085. }());
  82086. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  82087. })(BABYLON || (BABYLON = {}));
  82088. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  82089. var BABYLON;
  82090. (function (BABYLON) {
  82091. var SSAORenderingPipeline = /** @class */ (function (_super) {
  82092. __extends(SSAORenderingPipeline, _super);
  82093. /**
  82094. * @constructor
  82095. * @param {string} name - The rendering pipeline name
  82096. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82097. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  82098. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82099. */
  82100. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  82101. var _this = _super.call(this, scene.getEngine(), name) || this;
  82102. // Members
  82103. /**
  82104. * The PassPostProcess id in the pipeline that contains the original scene color
  82105. */
  82106. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82107. /**
  82108. * The SSAO PostProcess id in the pipeline
  82109. */
  82110. _this.SSAORenderEffect = "SSAORenderEffect";
  82111. /**
  82112. * The horizontal blur PostProcess id in the pipeline
  82113. */
  82114. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82115. /**
  82116. * The vertical blur PostProcess id in the pipeline
  82117. */
  82118. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82119. /**
  82120. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82121. */
  82122. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82123. /**
  82124. * The output strength of the SSAO post-process. Default value is 1.0.
  82125. */
  82126. _this.totalStrength = 1.0;
  82127. /**
  82128. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  82129. */
  82130. _this.radius = 0.0001;
  82131. /**
  82132. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  82133. * Must not be equal to fallOff and superior to fallOff.
  82134. * Default value is 0.975
  82135. */
  82136. _this.area = 0.0075;
  82137. /**
  82138. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  82139. * Must not be equal to area and inferior to area.
  82140. * Default value is 0.0
  82141. */
  82142. _this.fallOff = 0.000001;
  82143. /**
  82144. * The base color of the SSAO post-process
  82145. * The final result is "base + ssao" between [0, 1]
  82146. */
  82147. _this.base = 0.5;
  82148. _this._firstUpdate = true;
  82149. _this._scene = scene;
  82150. // Set up assets
  82151. _this._createRandomTexture();
  82152. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82153. var ssaoRatio = ratio.ssaoRatio || ratio;
  82154. var combineRatio = ratio.combineRatio || ratio;
  82155. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82156. _this._createSSAOPostProcess(ssaoRatio);
  82157. _this._createBlurPostProcess(ssaoRatio);
  82158. _this._createSSAOCombinePostProcess(combineRatio);
  82159. // Set up pipeline
  82160. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82161. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82162. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82163. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82164. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82165. // Finish
  82166. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82167. if (cameras)
  82168. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82169. return _this;
  82170. }
  82171. // Public Methods
  82172. /**
  82173. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82174. */
  82175. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82176. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82177. for (var i = 0; i < this._scene.cameras.length; i++) {
  82178. var camera = this._scene.cameras[i];
  82179. this._originalColorPostProcess.dispose(camera);
  82180. this._ssaoPostProcess.dispose(camera);
  82181. this._blurHPostProcess.dispose(camera);
  82182. this._blurVPostProcess.dispose(camera);
  82183. this._ssaoCombinePostProcess.dispose(camera);
  82184. }
  82185. this._randomTexture.dispose();
  82186. if (disableDepthRender)
  82187. this._scene.disableDepthRenderer();
  82188. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82189. _super.prototype.dispose.call(this);
  82190. };
  82191. // Private Methods
  82192. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  82193. var _this = this;
  82194. var size = 16;
  82195. 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);
  82196. 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);
  82197. this._blurHPostProcess.onActivateObservable.add(function () {
  82198. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  82199. _this._blurHPostProcess.kernel = size * dw;
  82200. });
  82201. this._blurVPostProcess.onActivateObservable.add(function () {
  82202. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  82203. _this._blurVPostProcess.kernel = size * dw;
  82204. });
  82205. };
  82206. /** @hidden */
  82207. SSAORenderingPipeline.prototype._rebuild = function () {
  82208. this._firstUpdate = true;
  82209. _super.prototype._rebuild.call(this);
  82210. };
  82211. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82212. var _this = this;
  82213. var numSamples = 16;
  82214. var sampleSphere = [
  82215. 0.5381, 0.1856, -0.4319,
  82216. 0.1379, 0.2486, 0.4430,
  82217. 0.3371, 0.5679, -0.0057,
  82218. -0.6999, -0.0451, -0.0019,
  82219. 0.0689, -0.1598, -0.8547,
  82220. 0.0560, 0.0069, -0.1843,
  82221. -0.0146, 0.1402, 0.0762,
  82222. 0.0100, -0.1924, -0.0344,
  82223. -0.3577, -0.5301, -0.4358,
  82224. -0.3169, 0.1063, 0.0158,
  82225. 0.0103, -0.5869, 0.0046,
  82226. -0.0897, -0.4940, 0.3287,
  82227. 0.7119, -0.0154, -0.0918,
  82228. -0.0533, 0.0596, -0.5411,
  82229. 0.0352, -0.0631, 0.5460,
  82230. -0.4776, 0.2847, -0.0271
  82231. ];
  82232. var samplesFactor = 1.0 / numSamples;
  82233. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  82234. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82235. "area", "fallOff", "base", "range", "viewport"
  82236. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82237. this._ssaoPostProcess.onApply = function (effect) {
  82238. if (_this._firstUpdate) {
  82239. effect.setArray3("sampleSphere", sampleSphere);
  82240. effect.setFloat("samplesFactor", samplesFactor);
  82241. effect.setFloat("randTextureTiles", 4.0);
  82242. }
  82243. effect.setFloat("totalStrength", _this.totalStrength);
  82244. effect.setFloat("radius", _this.radius);
  82245. effect.setFloat("area", _this.area);
  82246. effect.setFloat("fallOff", _this.fallOff);
  82247. effect.setFloat("base", _this.base);
  82248. effect.setTexture("textureSampler", _this._depthTexture);
  82249. effect.setTexture("randomSampler", _this._randomTexture);
  82250. };
  82251. };
  82252. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82253. var _this = this;
  82254. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82255. this._ssaoCombinePostProcess.onApply = function (effect) {
  82256. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  82257. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82258. };
  82259. };
  82260. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  82261. var size = 512;
  82262. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82263. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82264. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82265. var context = this._randomTexture.getContext();
  82266. var rand = function (min, max) {
  82267. return Math.random() * (max - min) + min;
  82268. };
  82269. var randVector = BABYLON.Vector3.Zero();
  82270. for (var x = 0; x < size; x++) {
  82271. for (var y = 0; y < size; y++) {
  82272. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  82273. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  82274. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  82275. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  82276. context.fillRect(x, y, 1, 1);
  82277. }
  82278. }
  82279. this._randomTexture.update(false);
  82280. };
  82281. __decorate([
  82282. BABYLON.serialize()
  82283. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  82284. __decorate([
  82285. BABYLON.serialize()
  82286. ], SSAORenderingPipeline.prototype, "radius", void 0);
  82287. __decorate([
  82288. BABYLON.serialize()
  82289. ], SSAORenderingPipeline.prototype, "area", void 0);
  82290. __decorate([
  82291. BABYLON.serialize()
  82292. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  82293. __decorate([
  82294. BABYLON.serialize()
  82295. ], SSAORenderingPipeline.prototype, "base", void 0);
  82296. return SSAORenderingPipeline;
  82297. }(BABYLON.PostProcessRenderPipeline));
  82298. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  82299. })(BABYLON || (BABYLON = {}));
  82300. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  82301. var BABYLON;
  82302. (function (BABYLON) {
  82303. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  82304. __extends(SSAO2RenderingPipeline, _super);
  82305. /**
  82306. * @constructor
  82307. * @param {string} name - The rendering pipeline name
  82308. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82309. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  82310. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82311. */
  82312. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  82313. var _this = _super.call(this, scene.getEngine(), name) || this;
  82314. // Members
  82315. /**
  82316. * The PassPostProcess id in the pipeline that contains the original scene color
  82317. */
  82318. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82319. /**
  82320. * The SSAO PostProcess id in the pipeline
  82321. */
  82322. _this.SSAORenderEffect = "SSAORenderEffect";
  82323. /**
  82324. * The horizontal blur PostProcess id in the pipeline
  82325. */
  82326. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82327. /**
  82328. * The vertical blur PostProcess id in the pipeline
  82329. */
  82330. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82331. /**
  82332. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82333. */
  82334. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82335. /**
  82336. * The output strength of the SSAO post-process. Default value is 1.0.
  82337. */
  82338. _this.totalStrength = 1.0;
  82339. /**
  82340. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  82341. */
  82342. _this.maxZ = 100.0;
  82343. /**
  82344. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  82345. */
  82346. _this.minZAspect = 0.2;
  82347. _this._samples = 8;
  82348. _this._textureSamples = 1;
  82349. /**
  82350. * Are we using bilateral blur ?
  82351. */
  82352. _this._expensiveBlur = true;
  82353. /**
  82354. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  82355. */
  82356. _this.radius = 2.0;
  82357. /**
  82358. * The base color of the SSAO post-process
  82359. * The final result is "base + ssao" between [0, 1]
  82360. */
  82361. _this.base = 0;
  82362. _this._firstUpdate = true;
  82363. _this._bits = new Uint32Array(1);
  82364. _this._scene = scene;
  82365. _this._ratio = ratio;
  82366. if (!_this.isSupported) {
  82367. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  82368. return _this;
  82369. }
  82370. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  82371. var blurRatio = _this._ratio.blurRatio || ratio;
  82372. // Set up assets
  82373. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  82374. _this._createRandomTexture();
  82375. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  82376. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  82377. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82378. _this._originalColorPostProcess.samples = _this.textureSamples;
  82379. _this._createSSAOPostProcess(1.0);
  82380. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  82381. _this._createSSAOCombinePostProcess(blurRatio);
  82382. // Set up pipeline
  82383. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82384. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82385. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82386. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82387. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82388. // Finish
  82389. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82390. if (cameras)
  82391. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82392. return _this;
  82393. }
  82394. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  82395. get: function () {
  82396. return this._samples;
  82397. },
  82398. /**
  82399. * Number of samples used for the SSAO calculations. Default value is 8
  82400. */
  82401. set: function (n) {
  82402. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  82403. this._samples = n;
  82404. this._sampleSphere = this._generateHemisphere();
  82405. this._firstUpdate = true;
  82406. },
  82407. enumerable: true,
  82408. configurable: true
  82409. });
  82410. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  82411. get: function () {
  82412. return this._textureSamples;
  82413. },
  82414. /**
  82415. * Number of samples to use for antialiasing
  82416. */
  82417. set: function (n) {
  82418. this._textureSamples = n;
  82419. this._originalColorPostProcess.samples = n;
  82420. this._blurHPostProcess.samples = n;
  82421. this._blurVPostProcess.samples = n;
  82422. this._ssaoPostProcess.samples = n;
  82423. this._ssaoCombinePostProcess.samples = n;
  82424. },
  82425. enumerable: true,
  82426. configurable: true
  82427. });
  82428. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  82429. get: function () {
  82430. return this._expensiveBlur;
  82431. },
  82432. set: function (b) {
  82433. 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"]);
  82434. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  82435. this._expensiveBlur = b;
  82436. this._firstUpdate = true;
  82437. },
  82438. enumerable: true,
  82439. configurable: true
  82440. });
  82441. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  82442. /**
  82443. * Support test.
  82444. */
  82445. get: function () {
  82446. var engine = BABYLON.Engine.LastCreatedEngine;
  82447. if (!engine) {
  82448. return false;
  82449. }
  82450. return engine.getCaps().drawBuffersExtension;
  82451. },
  82452. enumerable: true,
  82453. configurable: true
  82454. });
  82455. // Public Methods
  82456. /**
  82457. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82458. */
  82459. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  82460. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  82461. for (var i = 0; i < this._scene.cameras.length; i++) {
  82462. var camera = this._scene.cameras[i];
  82463. this._originalColorPostProcess.dispose(camera);
  82464. this._ssaoPostProcess.dispose(camera);
  82465. this._blurHPostProcess.dispose(camera);
  82466. this._blurVPostProcess.dispose(camera);
  82467. this._ssaoCombinePostProcess.dispose(camera);
  82468. }
  82469. this._randomTexture.dispose();
  82470. if (disableGeometryBufferRenderer)
  82471. this._scene.disableGeometryBufferRenderer();
  82472. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82473. _super.prototype.dispose.call(this);
  82474. };
  82475. // Private Methods
  82476. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  82477. var _this = this;
  82478. this._samplerOffsets = [];
  82479. var expensive = this.expensiveBlur;
  82480. for (var i = -8; i < 8; i++) {
  82481. this._samplerOffsets.push(i * 2 + 0.5);
  82482. }
  82483. 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");
  82484. this._blurHPostProcess.onApply = function (effect) {
  82485. if (!_this._scene.activeCamera) {
  82486. return;
  82487. }
  82488. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  82489. effect.setFloat("near", _this._scene.activeCamera.minZ);
  82490. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  82491. effect.setFloat("radius", _this.radius);
  82492. effect.setTexture("depthSampler", _this._depthTexture);
  82493. if (_this._firstUpdate) {
  82494. effect.setArray("samplerOffsets", _this._samplerOffsets);
  82495. }
  82496. };
  82497. 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");
  82498. this._blurVPostProcess.onApply = function (effect) {
  82499. if (!_this._scene.activeCamera) {
  82500. return;
  82501. }
  82502. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  82503. effect.setFloat("near", _this._scene.activeCamera.minZ);
  82504. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  82505. effect.setFloat("radius", _this.radius);
  82506. effect.setTexture("depthSampler", _this._depthTexture);
  82507. if (_this._firstUpdate) {
  82508. effect.setArray("samplerOffsets", _this._samplerOffsets);
  82509. _this._firstUpdate = false;
  82510. }
  82511. };
  82512. this._blurHPostProcess.samples = this.textureSamples;
  82513. this._blurVPostProcess.samples = this.textureSamples;
  82514. };
  82515. /** @hidden */
  82516. SSAO2RenderingPipeline.prototype._rebuild = function () {
  82517. this._firstUpdate = true;
  82518. _super.prototype._rebuild.call(this);
  82519. };
  82520. //Van der Corput radical inverse
  82521. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  82522. this._bits[0] = i;
  82523. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  82524. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  82525. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  82526. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  82527. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  82528. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  82529. };
  82530. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  82531. return [i / n, this._radicalInverse_VdC(i)];
  82532. };
  82533. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  82534. var phi = v * 2.0 * Math.PI;
  82535. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  82536. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  82537. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  82538. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  82539. };
  82540. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  82541. var numSamples = this.samples;
  82542. var result = [];
  82543. var vector;
  82544. var i = 0;
  82545. while (i < numSamples) {
  82546. if (numSamples < 16) {
  82547. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  82548. }
  82549. else {
  82550. var rand = this._hammersley(i, numSamples);
  82551. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  82552. }
  82553. result.push(vector.x, vector.y, vector.z);
  82554. i++;
  82555. }
  82556. return result;
  82557. };
  82558. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82559. var _this = this;
  82560. var numSamples = this.samples;
  82561. this._sampleSphere = this._generateHemisphere();
  82562. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  82563. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82564. "base", "range", "projection", "near", "far", "texelSize",
  82565. "xViewport", "yViewport", "maxZ", "minZAspect"
  82566. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82567. this._ssaoPostProcess.onApply = function (effect) {
  82568. if (_this._firstUpdate) {
  82569. effect.setArray3("sampleSphere", _this._sampleSphere);
  82570. effect.setFloat("randTextureTiles", 32.0);
  82571. }
  82572. if (!_this._scene.activeCamera) {
  82573. return;
  82574. }
  82575. effect.setFloat("samplesFactor", 1 / _this.samples);
  82576. effect.setFloat("totalStrength", _this.totalStrength);
  82577. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  82578. effect.setFloat("radius", _this.radius);
  82579. effect.setFloat("maxZ", _this.maxZ);
  82580. effect.setFloat("minZAspect", _this.minZAspect);
  82581. effect.setFloat("base", _this.base);
  82582. effect.setFloat("near", _this._scene.activeCamera.minZ);
  82583. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  82584. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  82585. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  82586. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  82587. effect.setTexture("textureSampler", _this._depthTexture);
  82588. effect.setTexture("normalSampler", _this._normalTexture);
  82589. effect.setTexture("randomSampler", _this._randomTexture);
  82590. };
  82591. this._ssaoPostProcess.samples = this.textureSamples;
  82592. };
  82593. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82594. var _this = this;
  82595. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82596. this._ssaoCombinePostProcess.onApply = function (effect) {
  82597. var viewport = _this._scene.activeCamera.viewport;
  82598. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  82599. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82600. };
  82601. this._ssaoCombinePostProcess.samples = this.textureSamples;
  82602. };
  82603. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  82604. var size = 128;
  82605. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82606. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82607. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82608. var context = this._randomTexture.getContext();
  82609. var rand = function (min, max) {
  82610. return Math.random() * (max - min) + min;
  82611. };
  82612. var randVector = BABYLON.Vector3.Zero();
  82613. for (var x = 0; x < size; x++) {
  82614. for (var y = 0; y < size; y++) {
  82615. randVector.x = rand(0.0, 1.0);
  82616. randVector.y = rand(0.0, 1.0);
  82617. randVector.z = 0.0;
  82618. randVector.normalize();
  82619. randVector.scaleInPlace(255);
  82620. randVector.x = Math.floor(randVector.x);
  82621. randVector.y = Math.floor(randVector.y);
  82622. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  82623. context.fillRect(x, y, 1, 1);
  82624. }
  82625. }
  82626. this._randomTexture.update(false);
  82627. };
  82628. /**
  82629. * Serialize the rendering pipeline (Used when exporting)
  82630. * @returns the serialized object
  82631. */
  82632. SSAO2RenderingPipeline.prototype.serialize = function () {
  82633. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82634. serializationObject.customType = "SSAO2RenderingPipeline";
  82635. return serializationObject;
  82636. };
  82637. /**
  82638. * Parse the serialized pipeline
  82639. * @param source Source pipeline.
  82640. * @param scene The scene to load the pipeline to.
  82641. * @param rootUrl The URL of the serialized pipeline.
  82642. * @returns An instantiated pipeline from the serialized object.
  82643. */
  82644. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  82645. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  82646. };
  82647. __decorate([
  82648. BABYLON.serialize()
  82649. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  82650. __decorate([
  82651. BABYLON.serialize()
  82652. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  82653. __decorate([
  82654. BABYLON.serialize()
  82655. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  82656. __decorate([
  82657. BABYLON.serialize("samples")
  82658. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  82659. __decorate([
  82660. BABYLON.serialize("textureSamples")
  82661. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  82662. __decorate([
  82663. BABYLON.serialize()
  82664. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  82665. __decorate([
  82666. BABYLON.serialize("expensiveBlur")
  82667. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  82668. __decorate([
  82669. BABYLON.serialize()
  82670. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  82671. __decorate([
  82672. BABYLON.serialize()
  82673. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  82674. return SSAO2RenderingPipeline;
  82675. }(BABYLON.PostProcessRenderPipeline));
  82676. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  82677. })(BABYLON || (BABYLON = {}));
  82678. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  82679. // BABYLON.JS Chromatic Aberration GLSL Shader
  82680. // Author: Olivier Guyot
  82681. // Separates very slightly R, G and B colors on the edges of the screen
  82682. // Inspired by Francois Tarlier & Martins Upitis
  82683. var BABYLON;
  82684. (function (BABYLON) {
  82685. var LensRenderingPipeline = /** @class */ (function (_super) {
  82686. __extends(LensRenderingPipeline, _super);
  82687. /**
  82688. * @constructor
  82689. *
  82690. * Effect parameters are as follow:
  82691. * {
  82692. * chromatic_aberration: number; // from 0 to x (1 for realism)
  82693. * edge_blur: number; // from 0 to x (1 for realism)
  82694. * distortion: number; // from 0 to x (1 for realism)
  82695. * grain_amount: number; // from 0 to 1
  82696. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  82697. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  82698. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  82699. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  82700. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  82701. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  82702. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  82703. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  82704. * }
  82705. * Note: if an effect parameter is unset, effect is disabled
  82706. *
  82707. * @param {string} name - The rendering pipeline name
  82708. * @param {object} parameters - An object containing all parameters (see above)
  82709. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82710. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  82711. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82712. */
  82713. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  82714. if (ratio === void 0) { ratio = 1.0; }
  82715. var _this = _super.call(this, scene.getEngine(), name) || this;
  82716. // Lens effects can be of the following:
  82717. // - chromatic aberration (slight shift of RGB colors)
  82718. // - blur on the edge of the lens
  82719. // - lens distortion
  82720. // - depth-of-field blur & highlights enhancing
  82721. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  82722. // - grain effect (noise or custom texture)
  82723. // Two additional texture samplers are needed:
  82724. // - depth map (for depth-of-field)
  82725. // - grain texture
  82726. /**
  82727. * The chromatic aberration PostProcess id in the pipeline
  82728. */
  82729. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  82730. /**
  82731. * The highlights enhancing PostProcess id in the pipeline
  82732. */
  82733. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  82734. /**
  82735. * The depth-of-field PostProcess id in the pipeline
  82736. */
  82737. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  82738. _this._scene = scene;
  82739. // Fetch texture samplers
  82740. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82741. if (parameters.grain_texture) {
  82742. _this._grainTexture = parameters.grain_texture;
  82743. }
  82744. else {
  82745. _this._createGrainTexture();
  82746. }
  82747. // save parameters
  82748. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  82749. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  82750. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  82751. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  82752. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  82753. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  82754. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  82755. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  82756. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  82757. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  82758. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  82759. // Create effects
  82760. _this._createChromaticAberrationPostProcess(ratio);
  82761. _this._createHighlightsPostProcess(ratio);
  82762. _this._createDepthOfFieldPostProcess(ratio / 4);
  82763. // Set up pipeline
  82764. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  82765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  82766. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  82767. if (_this._highlightsGain === -1) {
  82768. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  82769. }
  82770. // Finish
  82771. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82772. if (cameras) {
  82773. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82774. }
  82775. return _this;
  82776. }
  82777. // public methods (self explanatory)
  82778. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  82779. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  82780. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  82781. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  82782. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  82783. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  82784. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  82785. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  82786. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  82787. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  82788. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  82789. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  82790. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  82791. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  82792. };
  82793. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  82794. this._highlightsPostProcess.updateEffect();
  82795. };
  82796. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  82797. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  82798. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  82799. this._highlightsGain = amount;
  82800. };
  82801. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  82802. if (this._highlightsGain === -1) {
  82803. this._highlightsGain = 1.0;
  82804. }
  82805. this._highlightsThreshold = amount;
  82806. };
  82807. LensRenderingPipeline.prototype.disableHighlights = function () {
  82808. this._highlightsGain = -1;
  82809. };
  82810. /**
  82811. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  82812. */
  82813. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82814. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82815. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82816. this._chromaticAberrationPostProcess = null;
  82817. this._highlightsPostProcess = null;
  82818. this._depthOfFieldPostProcess = null;
  82819. this._grainTexture.dispose();
  82820. if (disableDepthRender)
  82821. this._scene.disableDepthRenderer();
  82822. };
  82823. // colors shifting and distortion
  82824. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  82825. var _this = this;
  82826. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  82827. [], // samplers
  82828. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82829. this._chromaticAberrationPostProcess.onApply = function (effect) {
  82830. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  82831. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82832. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82833. effect.setFloat('radialIntensity', 1);
  82834. effect.setFloat2('direction', 17, 17);
  82835. effect.setFloat2('centerPosition', 0.5, 0.5);
  82836. };
  82837. };
  82838. // highlights enhancing
  82839. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  82840. var _this = this;
  82841. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  82842. [], // samplers
  82843. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  82844. this._highlightsPostProcess.onApply = function (effect) {
  82845. effect.setFloat('gain', _this._highlightsGain);
  82846. effect.setFloat('threshold', _this._highlightsThreshold);
  82847. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  82848. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82849. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82850. };
  82851. };
  82852. // colors shifting and distortion
  82853. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  82854. var _this = this;
  82855. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  82856. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  82857. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  82858. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82859. this._depthOfFieldPostProcess.onApply = function (effect) {
  82860. effect.setTexture("depthSampler", _this._depthTexture);
  82861. effect.setTexture("grainSampler", _this._grainTexture);
  82862. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  82863. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  82864. effect.setFloat('grain_amount', _this._grainAmount);
  82865. effect.setBool('blur_noise', _this._blurNoise);
  82866. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82867. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82868. effect.setFloat('distortion', _this._distortion);
  82869. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  82870. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  82871. effect.setFloat('aperture', _this._dofAperture);
  82872. effect.setFloat('darken', _this._dofDarken);
  82873. effect.setFloat('edge_blur', _this._edgeBlur);
  82874. effect.setBool('highlights', (_this._highlightsGain !== -1));
  82875. if (_this._scene.activeCamera) {
  82876. effect.setFloat('near', _this._scene.activeCamera.minZ);
  82877. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  82878. }
  82879. };
  82880. };
  82881. // creates a black and white random noise texture, 512x512
  82882. LensRenderingPipeline.prototype._createGrainTexture = function () {
  82883. var size = 512;
  82884. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82885. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82886. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82887. var context = this._grainTexture.getContext();
  82888. var rand = function (min, max) {
  82889. return Math.random() * (max - min) + min;
  82890. };
  82891. var value;
  82892. for (var x = 0; x < size; x++) {
  82893. for (var y = 0; y < size; y++) {
  82894. value = Math.floor(rand(0.42, 0.58) * 255);
  82895. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  82896. context.fillRect(x, y, 1, 1);
  82897. }
  82898. }
  82899. this._grainTexture.update(false);
  82900. };
  82901. return LensRenderingPipeline;
  82902. }(BABYLON.PostProcessRenderPipeline));
  82903. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  82904. })(BABYLON || (BABYLON = {}));
  82905. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  82906. var BABYLON;
  82907. (function (BABYLON) {
  82908. var StandardRenderingPipeline = /** @class */ (function (_super) {
  82909. __extends(StandardRenderingPipeline, _super);
  82910. /**
  82911. * @constructor
  82912. * @param {string} name - The rendering pipeline name
  82913. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82914. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  82915. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  82916. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82917. */
  82918. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  82919. if (originalPostProcess === void 0) { originalPostProcess = null; }
  82920. var _this = _super.call(this, scene.getEngine(), name) || this;
  82921. /**
  82922. * Post-process used to down scale an image x4
  82923. */
  82924. _this.downSampleX4PostProcess = null;
  82925. /**
  82926. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  82927. */
  82928. _this.brightPassPostProcess = null;
  82929. /**
  82930. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  82931. */
  82932. _this.blurHPostProcesses = [];
  82933. /**
  82934. * Post-process array storing all the vertical blur post-processes used by the pipeline
  82935. */
  82936. _this.blurVPostProcesses = [];
  82937. /**
  82938. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  82939. */
  82940. _this.textureAdderPostProcess = null;
  82941. /**
  82942. * Post-process used to create volumetric lighting effect
  82943. */
  82944. _this.volumetricLightPostProcess = null;
  82945. /**
  82946. * Post-process used to smooth the previous volumetric light post-process on the X axis
  82947. */
  82948. _this.volumetricLightSmoothXPostProcess = null;
  82949. /**
  82950. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  82951. */
  82952. _this.volumetricLightSmoothYPostProcess = null;
  82953. /**
  82954. * Post-process used to merge the volumetric light effect and the real scene color
  82955. */
  82956. _this.volumetricLightMergePostProces = null;
  82957. /**
  82958. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  82959. */
  82960. _this.volumetricLightFinalPostProcess = null;
  82961. /**
  82962. * Base post-process used to calculate the average luminance of the final image for HDR
  82963. */
  82964. _this.luminancePostProcess = null;
  82965. /**
  82966. * Post-processes used to create down sample post-processes in order to get
  82967. * the average luminance of the final image for HDR
  82968. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  82969. */
  82970. _this.luminanceDownSamplePostProcesses = [];
  82971. /**
  82972. * Post-process used to create a HDR effect (light adaptation)
  82973. */
  82974. _this.hdrPostProcess = null;
  82975. /**
  82976. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  82977. */
  82978. _this.textureAdderFinalPostProcess = null;
  82979. /**
  82980. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  82981. */
  82982. _this.lensFlareFinalPostProcess = null;
  82983. /**
  82984. * Post-process used to merge the final HDR post-process and the real scene color
  82985. */
  82986. _this.hdrFinalPostProcess = null;
  82987. /**
  82988. * Post-process used to create a lens flare effect
  82989. */
  82990. _this.lensFlarePostProcess = null;
  82991. /**
  82992. * Post-process that merges the result of the lens flare post-process and the real scene color
  82993. */
  82994. _this.lensFlareComposePostProcess = null;
  82995. /**
  82996. * Post-process used to create a motion blur effect
  82997. */
  82998. _this.motionBlurPostProcess = null;
  82999. /**
  83000. * Post-process used to create a depth of field effect
  83001. */
  83002. _this.depthOfFieldPostProcess = null;
  83003. /**
  83004. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  83005. */
  83006. _this.fxaaPostProcess = null;
  83007. // Values
  83008. /**
  83009. * Represents the brightness threshold in order to configure the illuminated surfaces
  83010. */
  83011. _this.brightThreshold = 1.0;
  83012. /**
  83013. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  83014. */
  83015. _this.blurWidth = 512.0;
  83016. /**
  83017. * Sets if the blur for highlighted surfaces must be only horizontal
  83018. */
  83019. _this.horizontalBlur = false;
  83020. /**
  83021. * Sets the overall exposure used by the pipeline
  83022. */
  83023. _this.exposure = 1.0;
  83024. /**
  83025. * Texture used typically to simulate "dirty" on camera lens
  83026. */
  83027. _this.lensTexture = null;
  83028. /**
  83029. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  83030. */
  83031. _this.volumetricLightCoefficient = 0.2;
  83032. /**
  83033. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  83034. */
  83035. _this.volumetricLightPower = 4.0;
  83036. /**
  83037. * Used the set the blur intensity to smooth the volumetric lights
  83038. */
  83039. _this.volumetricLightBlurScale = 64.0;
  83040. /**
  83041. * Light (spot or directional) used to generate the volumetric lights rays
  83042. * The source light must have a shadow generate so the pipeline can get its
  83043. * depth map
  83044. */
  83045. _this.sourceLight = null;
  83046. /**
  83047. * For eye adaptation, represents the minimum luminance the eye can see
  83048. */
  83049. _this.hdrMinimumLuminance = 1.0;
  83050. /**
  83051. * For eye adaptation, represents the decrease luminance speed
  83052. */
  83053. _this.hdrDecreaseRate = 0.5;
  83054. /**
  83055. * For eye adaptation, represents the increase luminance speed
  83056. */
  83057. _this.hdrIncreaseRate = 0.5;
  83058. /**
  83059. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  83060. */
  83061. _this.lensColorTexture = null;
  83062. /**
  83063. * The overall strengh for the lens flare effect
  83064. */
  83065. _this.lensFlareStrength = 20.0;
  83066. /**
  83067. * Dispersion coefficient for lens flare ghosts
  83068. */
  83069. _this.lensFlareGhostDispersal = 1.4;
  83070. /**
  83071. * Main lens flare halo width
  83072. */
  83073. _this.lensFlareHaloWidth = 0.7;
  83074. /**
  83075. * Based on the lens distortion effect, defines how much the lens flare result
  83076. * is distorted
  83077. */
  83078. _this.lensFlareDistortionStrength = 16.0;
  83079. /**
  83080. * Lens star texture must be used to simulate rays on the flares and is available
  83081. * in the documentation
  83082. */
  83083. _this.lensStarTexture = null;
  83084. /**
  83085. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  83086. * flare effect by taking account of the dirt texture
  83087. */
  83088. _this.lensFlareDirtTexture = null;
  83089. /**
  83090. * Represents the focal length for the depth of field effect
  83091. */
  83092. _this.depthOfFieldDistance = 10.0;
  83093. /**
  83094. * Represents the blur intensity for the blurred part of the depth of field effect
  83095. */
  83096. _this.depthOfFieldBlurWidth = 64.0;
  83097. /**
  83098. * For motion blur, defines how much the image is blurred by the movement
  83099. */
  83100. _this.motionStrength = 1.0;
  83101. /**
  83102. * List of animations for the pipeline (IAnimatable implementation)
  83103. */
  83104. _this.animations = [];
  83105. _this._currentDepthOfFieldSource = null;
  83106. _this._hdrCurrentLuminance = 1.0;
  83107. // Getters and setters
  83108. _this._bloomEnabled = false;
  83109. _this._depthOfFieldEnabled = false;
  83110. _this._vlsEnabled = false;
  83111. _this._lensFlareEnabled = false;
  83112. _this._hdrEnabled = false;
  83113. _this._motionBlurEnabled = false;
  83114. _this._fxaaEnabled = false;
  83115. _this._motionBlurSamples = 64.0;
  83116. _this._volumetricLightStepsCount = 50.0;
  83117. _this._samples = 1;
  83118. _this._cameras = cameras || [];
  83119. // Initialize
  83120. _this._scene = scene;
  83121. _this._basePostProcess = originalPostProcess;
  83122. _this._ratio = ratio;
  83123. // Misc
  83124. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83125. // Finish
  83126. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83127. _this._buildPipeline();
  83128. return _this;
  83129. }
  83130. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  83131. /**
  83132. * Specifies if the bloom pipeline is enabled
  83133. */
  83134. get: function () {
  83135. return this._bloomEnabled;
  83136. },
  83137. set: function (enabled) {
  83138. if (this._bloomEnabled === enabled) {
  83139. return;
  83140. }
  83141. this._bloomEnabled = enabled;
  83142. this._buildPipeline();
  83143. },
  83144. enumerable: true,
  83145. configurable: true
  83146. });
  83147. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  83148. /**
  83149. * Specifies if the depth of field pipeline is enabed
  83150. */
  83151. get: function () {
  83152. return this._depthOfFieldEnabled;
  83153. },
  83154. set: function (enabled) {
  83155. if (this._depthOfFieldEnabled === enabled) {
  83156. return;
  83157. }
  83158. this._depthOfFieldEnabled = enabled;
  83159. this._buildPipeline();
  83160. },
  83161. enumerable: true,
  83162. configurable: true
  83163. });
  83164. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  83165. /**
  83166. * Specifies if the lens flare pipeline is enabed
  83167. */
  83168. get: function () {
  83169. return this._lensFlareEnabled;
  83170. },
  83171. set: function (enabled) {
  83172. if (this._lensFlareEnabled === enabled) {
  83173. return;
  83174. }
  83175. this._lensFlareEnabled = enabled;
  83176. this._buildPipeline();
  83177. },
  83178. enumerable: true,
  83179. configurable: true
  83180. });
  83181. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  83182. /**
  83183. * Specifies if the HDR pipeline is enabled
  83184. */
  83185. get: function () {
  83186. return this._hdrEnabled;
  83187. },
  83188. set: function (enabled) {
  83189. if (this._hdrEnabled === enabled) {
  83190. return;
  83191. }
  83192. this._hdrEnabled = enabled;
  83193. this._buildPipeline();
  83194. },
  83195. enumerable: true,
  83196. configurable: true
  83197. });
  83198. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  83199. /**
  83200. * Specifies if the volumetric lights scattering effect is enabled
  83201. */
  83202. get: function () {
  83203. return this._vlsEnabled;
  83204. },
  83205. set: function (enabled) {
  83206. if (this._vlsEnabled === enabled) {
  83207. return;
  83208. }
  83209. if (enabled) {
  83210. var geometry = this._scene.enableGeometryBufferRenderer();
  83211. if (!geometry) {
  83212. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  83213. return;
  83214. }
  83215. }
  83216. this._vlsEnabled = enabled;
  83217. this._buildPipeline();
  83218. },
  83219. enumerable: true,
  83220. configurable: true
  83221. });
  83222. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  83223. /**
  83224. * Specifies if the motion blur effect is enabled
  83225. */
  83226. get: function () {
  83227. return this._motionBlurEnabled;
  83228. },
  83229. set: function (enabled) {
  83230. if (this._motionBlurEnabled === enabled) {
  83231. return;
  83232. }
  83233. this._motionBlurEnabled = enabled;
  83234. this._buildPipeline();
  83235. },
  83236. enumerable: true,
  83237. configurable: true
  83238. });
  83239. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  83240. /**
  83241. * Specifies if anti-aliasing is enabled
  83242. */
  83243. get: function () {
  83244. return this._fxaaEnabled;
  83245. },
  83246. set: function (enabled) {
  83247. if (this._fxaaEnabled === enabled) {
  83248. return;
  83249. }
  83250. this._fxaaEnabled = enabled;
  83251. this._buildPipeline();
  83252. },
  83253. enumerable: true,
  83254. configurable: true
  83255. });
  83256. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  83257. /**
  83258. * Specifies the number of steps used to calculate the volumetric lights
  83259. * Typically in interval [50, 200]
  83260. */
  83261. get: function () {
  83262. return this._volumetricLightStepsCount;
  83263. },
  83264. set: function (count) {
  83265. if (this.volumetricLightPostProcess) {
  83266. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  83267. }
  83268. this._volumetricLightStepsCount = count;
  83269. },
  83270. enumerable: true,
  83271. configurable: true
  83272. });
  83273. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  83274. /**
  83275. * Specifies the number of samples used for the motion blur effect
  83276. * Typically in interval [16, 64]
  83277. */
  83278. get: function () {
  83279. return this._motionBlurSamples;
  83280. },
  83281. set: function (samples) {
  83282. if (this.motionBlurPostProcess) {
  83283. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  83284. }
  83285. this._motionBlurSamples = samples;
  83286. },
  83287. enumerable: true,
  83288. configurable: true
  83289. });
  83290. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  83291. /**
  83292. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83293. */
  83294. get: function () {
  83295. return this._samples;
  83296. },
  83297. set: function (sampleCount) {
  83298. if (this._samples === sampleCount) {
  83299. return;
  83300. }
  83301. this._samples = sampleCount;
  83302. this._buildPipeline();
  83303. },
  83304. enumerable: true,
  83305. configurable: true
  83306. });
  83307. StandardRenderingPipeline.prototype._buildPipeline = function () {
  83308. var _this = this;
  83309. var ratio = this._ratio;
  83310. var scene = this._scene;
  83311. this._disposePostProcesses();
  83312. this._reset();
  83313. // Create pass post-process
  83314. if (!this._basePostProcess) {
  83315. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  83316. this.originalPostProcess.onApply = function (effect) {
  83317. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  83318. };
  83319. }
  83320. else {
  83321. this.originalPostProcess = this._basePostProcess;
  83322. }
  83323. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  83324. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  83325. }
  83326. this._currentDepthOfFieldSource = this.originalPostProcess;
  83327. if (this._bloomEnabled) {
  83328. // Create down sample X4 post-process
  83329. this._createDownSampleX4PostProcess(scene, ratio / 2);
  83330. // Create bright pass post-process
  83331. this._createBrightPassPostProcess(scene, ratio / 2);
  83332. // Create gaussian blur post-processes (down sampling blurs)
  83333. this._createBlurPostProcesses(scene, ratio / 4, 1);
  83334. // Create texture adder post-process
  83335. this._createTextureAdderPostProcess(scene, ratio);
  83336. // Create depth-of-field source post-process
  83337. 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);
  83338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  83339. }
  83340. if (this._vlsEnabled) {
  83341. // Create volumetric light
  83342. this._createVolumetricLightPostProcess(scene, ratio);
  83343. // Create volumetric light final post-process
  83344. 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);
  83345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  83346. }
  83347. if (this._lensFlareEnabled) {
  83348. // Create lens flare post-process
  83349. this._createLensFlarePostProcess(scene, ratio);
  83350. // Create depth-of-field source post-process post lens-flare and disable it now
  83351. 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);
  83352. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  83353. }
  83354. if (this._hdrEnabled) {
  83355. // Create luminance
  83356. this._createLuminancePostProcesses(scene, this._floatTextureType);
  83357. // Create HDR
  83358. this._createHdrPostProcess(scene, ratio);
  83359. // Create depth-of-field source post-process post hdr and disable it now
  83360. 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);
  83361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  83362. }
  83363. if (this._depthOfFieldEnabled) {
  83364. // Create gaussian blur used by depth-of-field
  83365. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  83366. // Create depth-of-field post-process
  83367. this._createDepthOfFieldPostProcess(scene, ratio);
  83368. }
  83369. if (this._motionBlurEnabled) {
  83370. // Create motion blur post-process
  83371. this._createMotionBlurPostProcess(scene, ratio);
  83372. }
  83373. if (this._fxaaEnabled) {
  83374. // Create fxaa post-process
  83375. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83376. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  83377. }
  83378. if (this._cameras !== null) {
  83379. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  83380. }
  83381. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  83382. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  83383. }
  83384. };
  83385. // Down Sample X4 Post-Processs
  83386. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  83387. var _this = this;
  83388. var downSampleX4Offsets = new Array(32);
  83389. 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);
  83390. this.downSampleX4PostProcess.onApply = function (effect) {
  83391. var id = 0;
  83392. var width = _this.downSampleX4PostProcess.width;
  83393. var height = _this.downSampleX4PostProcess.height;
  83394. for (var i = -2; i < 2; i++) {
  83395. for (var j = -2; j < 2; j++) {
  83396. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  83397. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  83398. id += 2;
  83399. }
  83400. }
  83401. effect.setArray2("dsOffsets", downSampleX4Offsets);
  83402. };
  83403. // Add to pipeline
  83404. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  83405. };
  83406. // Brightpass Post-Process
  83407. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  83408. var _this = this;
  83409. var brightOffsets = new Array(8);
  83410. 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);
  83411. this.brightPassPostProcess.onApply = function (effect) {
  83412. var sU = (1.0 / _this.brightPassPostProcess.width);
  83413. var sV = (1.0 / _this.brightPassPostProcess.height);
  83414. brightOffsets[0] = -0.5 * sU;
  83415. brightOffsets[1] = 0.5 * sV;
  83416. brightOffsets[2] = 0.5 * sU;
  83417. brightOffsets[3] = 0.5 * sV;
  83418. brightOffsets[4] = -0.5 * sU;
  83419. brightOffsets[5] = -0.5 * sV;
  83420. brightOffsets[6] = 0.5 * sU;
  83421. brightOffsets[7] = -0.5 * sV;
  83422. effect.setArray2("dsOffsets", brightOffsets);
  83423. effect.setFloat("brightThreshold", _this.brightThreshold);
  83424. };
  83425. // Add to pipeline
  83426. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  83427. };
  83428. // Create blur H&V post-processes
  83429. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  83430. var _this = this;
  83431. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  83432. var engine = scene.getEngine();
  83433. 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);
  83434. 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);
  83435. blurX.onActivateObservable.add(function () {
  83436. var dw = blurX.width / engine.getRenderWidth();
  83437. blurX.kernel = _this[blurWidthKey] * dw;
  83438. });
  83439. blurY.onActivateObservable.add(function () {
  83440. var dw = blurY.height / engine.getRenderHeight();
  83441. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  83442. });
  83443. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  83444. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  83445. this.blurHPostProcesses.push(blurX);
  83446. this.blurVPostProcesses.push(blurY);
  83447. };
  83448. // Create texture adder post-process
  83449. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  83450. var _this = this;
  83451. 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);
  83452. this.textureAdderPostProcess.onApply = function (effect) {
  83453. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  83454. effect.setTexture("lensSampler", _this.lensTexture);
  83455. effect.setFloat("exposure", _this.exposure);
  83456. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  83457. };
  83458. // Add to pipeline
  83459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  83460. };
  83461. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  83462. var _this = this;
  83463. var geometryRenderer = scene.enableGeometryBufferRenderer();
  83464. geometryRenderer.enablePosition = true;
  83465. var geometry = geometryRenderer.getGBuffer();
  83466. // Base post-process
  83467. 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));
  83468. var depthValues = BABYLON.Vector2.Zero();
  83469. this.volumetricLightPostProcess.onApply = function (effect) {
  83470. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  83471. var generator = _this.sourceLight.getShadowGenerator();
  83472. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  83473. effect.setTexture("positionSampler", geometry.textures[2]);
  83474. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  83475. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  83476. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  83477. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  83478. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  83479. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  83480. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  83481. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  83482. effect.setVector2("depthValues", depthValues);
  83483. }
  83484. };
  83485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  83486. // Smooth
  83487. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  83488. // Merge
  83489. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  83490. this.volumetricLightMergePostProces.onApply = function (effect) {
  83491. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  83492. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  83493. };
  83494. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  83495. };
  83496. // Create luminance
  83497. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  83498. var _this = this;
  83499. // Create luminance
  83500. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  83501. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  83502. var offsets = [];
  83503. this.luminancePostProcess.onApply = function (effect) {
  83504. var sU = (1.0 / _this.luminancePostProcess.width);
  83505. var sV = (1.0 / _this.luminancePostProcess.height);
  83506. offsets[0] = -0.5 * sU;
  83507. offsets[1] = 0.5 * sV;
  83508. offsets[2] = 0.5 * sU;
  83509. offsets[3] = 0.5 * sV;
  83510. offsets[4] = -0.5 * sU;
  83511. offsets[5] = -0.5 * sV;
  83512. offsets[6] = 0.5 * sU;
  83513. offsets[7] = -0.5 * sV;
  83514. effect.setArray2("lumOffsets", offsets);
  83515. };
  83516. // Add to pipeline
  83517. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  83518. // Create down sample luminance
  83519. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  83520. var size = Math.pow(3, i);
  83521. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  83522. if (i === 0) {
  83523. defines += "#define FINAL_DOWN_SAMPLER";
  83524. }
  83525. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  83526. this.luminanceDownSamplePostProcesses.push(postProcess);
  83527. }
  83528. // Create callbacks and add effects
  83529. var lastLuminance = this.luminancePostProcess;
  83530. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  83531. var downSampleOffsets = new Array(18);
  83532. pp.onApply = function (effect) {
  83533. if (!lastLuminance) {
  83534. return;
  83535. }
  83536. var id = 0;
  83537. for (var x = -1; x < 2; x++) {
  83538. for (var y = -1; y < 2; y++) {
  83539. downSampleOffsets[id] = x / lastLuminance.width;
  83540. downSampleOffsets[id + 1] = y / lastLuminance.height;
  83541. id += 2;
  83542. }
  83543. }
  83544. effect.setArray2("dsOffsets", downSampleOffsets);
  83545. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  83546. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  83547. lastLuminance = _this.luminancePostProcess;
  83548. }
  83549. else {
  83550. lastLuminance = pp;
  83551. }
  83552. };
  83553. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  83554. pp.onAfterRender = function (effect) {
  83555. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  83556. 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);
  83557. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  83558. };
  83559. }
  83560. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  83561. });
  83562. };
  83563. // Create HDR post-process
  83564. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  83565. var _this = this;
  83566. 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);
  83567. var outputLiminance = 1;
  83568. var time = 0;
  83569. var lastTime = 0;
  83570. this.hdrPostProcess.onApply = function (effect) {
  83571. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  83572. time += scene.getEngine().getDeltaTime();
  83573. if (outputLiminance < 0) {
  83574. outputLiminance = _this._hdrCurrentLuminance;
  83575. }
  83576. else {
  83577. var dt = (lastTime - time) / 1000.0;
  83578. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  83579. outputLiminance += _this.hdrDecreaseRate * dt;
  83580. }
  83581. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  83582. outputLiminance -= _this.hdrIncreaseRate * dt;
  83583. }
  83584. else {
  83585. outputLiminance = _this._hdrCurrentLuminance;
  83586. }
  83587. }
  83588. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  83589. effect.setFloat("averageLuminance", outputLiminance);
  83590. lastTime = time;
  83591. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  83592. };
  83593. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  83594. };
  83595. // Create lens flare post-process
  83596. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  83597. var _this = this;
  83598. 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);
  83599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  83600. this._createBlurPostProcesses(scene, ratio / 4, 2);
  83601. 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);
  83602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  83603. var resolution = new BABYLON.Vector2(0, 0);
  83604. // Lens flare
  83605. this.lensFlarePostProcess.onApply = function (effect) {
  83606. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  83607. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  83608. effect.setFloat("strength", _this.lensFlareStrength);
  83609. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  83610. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  83611. // Shift
  83612. resolution.x = _this.lensFlarePostProcess.width;
  83613. resolution.y = _this.lensFlarePostProcess.height;
  83614. effect.setVector2("resolution", resolution);
  83615. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  83616. };
  83617. // Compose
  83618. 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);
  83619. 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);
  83620. this.lensFlareComposePostProcess.onApply = function (effect) {
  83621. if (!_this._scene.activeCamera) {
  83622. return;
  83623. }
  83624. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  83625. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  83626. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  83627. // Lens start rotation matrix
  83628. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  83629. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  83630. 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));
  83631. camRot *= 4.0;
  83632. 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);
  83633. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  83634. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  83635. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  83636. };
  83637. };
  83638. // Create depth-of-field post-process
  83639. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  83640. var _this = this;
  83641. 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);
  83642. this.depthOfFieldPostProcess.onApply = function (effect) {
  83643. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  83644. effect.setTexture("depthSampler", _this._getDepthTexture());
  83645. effect.setFloat("distance", _this.depthOfFieldDistance);
  83646. };
  83647. // Add to pipeline
  83648. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  83649. };
  83650. // Create motion blur post-process
  83651. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  83652. var _this = this;
  83653. 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);
  83654. var motionScale = 0;
  83655. var prevViewProjection = BABYLON.Matrix.Identity();
  83656. var invViewProjection = BABYLON.Matrix.Identity();
  83657. var viewProjection = BABYLON.Matrix.Identity();
  83658. var screenSize = BABYLON.Vector2.Zero();
  83659. this.motionBlurPostProcess.onApply = function (effect) {
  83660. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  83661. viewProjection.invertToRef(invViewProjection);
  83662. effect.setMatrix("inverseViewProjection", invViewProjection);
  83663. effect.setMatrix("prevViewProjection", prevViewProjection);
  83664. prevViewProjection = viewProjection;
  83665. screenSize.x = _this.motionBlurPostProcess.width;
  83666. screenSize.y = _this.motionBlurPostProcess.height;
  83667. effect.setVector2("screenSize", screenSize);
  83668. motionScale = scene.getEngine().getFps() / 60.0;
  83669. effect.setFloat("motionScale", motionScale);
  83670. effect.setFloat("motionStrength", _this.motionStrength);
  83671. effect.setTexture("depthSampler", _this._getDepthTexture());
  83672. };
  83673. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  83674. };
  83675. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  83676. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  83677. var renderer = this._scene.enableGeometryBufferRenderer();
  83678. return renderer.getGBuffer().textures[0];
  83679. }
  83680. return this._scene.enableDepthRenderer().getDepthMap();
  83681. };
  83682. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  83683. for (var i = 0; i < this._cameras.length; i++) {
  83684. var camera = this._cameras[i];
  83685. if (this.originalPostProcess) {
  83686. this.originalPostProcess.dispose(camera);
  83687. }
  83688. if (this.downSampleX4PostProcess) {
  83689. this.downSampleX4PostProcess.dispose(camera);
  83690. }
  83691. if (this.brightPassPostProcess) {
  83692. this.brightPassPostProcess.dispose(camera);
  83693. }
  83694. if (this.textureAdderPostProcess) {
  83695. this.textureAdderPostProcess.dispose(camera);
  83696. }
  83697. if (this.textureAdderFinalPostProcess) {
  83698. this.textureAdderFinalPostProcess.dispose(camera);
  83699. }
  83700. if (this.volumetricLightPostProcess) {
  83701. this.volumetricLightPostProcess.dispose(camera);
  83702. }
  83703. if (this.volumetricLightSmoothXPostProcess) {
  83704. this.volumetricLightSmoothXPostProcess.dispose(camera);
  83705. }
  83706. if (this.volumetricLightSmoothYPostProcess) {
  83707. this.volumetricLightSmoothYPostProcess.dispose(camera);
  83708. }
  83709. if (this.volumetricLightMergePostProces) {
  83710. this.volumetricLightMergePostProces.dispose(camera);
  83711. }
  83712. if (this.volumetricLightFinalPostProcess) {
  83713. this.volumetricLightFinalPostProcess.dispose(camera);
  83714. }
  83715. if (this.lensFlarePostProcess) {
  83716. this.lensFlarePostProcess.dispose(camera);
  83717. }
  83718. if (this.lensFlareComposePostProcess) {
  83719. this.lensFlareComposePostProcess.dispose(camera);
  83720. }
  83721. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  83722. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  83723. }
  83724. if (this.luminancePostProcess) {
  83725. this.luminancePostProcess.dispose(camera);
  83726. }
  83727. if (this.hdrPostProcess) {
  83728. this.hdrPostProcess.dispose(camera);
  83729. }
  83730. if (this.hdrFinalPostProcess) {
  83731. this.hdrFinalPostProcess.dispose(camera);
  83732. }
  83733. if (this.depthOfFieldPostProcess) {
  83734. this.depthOfFieldPostProcess.dispose(camera);
  83735. }
  83736. if (this.motionBlurPostProcess) {
  83737. this.motionBlurPostProcess.dispose(camera);
  83738. }
  83739. if (this.fxaaPostProcess) {
  83740. this.fxaaPostProcess.dispose(camera);
  83741. }
  83742. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  83743. this.blurHPostProcesses[j].dispose(camera);
  83744. }
  83745. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  83746. this.blurVPostProcesses[j].dispose(camera);
  83747. }
  83748. }
  83749. this.originalPostProcess = null;
  83750. this.downSampleX4PostProcess = null;
  83751. this.brightPassPostProcess = null;
  83752. this.textureAdderPostProcess = null;
  83753. this.textureAdderFinalPostProcess = null;
  83754. this.volumetricLightPostProcess = null;
  83755. this.volumetricLightSmoothXPostProcess = null;
  83756. this.volumetricLightSmoothYPostProcess = null;
  83757. this.volumetricLightMergePostProces = null;
  83758. this.volumetricLightFinalPostProcess = null;
  83759. this.lensFlarePostProcess = null;
  83760. this.lensFlareComposePostProcess = null;
  83761. this.luminancePostProcess = null;
  83762. this.hdrPostProcess = null;
  83763. this.hdrFinalPostProcess = null;
  83764. this.depthOfFieldPostProcess = null;
  83765. this.motionBlurPostProcess = null;
  83766. this.fxaaPostProcess = null;
  83767. this.luminanceDownSamplePostProcesses = [];
  83768. this.blurHPostProcesses = [];
  83769. this.blurVPostProcesses = [];
  83770. };
  83771. /**
  83772. * Dispose of the pipeline and stop all post processes
  83773. */
  83774. StandardRenderingPipeline.prototype.dispose = function () {
  83775. this._disposePostProcesses();
  83776. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83777. _super.prototype.dispose.call(this);
  83778. };
  83779. /**
  83780. * Serialize the rendering pipeline (Used when exporting)
  83781. * @returns the serialized object
  83782. */
  83783. StandardRenderingPipeline.prototype.serialize = function () {
  83784. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83785. if (this.sourceLight) {
  83786. serializationObject.sourceLightId = this.sourceLight.id;
  83787. }
  83788. serializationObject.customType = "StandardRenderingPipeline";
  83789. return serializationObject;
  83790. };
  83791. /**
  83792. * Parse the serialized pipeline
  83793. * @param source Source pipeline.
  83794. * @param scene The scene to load the pipeline to.
  83795. * @param rootUrl The URL of the serialized pipeline.
  83796. * @returns An instantiated pipeline from the serialized object.
  83797. */
  83798. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83799. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83800. if (source.sourceLightId) {
  83801. p.sourceLight = scene.getLightByID(source.sourceLightId);
  83802. }
  83803. return p;
  83804. };
  83805. // Luminance steps
  83806. StandardRenderingPipeline.LuminanceSteps = 6;
  83807. __decorate([
  83808. BABYLON.serialize()
  83809. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  83810. __decorate([
  83811. BABYLON.serialize()
  83812. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  83813. __decorate([
  83814. BABYLON.serialize()
  83815. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  83816. __decorate([
  83817. BABYLON.serialize()
  83818. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  83819. __decorate([
  83820. BABYLON.serializeAsTexture("lensTexture")
  83821. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  83822. __decorate([
  83823. BABYLON.serialize()
  83824. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  83825. __decorate([
  83826. BABYLON.serialize()
  83827. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  83828. __decorate([
  83829. BABYLON.serialize()
  83830. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  83831. __decorate([
  83832. BABYLON.serialize()
  83833. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  83834. __decorate([
  83835. BABYLON.serialize()
  83836. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  83837. __decorate([
  83838. BABYLON.serialize()
  83839. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  83840. __decorate([
  83841. BABYLON.serializeAsTexture("lensColorTexture")
  83842. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  83843. __decorate([
  83844. BABYLON.serialize()
  83845. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  83846. __decorate([
  83847. BABYLON.serialize()
  83848. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  83849. __decorate([
  83850. BABYLON.serialize()
  83851. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  83852. __decorate([
  83853. BABYLON.serialize()
  83854. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  83855. __decorate([
  83856. BABYLON.serializeAsTexture("lensStarTexture")
  83857. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  83858. __decorate([
  83859. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  83860. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  83861. __decorate([
  83862. BABYLON.serialize()
  83863. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  83864. __decorate([
  83865. BABYLON.serialize()
  83866. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  83867. __decorate([
  83868. BABYLON.serialize()
  83869. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  83870. __decorate([
  83871. BABYLON.serialize()
  83872. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  83873. __decorate([
  83874. BABYLON.serialize()
  83875. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  83876. __decorate([
  83877. BABYLON.serialize()
  83878. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  83879. __decorate([
  83880. BABYLON.serialize()
  83881. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  83882. __decorate([
  83883. BABYLON.serialize()
  83884. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  83885. __decorate([
  83886. BABYLON.serialize()
  83887. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  83888. __decorate([
  83889. BABYLON.serialize()
  83890. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  83891. __decorate([
  83892. BABYLON.serialize()
  83893. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  83894. __decorate([
  83895. BABYLON.serialize()
  83896. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  83897. __decorate([
  83898. BABYLON.serialize()
  83899. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  83900. __decorate([
  83901. BABYLON.serialize()
  83902. ], StandardRenderingPipeline.prototype, "samples", null);
  83903. return StandardRenderingPipeline;
  83904. }(BABYLON.PostProcessRenderPipeline));
  83905. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  83906. })(BABYLON || (BABYLON = {}));
  83907. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  83908. var BABYLON;
  83909. (function (BABYLON) {
  83910. var FxaaPostProcess = /** @class */ (function (_super) {
  83911. __extends(FxaaPostProcess, _super);
  83912. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83913. if (camera === void 0) { camera = null; }
  83914. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83915. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  83916. var defines = _this._getDefines();
  83917. _this.updateEffect(defines);
  83918. _this.onApplyObservable.add(function (effect) {
  83919. var texelSize = _this.texelSize;
  83920. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  83921. });
  83922. return _this;
  83923. }
  83924. FxaaPostProcess.prototype._getDefines = function () {
  83925. var engine = this.getEngine();
  83926. if (!engine) {
  83927. return null;
  83928. }
  83929. var glInfo = engine.getGlInfo();
  83930. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  83931. return "#define MALI 1\n";
  83932. }
  83933. return null;
  83934. };
  83935. return FxaaPostProcess;
  83936. }(BABYLON.PostProcess));
  83937. BABYLON.FxaaPostProcess = FxaaPostProcess;
  83938. })(BABYLON || (BABYLON = {}));
  83939. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  83940. var BABYLON;
  83941. (function (BABYLON) {
  83942. /**
  83943. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  83944. */
  83945. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  83946. __extends(ChromaticAberrationPostProcess, _super);
  83947. /**
  83948. * Creates a new instance ChromaticAberrationPostProcess
  83949. * @param name The name of the effect.
  83950. * @param screenWidth The width of the screen to apply the effect on.
  83951. * @param screenHeight The height of the screen to apply the effect on.
  83952. * @param options The required width/height ratio to downsize to before computing the render pass.
  83953. * @param camera The camera to apply the render pass to.
  83954. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83955. * @param engine The engine which the post process will be applied. (default: current engine)
  83956. * @param reusable If the post process can be reused on the same frame. (default: false)
  83957. * @param textureType Type of textures used when performing the post process. (default: 0)
  83958. * @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)
  83959. */
  83960. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83961. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83962. if (blockCompilation === void 0) { blockCompilation = false; }
  83963. 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;
  83964. /**
  83965. * The amount of seperation of rgb channels (default: 30)
  83966. */
  83967. _this.aberrationAmount = 30;
  83968. /**
  83969. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  83970. */
  83971. _this.radialIntensity = 0;
  83972. /**
  83973. * 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))
  83974. */
  83975. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  83976. /**
  83977. * 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))
  83978. */
  83979. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  83980. _this.onApplyObservable.add(function (effect) {
  83981. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  83982. effect.setFloat('screen_width', screenWidth);
  83983. effect.setFloat('screen_height', screenHeight);
  83984. effect.setFloat('radialIntensity', _this.radialIntensity);
  83985. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  83986. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  83987. });
  83988. return _this;
  83989. }
  83990. return ChromaticAberrationPostProcess;
  83991. }(BABYLON.PostProcess));
  83992. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  83993. })(BABYLON || (BABYLON = {}));
  83994. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  83995. var BABYLON;
  83996. (function (BABYLON) {
  83997. /**
  83998. * The GrainPostProcess adds noise to the image at mid luminance levels
  83999. */
  84000. var GrainPostProcess = /** @class */ (function (_super) {
  84001. __extends(GrainPostProcess, _super);
  84002. /**
  84003. * Creates a new instance of @see GrainPostProcess
  84004. * @param name The name of the effect.
  84005. * @param options The required width/height ratio to downsize to before computing the render pass.
  84006. * @param camera The camera to apply the render pass to.
  84007. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84008. * @param engine The engine which the post process will be applied. (default: current engine)
  84009. * @param reusable If the post process can be reused on the same frame. (default: false)
  84010. * @param textureType Type of textures used when performing the post process. (default: 0)
  84011. * @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)
  84012. */
  84013. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84014. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84015. if (blockCompilation === void 0) { blockCompilation = false; }
  84016. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84017. /**
  84018. * The intensity of the grain added (default: 30)
  84019. */
  84020. _this.intensity = 30;
  84021. /**
  84022. * If the grain should be randomized on every frame
  84023. */
  84024. _this.animated = false;
  84025. _this.onApplyObservable.add(function (effect) {
  84026. effect.setFloat('intensity', _this.intensity);
  84027. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  84028. });
  84029. return _this;
  84030. }
  84031. return GrainPostProcess;
  84032. }(BABYLON.PostProcess));
  84033. BABYLON.GrainPostProcess = GrainPostProcess;
  84034. })(BABYLON || (BABYLON = {}));
  84035. //# sourceMappingURL=babylon.grainPostProcess.js.map
  84036. var BABYLON;
  84037. (function (BABYLON) {
  84038. /**
  84039. * The SharpenPostProcess applies a sharpen kernel to every pixel
  84040. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84041. */
  84042. var SharpenPostProcess = /** @class */ (function (_super) {
  84043. __extends(SharpenPostProcess, _super);
  84044. /**
  84045. * Creates a new instance ConvolutionPostProcess
  84046. * @param name The name of the effect.
  84047. * @param options The required width/height ratio to downsize to before computing the render pass.
  84048. * @param camera The camera to apply the render pass to.
  84049. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84050. * @param engine The engine which the post process will be applied. (default: current engine)
  84051. * @param reusable If the post process can be reused on the same frame. (default: false)
  84052. * @param textureType Type of textures used when performing the post process. (default: 0)
  84053. * @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)
  84054. */
  84055. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84056. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84057. if (blockCompilation === void 0) { blockCompilation = false; }
  84058. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84059. /**
  84060. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  84061. */
  84062. _this.colorAmount = 1.0;
  84063. /**
  84064. * How much sharpness should be applied (default: 0.3)
  84065. */
  84066. _this.edgeAmount = 0.3;
  84067. _this.onApply = function (effect) {
  84068. effect.setFloat2("screenSize", _this.width, _this.height);
  84069. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  84070. };
  84071. return _this;
  84072. }
  84073. return SharpenPostProcess;
  84074. }(BABYLON.PostProcess));
  84075. BABYLON.SharpenPostProcess = SharpenPostProcess;
  84076. })(BABYLON || (BABYLON = {}));
  84077. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  84078. var BABYLON;
  84079. (function (BABYLON) {
  84080. /**
  84081. * The Blur Post Process which blurs an image based on a kernel and direction.
  84082. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  84083. */
  84084. var BlurPostProcess = /** @class */ (function (_super) {
  84085. __extends(BlurPostProcess, _super);
  84086. /**
  84087. * Creates a new instance BlurPostProcess
  84088. * @param name The name of the effect.
  84089. * @param direction The direction in which to blur the image.
  84090. * @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.
  84091. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  84092. * @param camera The camera to apply the render pass to.
  84093. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84094. * @param engine The engine which the post process will be applied. (default: current engine)
  84095. * @param reusable If the post process can be reused on the same frame. (default: false)
  84096. * @param textureType Type of textures used when performing the post process. (default: 0)
  84097. * @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)
  84098. */
  84099. function BlurPostProcess(name,
  84100. /** The direction in which to blur the image. */
  84101. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  84102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84103. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84104. if (defines === void 0) { defines = ""; }
  84105. if (blockCompilation === void 0) { blockCompilation = false; }
  84106. 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;
  84107. _this.direction = direction;
  84108. _this.blockCompilation = blockCompilation;
  84109. _this._packedFloat = false;
  84110. _this._staticDefines = "";
  84111. _this._staticDefines = defines;
  84112. _this.onApplyObservable.add(function (effect) {
  84113. if (_this._outputTexture) {
  84114. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  84115. }
  84116. else {
  84117. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  84118. }
  84119. });
  84120. _this.kernel = kernel;
  84121. return _this;
  84122. }
  84123. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  84124. /**
  84125. * Gets the length in pixels of the blur sample region
  84126. */
  84127. get: function () {
  84128. return this._idealKernel;
  84129. },
  84130. /**
  84131. * Sets the length in pixels of the blur sample region
  84132. */
  84133. set: function (v) {
  84134. if (this._idealKernel === v) {
  84135. return;
  84136. }
  84137. v = Math.max(v, 1);
  84138. this._idealKernel = v;
  84139. this._kernel = this._nearestBestKernel(v);
  84140. if (!this.blockCompilation) {
  84141. this._updateParameters();
  84142. }
  84143. },
  84144. enumerable: true,
  84145. configurable: true
  84146. });
  84147. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  84148. /**
  84149. * Gets wether or not the blur is unpacking/repacking floats
  84150. */
  84151. get: function () {
  84152. return this._packedFloat;
  84153. },
  84154. /**
  84155. * Sets wether or not the blur needs to unpack/repack floats
  84156. */
  84157. set: function (v) {
  84158. if (this._packedFloat === v) {
  84159. return;
  84160. }
  84161. this._packedFloat = v;
  84162. if (!this.blockCompilation) {
  84163. this._updateParameters();
  84164. }
  84165. },
  84166. enumerable: true,
  84167. configurable: true
  84168. });
  84169. /**
  84170. * Updates the effect with the current post process compile time values and recompiles the shader.
  84171. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84172. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84173. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84174. * @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
  84175. * @param onCompiled Called when the shader has been compiled.
  84176. * @param onError Called if there is an error when compiling a shader.
  84177. */
  84178. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84179. if (defines === void 0) { defines = null; }
  84180. if (uniforms === void 0) { uniforms = null; }
  84181. if (samplers === void 0) { samplers = null; }
  84182. this._updateParameters(onCompiled, onError);
  84183. };
  84184. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  84185. // Generate sampling offsets and weights
  84186. var N = this._kernel;
  84187. var centerIndex = (N - 1) / 2;
  84188. // Generate Gaussian sampling weights over kernel
  84189. var offsets = [];
  84190. var weights = [];
  84191. var totalWeight = 0;
  84192. for (var i = 0; i < N; i++) {
  84193. var u = i / (N - 1);
  84194. var w = this._gaussianWeight(u * 2.0 - 1);
  84195. offsets[i] = (i - centerIndex);
  84196. weights[i] = w;
  84197. totalWeight += w;
  84198. }
  84199. // Normalize weights
  84200. for (var i = 0; i < weights.length; i++) {
  84201. weights[i] /= totalWeight;
  84202. }
  84203. // Optimize: combine samples to take advantage of hardware linear sampling
  84204. // Walk from left to center, combining pairs (symmetrically)
  84205. var linearSamplingWeights = [];
  84206. var linearSamplingOffsets = [];
  84207. var linearSamplingMap = [];
  84208. for (var i = 0; i <= centerIndex; i += 2) {
  84209. var j = Math.min(i + 1, Math.floor(centerIndex));
  84210. var singleCenterSample = i === j;
  84211. if (singleCenterSample) {
  84212. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84213. }
  84214. else {
  84215. var sharedCell = j === centerIndex;
  84216. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  84217. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  84218. if (offsetLinear === 0) {
  84219. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84220. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  84221. }
  84222. else {
  84223. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  84224. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  84225. }
  84226. }
  84227. }
  84228. for (var i = 0; i < linearSamplingMap.length; i++) {
  84229. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  84230. linearSamplingWeights[i] = linearSamplingMap[i].w;
  84231. }
  84232. // Replace with optimized
  84233. offsets = linearSamplingOffsets;
  84234. weights = linearSamplingWeights;
  84235. // Generate shaders
  84236. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  84237. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  84238. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  84239. var defines = "";
  84240. defines += this._staticDefines;
  84241. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  84242. if (this._staticDefines.indexOf("DOF") != -1) {
  84243. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  84244. varyingCount--;
  84245. }
  84246. for (var i = 0; i < varyingCount; i++) {
  84247. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  84248. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  84249. }
  84250. var depCount = 0;
  84251. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  84252. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  84253. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  84254. depCount++;
  84255. }
  84256. if (this.packedFloat) {
  84257. defines += "#define PACKEDFLOAT 1";
  84258. }
  84259. this.blockCompilation = false;
  84260. _super.prototype.updateEffect.call(this, defines, null, null, {
  84261. varyingCount: varyingCount,
  84262. depCount: depCount
  84263. }, onCompiled, onError);
  84264. };
  84265. /**
  84266. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  84267. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  84268. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  84269. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  84270. * The gaps between physical kernels are compensated for in the weighting of the samples
  84271. * @param idealKernel Ideal blur kernel.
  84272. * @return Nearest best kernel.
  84273. */
  84274. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  84275. var v = Math.round(idealKernel);
  84276. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  84277. var k = _a[_i];
  84278. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  84279. return Math.max(k, 3);
  84280. }
  84281. }
  84282. return Math.max(v, 3);
  84283. };
  84284. /**
  84285. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  84286. * @param x The point on the Gaussian distribution to sample.
  84287. * @return the value of the Gaussian function at x.
  84288. */
  84289. BlurPostProcess.prototype._gaussianWeight = function (x) {
  84290. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  84291. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  84292. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  84293. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  84294. // truncated at around 1.3% of peak strength.
  84295. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  84296. var sigma = (1 / 3);
  84297. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  84298. var exponent = -((x * x) / (2.0 * sigma * sigma));
  84299. var weight = (1.0 / denominator) * Math.exp(exponent);
  84300. return weight;
  84301. };
  84302. /**
  84303. * Generates a string that can be used as a floating point number in GLSL.
  84304. * @param x Value to print.
  84305. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  84306. * @return GLSL float string.
  84307. */
  84308. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  84309. if (decimalFigures === void 0) { decimalFigures = 8; }
  84310. return x.toFixed(decimalFigures).replace(/0+$/, '');
  84311. };
  84312. return BlurPostProcess;
  84313. }(BABYLON.PostProcess));
  84314. BABYLON.BlurPostProcess = BlurPostProcess;
  84315. })(BABYLON || (BABYLON = {}));
  84316. //# sourceMappingURL=babylon.blurPostProcess.js.map
  84317. var BABYLON;
  84318. (function (BABYLON) {
  84319. /**
  84320. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  84321. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  84322. * based on samples that have a large difference in distance than the center pixel.
  84323. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  84324. */
  84325. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  84326. __extends(DepthOfFieldBlurPostProcess, _super);
  84327. /**
  84328. * Creates a new instance CircleOfConfusionPostProcess
  84329. * @param name The name of the effect.
  84330. * @param scene The scene the effect belongs to.
  84331. * @param direction The direction the blur should be applied.
  84332. * @param kernel The size of the kernel used to blur.
  84333. * @param options The required width/height ratio to downsize to before computing the render pass.
  84334. * @param camera The camera to apply the render pass to.
  84335. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  84336. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  84337. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84338. * @param engine The engine which the post process will be applied. (default: current engine)
  84339. * @param reusable If the post process can be reused on the same frame. (default: false)
  84340. * @param textureType Type of textures used when performing the post process. (default: 0)
  84341. * @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)
  84342. */
  84343. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  84344. if (imageToBlur === void 0) { imageToBlur = null; }
  84345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84346. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84347. if (blockCompilation === void 0) { blockCompilation = false; }
  84348. 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;
  84349. _this.direction = direction;
  84350. _this.onApplyObservable.add(function (effect) {
  84351. if (imageToBlur != null) {
  84352. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  84353. }
  84354. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  84355. if (scene.activeCamera) {
  84356. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84357. }
  84358. });
  84359. return _this;
  84360. }
  84361. return DepthOfFieldBlurPostProcess;
  84362. }(BABYLON.BlurPostProcess));
  84363. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  84364. })(BABYLON || (BABYLON = {}));
  84365. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  84366. var BABYLON;
  84367. (function (BABYLON) {
  84368. /**
  84369. * Options to be set when merging outputs from the default pipeline.
  84370. */
  84371. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  84372. function DepthOfFieldMergePostProcessOptions() {
  84373. }
  84374. return DepthOfFieldMergePostProcessOptions;
  84375. }());
  84376. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  84377. /**
  84378. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  84379. */
  84380. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  84381. __extends(DepthOfFieldMergePostProcess, _super);
  84382. /**
  84383. * Creates a new instance of DepthOfFieldMergePostProcess
  84384. * @param name The name of the effect.
  84385. * @param originalFromInput Post process which's input will be used for the merge.
  84386. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  84387. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  84388. * @param options The required width/height ratio to downsize to before computing the render pass.
  84389. * @param camera The camera to apply the render pass to.
  84390. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84391. * @param engine The engine which the post process will be applied. (default: current engine)
  84392. * @param reusable If the post process can be reused on the same frame. (default: false)
  84393. * @param textureType Type of textures used when performing the post process. (default: 0)
  84394. * @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)
  84395. */
  84396. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84397. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84398. if (blockCompilation === void 0) { blockCompilation = false; }
  84399. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  84400. _this.blurSteps = blurSteps;
  84401. _this.onApplyObservable.add(function (effect) {
  84402. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  84403. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  84404. blurSteps.forEach(function (step, index) {
  84405. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  84406. });
  84407. });
  84408. if (!blockCompilation) {
  84409. _this.updateEffect();
  84410. }
  84411. return _this;
  84412. }
  84413. /**
  84414. * Updates the effect with the current post process compile time values and recompiles the shader.
  84415. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84416. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84417. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84418. * @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
  84419. * @param onCompiled Called when the shader has been compiled.
  84420. * @param onError Called if there is an error when compiling a shader.
  84421. */
  84422. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84423. if (defines === void 0) { defines = null; }
  84424. if (uniforms === void 0) { uniforms = null; }
  84425. if (samplers === void 0) { samplers = null; }
  84426. if (!defines) {
  84427. defines = "";
  84428. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  84429. }
  84430. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  84431. };
  84432. return DepthOfFieldMergePostProcess;
  84433. }(BABYLON.PostProcess));
  84434. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  84435. })(BABYLON || (BABYLON = {}));
  84436. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  84437. var BABYLON;
  84438. (function (BABYLON) {
  84439. /**
  84440. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  84441. */
  84442. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  84443. __extends(CircleOfConfusionPostProcess, _super);
  84444. /**
  84445. * Creates a new instance CircleOfConfusionPostProcess
  84446. * @param name The name of the effect.
  84447. * @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.
  84448. * @param options The required width/height ratio to downsize to before computing the render pass.
  84449. * @param camera The camera to apply the render pass to.
  84450. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84451. * @param engine The engine which the post process will be applied. (default: current engine)
  84452. * @param reusable If the post process can be reused on the same frame. (default: false)
  84453. * @param textureType Type of textures used when performing the post process. (default: 0)
  84454. * @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)
  84455. */
  84456. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84457. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84458. if (blockCompilation === void 0) { blockCompilation = false; }
  84459. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84460. /**
  84461. * 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.
  84462. */
  84463. _this.lensSize = 50;
  84464. /**
  84465. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  84466. */
  84467. _this.fStop = 1.4;
  84468. /**
  84469. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  84470. */
  84471. _this.focusDistance = 2000;
  84472. /**
  84473. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  84474. */
  84475. _this.focalLength = 50;
  84476. _this._depthTexture = null;
  84477. _this._depthTexture = depthTexture;
  84478. _this.onApplyObservable.add(function (effect) {
  84479. if (!_this._depthTexture) {
  84480. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  84481. return;
  84482. }
  84483. effect.setTexture("depthSampler", _this._depthTexture);
  84484. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  84485. var aperture = _this.lensSize / _this.fStop;
  84486. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  84487. effect.setFloat('focusDistance', _this.focusDistance);
  84488. effect.setFloat('cocPrecalculation', cocPrecalculation);
  84489. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  84490. });
  84491. return _this;
  84492. }
  84493. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  84494. /**
  84495. * 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.
  84496. */
  84497. set: function (value) {
  84498. this._depthTexture = value;
  84499. },
  84500. enumerable: true,
  84501. configurable: true
  84502. });
  84503. return CircleOfConfusionPostProcess;
  84504. }(BABYLON.PostProcess));
  84505. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  84506. })(BABYLON || (BABYLON = {}));
  84507. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  84508. var BABYLON;
  84509. (function (BABYLON) {
  84510. /**
  84511. * Specifies the level of max blur that should be applied when using the depth of field effect
  84512. */
  84513. var DepthOfFieldEffectBlurLevel;
  84514. (function (DepthOfFieldEffectBlurLevel) {
  84515. /**
  84516. * Subtle blur
  84517. */
  84518. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  84519. /**
  84520. * Medium blur
  84521. */
  84522. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  84523. /**
  84524. * Large blur
  84525. */
  84526. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  84527. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  84528. ;
  84529. /**
  84530. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  84531. */
  84532. var DepthOfFieldEffect = /** @class */ (function (_super) {
  84533. __extends(DepthOfFieldEffect, _super);
  84534. /**
  84535. * Creates a new instance DepthOfFieldEffect
  84536. * @param scene The scene the effect belongs to.
  84537. * @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.
  84538. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  84539. * @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)
  84540. */
  84541. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  84542. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  84543. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  84544. if (blockCompilation === void 0) { blockCompilation = false; }
  84545. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  84546. return _this._effects;
  84547. }, true) || this;
  84548. /**
  84549. * @hidden Internal post processes in depth of field effect
  84550. */
  84551. _this._effects = [];
  84552. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  84553. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84554. // 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)
  84555. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  84556. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  84557. _this._depthOfFieldBlurY = [];
  84558. _this._depthOfFieldBlurX = [];
  84559. var blurCount = 1;
  84560. var kernelSize = 15;
  84561. switch (blurLevel) {
  84562. case DepthOfFieldEffectBlurLevel.High: {
  84563. blurCount = 3;
  84564. kernelSize = 51;
  84565. break;
  84566. }
  84567. case DepthOfFieldEffectBlurLevel.Medium: {
  84568. blurCount = 2;
  84569. kernelSize = 31;
  84570. break;
  84571. }
  84572. default: {
  84573. kernelSize = 15;
  84574. blurCount = 1;
  84575. break;
  84576. }
  84577. }
  84578. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  84579. var ratio = 1.0;
  84580. for (var i = 0; i < blurCount; i++) {
  84581. 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);
  84582. blurY.autoClear = false;
  84583. ratio = 0.75 / Math.pow(2, i);
  84584. 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);
  84585. blurX.autoClear = false;
  84586. _this._depthOfFieldBlurY.push(blurY);
  84587. _this._depthOfFieldBlurX.push(blurX);
  84588. }
  84589. // Set all post processes on the effect.
  84590. _this._effects = [_this._circleOfConfusion];
  84591. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  84592. _this._effects.push(_this._depthOfFieldBlurY[i]);
  84593. _this._effects.push(_this._depthOfFieldBlurX[i]);
  84594. }
  84595. // Merge blurred images with original image based on circleOfConfusion
  84596. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84597. _this._dofMerge.autoClear = false;
  84598. _this._effects.push(_this._dofMerge);
  84599. return _this;
  84600. }
  84601. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  84602. get: function () {
  84603. return this._circleOfConfusion.focalLength;
  84604. },
  84605. /**
  84606. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  84607. */
  84608. set: function (value) {
  84609. this._circleOfConfusion.focalLength = value;
  84610. },
  84611. enumerable: true,
  84612. configurable: true
  84613. });
  84614. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  84615. get: function () {
  84616. return this._circleOfConfusion.fStop;
  84617. },
  84618. /**
  84619. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  84620. */
  84621. set: function (value) {
  84622. this._circleOfConfusion.fStop = value;
  84623. },
  84624. enumerable: true,
  84625. configurable: true
  84626. });
  84627. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  84628. get: function () {
  84629. return this._circleOfConfusion.focusDistance;
  84630. },
  84631. /**
  84632. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  84633. */
  84634. set: function (value) {
  84635. this._circleOfConfusion.focusDistance = value;
  84636. },
  84637. enumerable: true,
  84638. configurable: true
  84639. });
  84640. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  84641. get: function () {
  84642. return this._circleOfConfusion.lensSize;
  84643. },
  84644. /**
  84645. * 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.
  84646. */
  84647. set: function (value) {
  84648. this._circleOfConfusion.lensSize = value;
  84649. },
  84650. enumerable: true,
  84651. configurable: true
  84652. });
  84653. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  84654. /**
  84655. * 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.
  84656. */
  84657. set: function (value) {
  84658. this._circleOfConfusion.depthTexture = value;
  84659. },
  84660. enumerable: true,
  84661. configurable: true
  84662. });
  84663. /**
  84664. * Disposes each of the internal effects for a given camera.
  84665. * @param camera The camera to dispose the effect on.
  84666. */
  84667. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  84668. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84669. this._effects[effectIndex].dispose(camera);
  84670. }
  84671. };
  84672. /**
  84673. * @hidden Internal
  84674. */
  84675. DepthOfFieldEffect.prototype._updateEffects = function () {
  84676. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84677. this._effects[effectIndex].updateEffect();
  84678. }
  84679. };
  84680. /**
  84681. * Internal
  84682. * @returns if all the contained post processes are ready.
  84683. * @hidden
  84684. */
  84685. DepthOfFieldEffect.prototype._isReady = function () {
  84686. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84687. if (!this._effects[effectIndex].isReady()) {
  84688. return false;
  84689. }
  84690. }
  84691. return true;
  84692. };
  84693. return DepthOfFieldEffect;
  84694. }(BABYLON.PostProcessRenderEffect));
  84695. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  84696. })(BABYLON || (BABYLON = {}));
  84697. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  84698. var BABYLON;
  84699. (function (BABYLON) {
  84700. /**
  84701. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  84702. */
  84703. var BloomMergePostProcess = /** @class */ (function (_super) {
  84704. __extends(BloomMergePostProcess, _super);
  84705. /**
  84706. * Creates a new instance of @see BloomMergePostProcess
  84707. * @param name The name of the effect.
  84708. * @param originalFromInput Post process which's input will be used for the merge.
  84709. * @param blurred Blurred highlights post process which's output will be used.
  84710. * @param weight Weight of the bloom to be added to the original input.
  84711. * @param options The required width/height ratio to downsize to before computing the render pass.
  84712. * @param camera The camera to apply the render pass to.
  84713. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84714. * @param engine The engine which the post process will be applied. (default: current engine)
  84715. * @param reusable If the post process can be reused on the same frame. (default: false)
  84716. * @param textureType Type of textures used when performing the post process. (default: 0)
  84717. * @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)
  84718. */
  84719. function BloomMergePostProcess(name, originalFromInput, blurred,
  84720. /** Weight of the bloom to be added to the original input. */
  84721. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84722. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84723. if (blockCompilation === void 0) { blockCompilation = false; }
  84724. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  84725. _this.weight = weight;
  84726. _this.onApplyObservable.add(function (effect) {
  84727. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  84728. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  84729. effect.setFloat("bloomWeight", _this.weight);
  84730. });
  84731. if (!blockCompilation) {
  84732. _this.updateEffect();
  84733. }
  84734. return _this;
  84735. }
  84736. return BloomMergePostProcess;
  84737. }(BABYLON.PostProcess));
  84738. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  84739. })(BABYLON || (BABYLON = {}));
  84740. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  84741. var BABYLON;
  84742. (function (BABYLON) {
  84743. /**
  84744. * 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.
  84745. */
  84746. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  84747. __extends(ExtractHighlightsPostProcess, _super);
  84748. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84749. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84750. if (blockCompilation === void 0) { blockCompilation = false; }
  84751. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84752. /**
  84753. * The luminance threshold, pixels below this value will be set to black.
  84754. */
  84755. _this.threshold = 0.9;
  84756. /** @hidden */
  84757. _this._exposure = 1;
  84758. /**
  84759. * Post process which has the input texture to be used when performing highlight extraction
  84760. * @hidden
  84761. */
  84762. _this._inputPostProcess = null;
  84763. _this.onApplyObservable.add(function (effect) {
  84764. if (_this._inputPostProcess) {
  84765. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  84766. }
  84767. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  84768. effect.setFloat('exposure', _this._exposure);
  84769. });
  84770. return _this;
  84771. }
  84772. return ExtractHighlightsPostProcess;
  84773. }(BABYLON.PostProcess));
  84774. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  84775. })(BABYLON || (BABYLON = {}));
  84776. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  84777. var BABYLON;
  84778. (function (BABYLON) {
  84779. /**
  84780. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  84781. */
  84782. var BloomEffect = /** @class */ (function (_super) {
  84783. __extends(BloomEffect, _super);
  84784. /**
  84785. * Creates a new instance of @see BloomEffect
  84786. * @param scene The scene the effect belongs to.
  84787. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  84788. * @param bloomKernel The size of the kernel to be used when applying the blur.
  84789. * @param bloomWeight The the strength of bloom.
  84790. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  84791. * @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)
  84792. */
  84793. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  84794. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  84795. if (blockCompilation === void 0) { blockCompilation = false; }
  84796. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  84797. return _this._effects;
  84798. }, true) || this;
  84799. _this.bloomScale = bloomScale;
  84800. /**
  84801. * @hidden Internal
  84802. */
  84803. _this._effects = [];
  84804. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84805. _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);
  84806. _this._blurX.alwaysForcePOT = true;
  84807. _this._blurX.autoClear = false;
  84808. _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);
  84809. _this._blurY.alwaysForcePOT = true;
  84810. _this._blurY.autoClear = false;
  84811. _this.kernel = bloomKernel;
  84812. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  84813. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84814. _this._merge.autoClear = false;
  84815. _this._effects.push(_this._merge);
  84816. return _this;
  84817. }
  84818. Object.defineProperty(BloomEffect.prototype, "threshold", {
  84819. /**
  84820. * The luminance threshold to find bright areas of the image to bloom.
  84821. */
  84822. get: function () {
  84823. return this._downscale.threshold;
  84824. },
  84825. set: function (value) {
  84826. this._downscale.threshold = value;
  84827. },
  84828. enumerable: true,
  84829. configurable: true
  84830. });
  84831. Object.defineProperty(BloomEffect.prototype, "weight", {
  84832. /**
  84833. * The strength of the bloom.
  84834. */
  84835. get: function () {
  84836. return this._merge.weight;
  84837. },
  84838. set: function (value) {
  84839. this._merge.weight = value;
  84840. },
  84841. enumerable: true,
  84842. configurable: true
  84843. });
  84844. Object.defineProperty(BloomEffect.prototype, "kernel", {
  84845. /**
  84846. * Specifies the size of the bloom blur kernel, relative to the final output size
  84847. */
  84848. get: function () {
  84849. return this._blurX.kernel / this.bloomScale;
  84850. },
  84851. set: function (value) {
  84852. this._blurX.kernel = value * this.bloomScale;
  84853. this._blurY.kernel = value * this.bloomScale;
  84854. },
  84855. enumerable: true,
  84856. configurable: true
  84857. });
  84858. /**
  84859. * Disposes each of the internal effects for a given camera.
  84860. * @param camera The camera to dispose the effect on.
  84861. */
  84862. BloomEffect.prototype.disposeEffects = function (camera) {
  84863. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84864. this._effects[effectIndex].dispose(camera);
  84865. }
  84866. };
  84867. /**
  84868. * @hidden Internal
  84869. */
  84870. BloomEffect.prototype._updateEffects = function () {
  84871. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84872. this._effects[effectIndex].updateEffect();
  84873. }
  84874. };
  84875. /**
  84876. * Internal
  84877. * @returns if all the contained post processes are ready.
  84878. * @hidden
  84879. */
  84880. BloomEffect.prototype._isReady = function () {
  84881. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84882. if (!this._effects[effectIndex].isReady()) {
  84883. return false;
  84884. }
  84885. }
  84886. return true;
  84887. };
  84888. return BloomEffect;
  84889. }(BABYLON.PostProcessRenderEffect));
  84890. BABYLON.BloomEffect = BloomEffect;
  84891. })(BABYLON || (BABYLON = {}));
  84892. //# sourceMappingURL=babylon.bloomEffect.js.map
  84893. var BABYLON;
  84894. (function (BABYLON) {
  84895. /**
  84896. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  84897. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  84898. */
  84899. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  84900. __extends(DefaultRenderingPipeline, _super);
  84901. /**
  84902. * @constructor
  84903. * @param {string} name - The rendering pipeline name (default: "")
  84904. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  84905. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  84906. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  84907. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  84908. */
  84909. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  84910. if (name === void 0) { name = ""; }
  84911. if (hdr === void 0) { hdr = true; }
  84912. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  84913. if (automaticBuild === void 0) { automaticBuild = true; }
  84914. var _this = _super.call(this, scene.getEngine(), name) || this;
  84915. _this._camerasToBeAttached = [];
  84916. /**
  84917. * ID of the sharpen post process,
  84918. */
  84919. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  84920. /**
  84921. * ID of the image processing post process;
  84922. */
  84923. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  84924. /**
  84925. * ID of the Fast Approximate Anti-Aliasing post process;
  84926. */
  84927. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  84928. /**
  84929. * ID of the chromatic aberration post process,
  84930. */
  84931. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  84932. /**
  84933. * ID of the grain post process
  84934. */
  84935. _this.GrainPostProcessId = "GrainPostProcessEffect";
  84936. /**
  84937. * Glow post process which adds a glow to emmisive areas of the image
  84938. */
  84939. _this._glowLayer = null;
  84940. /**
  84941. * Animations which can be used to tweak settings over a period of time
  84942. */
  84943. _this.animations = [];
  84944. _this._imageProcessingConfigurationObserver = null;
  84945. // Values
  84946. _this._sharpenEnabled = false;
  84947. _this._bloomEnabled = false;
  84948. _this._depthOfFieldEnabled = false;
  84949. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  84950. _this._fxaaEnabled = false;
  84951. _this._imageProcessingEnabled = true;
  84952. _this._bloomScale = 0.5;
  84953. _this._chromaticAberrationEnabled = false;
  84954. _this._grainEnabled = false;
  84955. _this._buildAllowed = true;
  84956. _this._resizeObserver = null;
  84957. _this._hardwareScaleLevel = 1.0;
  84958. _this._bloomKernel = 64;
  84959. /**
  84960. * Specifies the weight of the bloom in the final rendering
  84961. */
  84962. _this._bloomWeight = 0.15;
  84963. /**
  84964. * Specifies the luma threshold for the area that will be blurred by the bloom
  84965. */
  84966. _this._bloomThreshold = 0.9;
  84967. _this._samples = 1;
  84968. _this._hasCleared = false;
  84969. _this._prevPostProcess = null;
  84970. _this._prevPrevPostProcess = null;
  84971. _this._depthOfFieldSceneObserver = null;
  84972. _this._cameras = cameras || scene.cameras;
  84973. _this._cameras = _this._cameras.slice();
  84974. _this._camerasToBeAttached = _this._cameras.slice();
  84975. _this._buildAllowed = automaticBuild;
  84976. // Initialize
  84977. _this._scene = scene;
  84978. var caps = _this._scene.getEngine().getCaps();
  84979. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  84980. // Misc
  84981. if (_this._hdr) {
  84982. if (caps.textureHalfFloatRender) {
  84983. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84984. }
  84985. else if (caps.textureFloatRender) {
  84986. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84987. }
  84988. }
  84989. else {
  84990. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84991. }
  84992. // Attach
  84993. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84994. var engine = _this._scene.getEngine();
  84995. // Create post processes before hand so they can be modified before enabled.
  84996. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  84997. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  84998. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  84999. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  85000. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  85001. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85002. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  85003. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85004. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  85005. _this._resizeObserver = engine.onResizeObservable.add(function () {
  85006. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  85007. _this.bloomKernel = _this.bloomKernel;
  85008. });
  85009. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  85010. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  85011. });
  85012. _this._buildPipeline();
  85013. return _this;
  85014. }
  85015. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  85016. get: function () {
  85017. return this._sharpenEnabled;
  85018. },
  85019. /**
  85020. * Enable or disable the sharpen process from the pipeline
  85021. */
  85022. set: function (enabled) {
  85023. if (this._sharpenEnabled === enabled) {
  85024. return;
  85025. }
  85026. this._sharpenEnabled = enabled;
  85027. this._buildPipeline();
  85028. },
  85029. enumerable: true,
  85030. configurable: true
  85031. });
  85032. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  85033. /**
  85034. * Specifies the size of the bloom blur kernel, relative to the final output size
  85035. */
  85036. get: function () {
  85037. return this._bloomKernel;
  85038. },
  85039. set: function (value) {
  85040. this._bloomKernel = value;
  85041. this.bloom.kernel = value / this._hardwareScaleLevel;
  85042. },
  85043. enumerable: true,
  85044. configurable: true
  85045. });
  85046. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  85047. get: function () {
  85048. return this._bloomWeight;
  85049. },
  85050. /**
  85051. * The strength of the bloom.
  85052. */
  85053. set: function (value) {
  85054. if (this._bloomWeight === value) {
  85055. return;
  85056. }
  85057. this.bloom.weight = value;
  85058. this._bloomWeight = value;
  85059. },
  85060. enumerable: true,
  85061. configurable: true
  85062. });
  85063. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  85064. get: function () {
  85065. return this._bloomThreshold;
  85066. },
  85067. /**
  85068. * The strength of the bloom.
  85069. */
  85070. set: function (value) {
  85071. if (this._bloomThreshold === value) {
  85072. return;
  85073. }
  85074. this.bloom.threshold = value;
  85075. this._bloomThreshold = value;
  85076. },
  85077. enumerable: true,
  85078. configurable: true
  85079. });
  85080. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  85081. get: function () {
  85082. return this._bloomScale;
  85083. },
  85084. /**
  85085. * The scale of the bloom, lower value will provide better performance.
  85086. */
  85087. set: function (value) {
  85088. if (this._bloomScale === value) {
  85089. return;
  85090. }
  85091. this._bloomScale = value;
  85092. // recreate bloom and dispose old as this setting is not dynamic
  85093. this._rebuildBloom();
  85094. this._buildPipeline();
  85095. },
  85096. enumerable: true,
  85097. configurable: true
  85098. });
  85099. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  85100. get: function () {
  85101. return this._bloomEnabled;
  85102. },
  85103. /**
  85104. * Enable or disable the bloom from the pipeline
  85105. */
  85106. set: function (enabled) {
  85107. if (this._bloomEnabled === enabled) {
  85108. return;
  85109. }
  85110. this._bloomEnabled = enabled;
  85111. this._buildPipeline();
  85112. },
  85113. enumerable: true,
  85114. configurable: true
  85115. });
  85116. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  85117. // recreate bloom and dispose old as this setting is not dynamic
  85118. var oldBloom = this.bloom;
  85119. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  85120. this.bloom.threshold = oldBloom.threshold;
  85121. for (var i = 0; i < this._cameras.length; i++) {
  85122. oldBloom.disposeEffects(this._cameras[i]);
  85123. }
  85124. };
  85125. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  85126. /**
  85127. * If the depth of field is enabled.
  85128. */
  85129. get: function () {
  85130. return this._depthOfFieldEnabled;
  85131. },
  85132. set: function (enabled) {
  85133. if (this._depthOfFieldEnabled === enabled) {
  85134. return;
  85135. }
  85136. this._depthOfFieldEnabled = enabled;
  85137. this._buildPipeline();
  85138. },
  85139. enumerable: true,
  85140. configurable: true
  85141. });
  85142. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  85143. /**
  85144. * Blur level of the depth of field effect. (Higher blur will effect performance)
  85145. */
  85146. get: function () {
  85147. return this._depthOfFieldBlurLevel;
  85148. },
  85149. set: function (value) {
  85150. if (this._depthOfFieldBlurLevel === value) {
  85151. return;
  85152. }
  85153. this._depthOfFieldBlurLevel = value;
  85154. // recreate dof and dispose old as this setting is not dynamic
  85155. var oldDof = this.depthOfField;
  85156. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  85157. this.depthOfField.focalLength = oldDof.focalLength;
  85158. this.depthOfField.focusDistance = oldDof.focusDistance;
  85159. this.depthOfField.fStop = oldDof.fStop;
  85160. this.depthOfField.lensSize = oldDof.lensSize;
  85161. for (var i = 0; i < this._cameras.length; i++) {
  85162. oldDof.disposeEffects(this._cameras[i]);
  85163. }
  85164. this._buildPipeline();
  85165. },
  85166. enumerable: true,
  85167. configurable: true
  85168. });
  85169. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  85170. get: function () {
  85171. return this._fxaaEnabled;
  85172. },
  85173. /**
  85174. * If the anti aliasing is enabled.
  85175. */
  85176. set: function (enabled) {
  85177. if (this._fxaaEnabled === enabled) {
  85178. return;
  85179. }
  85180. this._fxaaEnabled = enabled;
  85181. this._buildPipeline();
  85182. },
  85183. enumerable: true,
  85184. configurable: true
  85185. });
  85186. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  85187. get: function () {
  85188. return this._samples;
  85189. },
  85190. /**
  85191. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85192. */
  85193. set: function (sampleCount) {
  85194. if (this._samples === sampleCount) {
  85195. return;
  85196. }
  85197. this._samples = sampleCount;
  85198. this._buildPipeline();
  85199. },
  85200. enumerable: true,
  85201. configurable: true
  85202. });
  85203. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  85204. get: function () {
  85205. return this._imageProcessingEnabled;
  85206. },
  85207. /**
  85208. * If image processing is enabled.
  85209. */
  85210. set: function (enabled) {
  85211. if (this._imageProcessingEnabled === enabled) {
  85212. return;
  85213. }
  85214. this._imageProcessingEnabled = enabled;
  85215. this._buildPipeline();
  85216. },
  85217. enumerable: true,
  85218. configurable: true
  85219. });
  85220. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  85221. get: function () {
  85222. return this._glowLayer == null;
  85223. },
  85224. /**
  85225. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  85226. */
  85227. set: function (enabled) {
  85228. if (enabled && !this._glowLayer) {
  85229. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  85230. }
  85231. else if (!enabled && this._glowLayer) {
  85232. this._glowLayer.dispose();
  85233. this._glowLayer = null;
  85234. }
  85235. },
  85236. enumerable: true,
  85237. configurable: true
  85238. });
  85239. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  85240. get: function () {
  85241. return this._chromaticAberrationEnabled;
  85242. },
  85243. /**
  85244. * Enable or disable the chromaticAberration process from the pipeline
  85245. */
  85246. set: function (enabled) {
  85247. if (this._chromaticAberrationEnabled === enabled) {
  85248. return;
  85249. }
  85250. this._chromaticAberrationEnabled = enabled;
  85251. this._buildPipeline();
  85252. },
  85253. enumerable: true,
  85254. configurable: true
  85255. });
  85256. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  85257. get: function () {
  85258. return this._grainEnabled;
  85259. },
  85260. /**
  85261. * Enable or disable the grain process from the pipeline
  85262. */
  85263. set: function (enabled) {
  85264. if (this._grainEnabled === enabled) {
  85265. return;
  85266. }
  85267. this._grainEnabled = enabled;
  85268. this._buildPipeline();
  85269. },
  85270. enumerable: true,
  85271. configurable: true
  85272. });
  85273. /**
  85274. * Force the compilation of the entire pipeline.
  85275. */
  85276. DefaultRenderingPipeline.prototype.prepare = function () {
  85277. var previousState = this._buildAllowed;
  85278. this._buildAllowed = true;
  85279. this._buildPipeline();
  85280. this._buildAllowed = previousState;
  85281. };
  85282. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  85283. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  85284. if (this._hasCleared) {
  85285. postProcess.autoClear = false;
  85286. }
  85287. else {
  85288. postProcess.autoClear = true;
  85289. this._scene.autoClear = false;
  85290. this._hasCleared = true;
  85291. }
  85292. if (!skipTextureSharing) {
  85293. if (this._prevPrevPostProcess) {
  85294. postProcess.shareOutputWith(this._prevPrevPostProcess);
  85295. }
  85296. else {
  85297. postProcess.useOwnOutput();
  85298. }
  85299. if (this._prevPostProcess) {
  85300. this._prevPrevPostProcess = this._prevPostProcess;
  85301. }
  85302. this._prevPostProcess = postProcess;
  85303. }
  85304. };
  85305. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  85306. var _this = this;
  85307. if (!this._buildAllowed) {
  85308. return;
  85309. }
  85310. this._scene.autoClear = true;
  85311. var engine = this._scene.getEngine();
  85312. this._disposePostProcesses();
  85313. if (this._cameras !== null) {
  85314. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85315. // get back cameras to be used to reattach pipeline
  85316. this._cameras = this._camerasToBeAttached.slice();
  85317. }
  85318. this._reset();
  85319. this._prevPostProcess = null;
  85320. this._prevPrevPostProcess = null;
  85321. this._hasCleared = false;
  85322. if (this.depthOfFieldEnabled) {
  85323. // Multi camera suport
  85324. if (this._cameras.length > 1) {
  85325. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  85326. var camera = _a[_i];
  85327. var depthRenderer = this._scene.enableDepthRenderer(camera);
  85328. depthRenderer.useOnlyInActiveCamera = true;
  85329. }
  85330. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  85331. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  85332. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  85333. }
  85334. });
  85335. }
  85336. else {
  85337. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  85338. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  85339. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  85340. }
  85341. if (!this.depthOfField._isReady()) {
  85342. this.depthOfField._updateEffects();
  85343. }
  85344. this.addEffect(this.depthOfField);
  85345. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  85346. }
  85347. else {
  85348. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  85349. }
  85350. if (this.bloomEnabled) {
  85351. if (!this.bloom._isReady()) {
  85352. this.bloom._updateEffects();
  85353. }
  85354. this.addEffect(this.bloom);
  85355. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  85356. }
  85357. if (this._imageProcessingEnabled) {
  85358. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  85359. if (this._hdr) {
  85360. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  85361. this._setAutoClearAndTextureSharing(this.imageProcessing);
  85362. }
  85363. else {
  85364. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  85365. }
  85366. }
  85367. if (this.sharpenEnabled) {
  85368. if (!this.sharpen.isReady()) {
  85369. this.sharpen.updateEffect();
  85370. }
  85371. this.addEffect(this._sharpenEffect);
  85372. this._setAutoClearAndTextureSharing(this.sharpen);
  85373. }
  85374. if (this.grainEnabled) {
  85375. if (!this.grain.isReady()) {
  85376. this.grain.updateEffect();
  85377. }
  85378. this.addEffect(this._grainEffect);
  85379. this._setAutoClearAndTextureSharing(this.grain);
  85380. }
  85381. if (this.chromaticAberrationEnabled) {
  85382. if (!this.chromaticAberration.isReady()) {
  85383. this.chromaticAberration.updateEffect();
  85384. }
  85385. this.addEffect(this._chromaticAberrationEffect);
  85386. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  85387. }
  85388. if (this.fxaaEnabled) {
  85389. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  85390. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  85391. this._setAutoClearAndTextureSharing(this.fxaa, true);
  85392. }
  85393. if (this._cameras !== null) {
  85394. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85395. }
  85396. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  85397. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85398. }
  85399. };
  85400. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  85401. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  85402. for (var i = 0; i < this._cameras.length; i++) {
  85403. var camera = this._cameras[i];
  85404. if (this.imageProcessing) {
  85405. this.imageProcessing.dispose(camera);
  85406. }
  85407. if (this.fxaa) {
  85408. this.fxaa.dispose(camera);
  85409. }
  85410. // These are created in the constructor and should not be disposed on every pipeline change
  85411. if (disposeNonRecreated) {
  85412. if (this.sharpen) {
  85413. this.sharpen.dispose(camera);
  85414. }
  85415. if (this.depthOfField) {
  85416. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  85417. this.depthOfField.disposeEffects(camera);
  85418. }
  85419. if (this.bloom) {
  85420. this.bloom.disposeEffects(camera);
  85421. }
  85422. if (this.chromaticAberration) {
  85423. this.chromaticAberration.dispose(camera);
  85424. }
  85425. if (this.grain) {
  85426. this.grain.dispose(camera);
  85427. }
  85428. if (this._glowLayer) {
  85429. this._glowLayer.dispose();
  85430. }
  85431. }
  85432. }
  85433. this.imageProcessing = null;
  85434. this.fxaa = null;
  85435. if (disposeNonRecreated) {
  85436. this.sharpen = null;
  85437. this._sharpenEffect = null;
  85438. this.depthOfField = null;
  85439. this.bloom = null;
  85440. this.chromaticAberration = null;
  85441. this._chromaticAberrationEffect = null;
  85442. this.grain = null;
  85443. this._grainEffect = null;
  85444. this._glowLayer = null;
  85445. }
  85446. };
  85447. /**
  85448. * Adds a camera to the pipeline
  85449. * @param camera the camera to be added
  85450. */
  85451. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  85452. this._camerasToBeAttached.push(camera);
  85453. this._buildPipeline();
  85454. };
  85455. /**
  85456. * Removes a camera from the pipeline
  85457. * @param camera the camera to remove
  85458. */
  85459. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  85460. var index = this._camerasToBeAttached.indexOf(camera);
  85461. this._camerasToBeAttached.splice(index, 1);
  85462. this._buildPipeline();
  85463. };
  85464. /**
  85465. * Dispose of the pipeline and stop all post processes
  85466. */
  85467. DefaultRenderingPipeline.prototype.dispose = function () {
  85468. this._disposePostProcesses(true);
  85469. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85470. this._scene.autoClear = true;
  85471. if (this._resizeObserver) {
  85472. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  85473. this._resizeObserver = null;
  85474. }
  85475. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  85476. _super.prototype.dispose.call(this);
  85477. };
  85478. /**
  85479. * Serialize the rendering pipeline (Used when exporting)
  85480. * @returns the serialized object
  85481. */
  85482. DefaultRenderingPipeline.prototype.serialize = function () {
  85483. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85484. serializationObject.customType = "DefaultRenderingPipeline";
  85485. return serializationObject;
  85486. };
  85487. /**
  85488. * Parse the serialized pipeline
  85489. * @param source Source pipeline.
  85490. * @param scene The scene to load the pipeline to.
  85491. * @param rootUrl The URL of the serialized pipeline.
  85492. * @returns An instantiated pipeline from the serialized object.
  85493. */
  85494. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85495. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  85496. };
  85497. __decorate([
  85498. BABYLON.serialize()
  85499. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  85500. __decorate([
  85501. BABYLON.serialize()
  85502. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  85503. __decorate([
  85504. BABYLON.serialize()
  85505. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  85506. __decorate([
  85507. BABYLON.serialize()
  85508. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  85509. __decorate([
  85510. BABYLON.serialize()
  85511. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  85512. __decorate([
  85513. BABYLON.serialize()
  85514. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  85515. __decorate([
  85516. BABYLON.serialize()
  85517. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  85518. __decorate([
  85519. BABYLON.serialize()
  85520. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  85521. __decorate([
  85522. BABYLON.serialize()
  85523. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  85524. __decorate([
  85525. BABYLON.serialize()
  85526. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  85527. __decorate([
  85528. BABYLON.serialize()
  85529. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  85530. __decorate([
  85531. BABYLON.serialize()
  85532. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  85533. __decorate([
  85534. BABYLON.serialize()
  85535. ], DefaultRenderingPipeline.prototype, "samples", null);
  85536. __decorate([
  85537. BABYLON.serialize()
  85538. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  85539. __decorate([
  85540. BABYLON.serialize()
  85541. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  85542. __decorate([
  85543. BABYLON.serialize()
  85544. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  85545. __decorate([
  85546. BABYLON.serialize()
  85547. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  85548. return DefaultRenderingPipeline;
  85549. }(BABYLON.PostProcessRenderPipeline));
  85550. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  85551. })(BABYLON || (BABYLON = {}));
  85552. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  85553. var BABYLON;
  85554. (function (BABYLON) {
  85555. /**
  85556. * @hidden
  85557. */
  85558. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  85559. __extends(ImageProcessingConfigurationDefines, _super);
  85560. function ImageProcessingConfigurationDefines() {
  85561. var _this = _super.call(this) || this;
  85562. _this.IMAGEPROCESSING = false;
  85563. _this.VIGNETTE = false;
  85564. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  85565. _this.VIGNETTEBLENDMODEOPAQUE = false;
  85566. _this.TONEMAPPING = false;
  85567. _this.TONEMAPPING_ACES = false;
  85568. _this.CONTRAST = false;
  85569. _this.COLORCURVES = false;
  85570. _this.COLORGRADING = false;
  85571. _this.COLORGRADING3D = false;
  85572. _this.SAMPLER3DGREENDEPTH = false;
  85573. _this.SAMPLER3DBGRMAP = false;
  85574. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  85575. _this.EXPOSURE = false;
  85576. _this.rebuild();
  85577. return _this;
  85578. }
  85579. return ImageProcessingConfigurationDefines;
  85580. }(BABYLON.MaterialDefines));
  85581. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  85582. /**
  85583. * This groups together the common properties used for image processing either in direct forward pass
  85584. * or through post processing effect depending on the use of the image processing pipeline in your scene
  85585. * or not.
  85586. */
  85587. var ImageProcessingConfiguration = /** @class */ (function () {
  85588. function ImageProcessingConfiguration() {
  85589. /**
  85590. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  85591. */
  85592. this.colorCurves = new BABYLON.ColorCurves();
  85593. this._colorCurvesEnabled = false;
  85594. this._colorGradingEnabled = false;
  85595. this._colorGradingWithGreenDepth = true;
  85596. this._colorGradingBGR = true;
  85597. /** @hidden */
  85598. this._exposure = 1.0;
  85599. this._toneMappingEnabled = false;
  85600. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  85601. this._contrast = 1.0;
  85602. /**
  85603. * Vignette stretch size.
  85604. */
  85605. this.vignetteStretch = 0;
  85606. /**
  85607. * Vignette centre X Offset.
  85608. */
  85609. this.vignetteCentreX = 0;
  85610. /**
  85611. * Vignette centre Y Offset.
  85612. */
  85613. this.vignetteCentreY = 0;
  85614. /**
  85615. * Vignette weight or intensity of the vignette effect.
  85616. */
  85617. this.vignetteWeight = 1.5;
  85618. /**
  85619. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  85620. * if vignetteEnabled is set to true.
  85621. */
  85622. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  85623. /**
  85624. * Camera field of view used by the Vignette effect.
  85625. */
  85626. this.vignetteCameraFov = 0.5;
  85627. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  85628. this._vignetteEnabled = false;
  85629. this._applyByPostProcess = false;
  85630. this._isEnabled = true;
  85631. /**
  85632. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  85633. */
  85634. this.onUpdateParameters = new BABYLON.Observable();
  85635. }
  85636. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  85637. /**
  85638. * Gets wether the color curves effect is enabled.
  85639. */
  85640. get: function () {
  85641. return this._colorCurvesEnabled;
  85642. },
  85643. /**
  85644. * Sets wether the color curves effect is enabled.
  85645. */
  85646. set: function (value) {
  85647. if (this._colorCurvesEnabled === value) {
  85648. return;
  85649. }
  85650. this._colorCurvesEnabled = value;
  85651. this._updateParameters();
  85652. },
  85653. enumerable: true,
  85654. configurable: true
  85655. });
  85656. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  85657. /**
  85658. * Gets wether the color grading effect is enabled.
  85659. */
  85660. get: function () {
  85661. return this._colorGradingEnabled;
  85662. },
  85663. /**
  85664. * Sets wether the color grading effect is enabled.
  85665. */
  85666. set: function (value) {
  85667. if (this._colorGradingEnabled === value) {
  85668. return;
  85669. }
  85670. this._colorGradingEnabled = value;
  85671. this._updateParameters();
  85672. },
  85673. enumerable: true,
  85674. configurable: true
  85675. });
  85676. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  85677. /**
  85678. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  85679. */
  85680. get: function () {
  85681. return this._colorGradingWithGreenDepth;
  85682. },
  85683. /**
  85684. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  85685. */
  85686. set: function (value) {
  85687. if (this._colorGradingWithGreenDepth === value) {
  85688. return;
  85689. }
  85690. this._colorGradingWithGreenDepth = value;
  85691. this._updateParameters();
  85692. },
  85693. enumerable: true,
  85694. configurable: true
  85695. });
  85696. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  85697. /**
  85698. * Gets wether the color grading texture contains BGR values.
  85699. */
  85700. get: function () {
  85701. return this._colorGradingBGR;
  85702. },
  85703. /**
  85704. * Sets wether the color grading texture contains BGR values.
  85705. */
  85706. set: function (value) {
  85707. if (this._colorGradingBGR === value) {
  85708. return;
  85709. }
  85710. this._colorGradingBGR = value;
  85711. this._updateParameters();
  85712. },
  85713. enumerable: true,
  85714. configurable: true
  85715. });
  85716. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  85717. /**
  85718. * Gets the Exposure used in the effect.
  85719. */
  85720. get: function () {
  85721. return this._exposure;
  85722. },
  85723. /**
  85724. * Sets the Exposure used in the effect.
  85725. */
  85726. set: function (value) {
  85727. if (this._exposure === value) {
  85728. return;
  85729. }
  85730. this._exposure = value;
  85731. this._updateParameters();
  85732. },
  85733. enumerable: true,
  85734. configurable: true
  85735. });
  85736. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  85737. /**
  85738. * Gets wether the tone mapping effect is enabled.
  85739. */
  85740. get: function () {
  85741. return this._toneMappingEnabled;
  85742. },
  85743. /**
  85744. * Sets wether the tone mapping effect is enabled.
  85745. */
  85746. set: function (value) {
  85747. if (this._toneMappingEnabled === value) {
  85748. return;
  85749. }
  85750. this._toneMappingEnabled = value;
  85751. this._updateParameters();
  85752. },
  85753. enumerable: true,
  85754. configurable: true
  85755. });
  85756. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  85757. /**
  85758. * Gets the type of tone mapping effect.
  85759. */
  85760. get: function () {
  85761. return this._toneMappingType;
  85762. },
  85763. /**
  85764. * Sets the type of tone mapping effect used in BabylonJS.
  85765. */
  85766. set: function (value) {
  85767. if (this._toneMappingType === value) {
  85768. return;
  85769. }
  85770. this._toneMappingType = value;
  85771. this._updateParameters();
  85772. },
  85773. enumerable: true,
  85774. configurable: true
  85775. });
  85776. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  85777. /**
  85778. * Gets the contrast used in the effect.
  85779. */
  85780. get: function () {
  85781. return this._contrast;
  85782. },
  85783. /**
  85784. * Sets the contrast used in the effect.
  85785. */
  85786. set: function (value) {
  85787. if (this._contrast === value) {
  85788. return;
  85789. }
  85790. this._contrast = value;
  85791. this._updateParameters();
  85792. },
  85793. enumerable: true,
  85794. configurable: true
  85795. });
  85796. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  85797. /**
  85798. * Gets the vignette blend mode allowing different kind of effect.
  85799. */
  85800. get: function () {
  85801. return this._vignetteBlendMode;
  85802. },
  85803. /**
  85804. * Sets the vignette blend mode allowing different kind of effect.
  85805. */
  85806. set: function (value) {
  85807. if (this._vignetteBlendMode === value) {
  85808. return;
  85809. }
  85810. this._vignetteBlendMode = value;
  85811. this._updateParameters();
  85812. },
  85813. enumerable: true,
  85814. configurable: true
  85815. });
  85816. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  85817. /**
  85818. * Gets wether the vignette effect is enabled.
  85819. */
  85820. get: function () {
  85821. return this._vignetteEnabled;
  85822. },
  85823. /**
  85824. * Sets wether the vignette effect is enabled.
  85825. */
  85826. set: function (value) {
  85827. if (this._vignetteEnabled === value) {
  85828. return;
  85829. }
  85830. this._vignetteEnabled = value;
  85831. this._updateParameters();
  85832. },
  85833. enumerable: true,
  85834. configurable: true
  85835. });
  85836. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  85837. /**
  85838. * Gets wether the image processing is applied through a post process or not.
  85839. */
  85840. get: function () {
  85841. return this._applyByPostProcess;
  85842. },
  85843. /**
  85844. * Sets wether the image processing is applied through a post process or not.
  85845. */
  85846. set: function (value) {
  85847. if (this._applyByPostProcess === value) {
  85848. return;
  85849. }
  85850. this._applyByPostProcess = value;
  85851. this._updateParameters();
  85852. },
  85853. enumerable: true,
  85854. configurable: true
  85855. });
  85856. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  85857. /**
  85858. * Gets wether the image processing is enabled or not.
  85859. */
  85860. get: function () {
  85861. return this._isEnabled;
  85862. },
  85863. /**
  85864. * Sets wether the image processing is enabled or not.
  85865. */
  85866. set: function (value) {
  85867. if (this._isEnabled === value) {
  85868. return;
  85869. }
  85870. this._isEnabled = value;
  85871. this._updateParameters();
  85872. },
  85873. enumerable: true,
  85874. configurable: true
  85875. });
  85876. /**
  85877. * Method called each time the image processing information changes requires to recompile the effect.
  85878. */
  85879. ImageProcessingConfiguration.prototype._updateParameters = function () {
  85880. this.onUpdateParameters.notifyObservers(this);
  85881. };
  85882. /**
  85883. * Gets the current class name.
  85884. * @return "ImageProcessingConfiguration"
  85885. */
  85886. ImageProcessingConfiguration.prototype.getClassName = function () {
  85887. return "ImageProcessingConfiguration";
  85888. };
  85889. /**
  85890. * Prepare the list of uniforms associated with the Image Processing effects.
  85891. * @param uniforms The list of uniforms used in the effect
  85892. * @param defines the list of defines currently in use
  85893. */
  85894. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  85895. if (defines.EXPOSURE) {
  85896. uniforms.push("exposureLinear");
  85897. }
  85898. if (defines.CONTRAST) {
  85899. uniforms.push("contrast");
  85900. }
  85901. if (defines.COLORGRADING) {
  85902. uniforms.push("colorTransformSettings");
  85903. }
  85904. if (defines.VIGNETTE) {
  85905. uniforms.push("vInverseScreenSize");
  85906. uniforms.push("vignetteSettings1");
  85907. uniforms.push("vignetteSettings2");
  85908. }
  85909. if (defines.COLORCURVES) {
  85910. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  85911. }
  85912. };
  85913. /**
  85914. * Prepare the list of samplers associated with the Image Processing effects.
  85915. * @param samplersList The list of uniforms used in the effect
  85916. * @param defines the list of defines currently in use
  85917. */
  85918. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  85919. if (defines.COLORGRADING) {
  85920. samplersList.push("txColorTransform");
  85921. }
  85922. };
  85923. /**
  85924. * Prepare the list of defines associated to the shader.
  85925. * @param defines the list of defines to complete
  85926. * @param forPostProcess Define if we are currently in post process mode or not
  85927. */
  85928. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  85929. if (forPostProcess === void 0) { forPostProcess = false; }
  85930. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  85931. defines.VIGNETTE = false;
  85932. defines.TONEMAPPING = false;
  85933. defines.TONEMAPPING_ACES = false;
  85934. defines.CONTRAST = false;
  85935. defines.EXPOSURE = false;
  85936. defines.COLORCURVES = false;
  85937. defines.COLORGRADING = false;
  85938. defines.COLORGRADING3D = false;
  85939. defines.IMAGEPROCESSING = false;
  85940. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  85941. return;
  85942. }
  85943. defines.VIGNETTE = this.vignetteEnabled;
  85944. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  85945. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  85946. defines.TONEMAPPING = this.toneMappingEnabled;
  85947. switch (this._toneMappingType) {
  85948. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  85949. defines.TONEMAPPING_ACES = true;
  85950. break;
  85951. }
  85952. defines.CONTRAST = (this.contrast !== 1.0);
  85953. defines.EXPOSURE = (this.exposure !== 1.0);
  85954. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  85955. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  85956. if (defines.COLORGRADING) {
  85957. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  85958. }
  85959. else {
  85960. defines.COLORGRADING3D = false;
  85961. }
  85962. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  85963. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  85964. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  85965. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  85966. };
  85967. /**
  85968. * Returns true if all the image processing information are ready.
  85969. * @returns True if ready, otherwise, false
  85970. */
  85971. ImageProcessingConfiguration.prototype.isReady = function () {
  85972. // Color Grading texure can not be none blocking.
  85973. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  85974. };
  85975. /**
  85976. * Binds the image processing to the shader.
  85977. * @param effect The effect to bind to
  85978. * @param aspectRatio Define the current aspect ratio of the effect
  85979. */
  85980. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  85981. if (aspectRatio === void 0) { aspectRatio = 1; }
  85982. // Color Curves
  85983. if (this._colorCurvesEnabled && this.colorCurves) {
  85984. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  85985. }
  85986. // Vignette
  85987. if (this._vignetteEnabled) {
  85988. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  85989. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  85990. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  85991. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  85992. var vignetteScaleX = vignetteScaleY * aspectRatio;
  85993. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  85994. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  85995. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  85996. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  85997. var vignettePower = -2.0 * this.vignetteWeight;
  85998. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  85999. }
  86000. // Exposure
  86001. effect.setFloat("exposureLinear", this.exposure);
  86002. // Contrast
  86003. effect.setFloat("contrast", this.contrast);
  86004. // Color transform settings
  86005. if (this.colorGradingTexture) {
  86006. effect.setTexture("txColorTransform", this.colorGradingTexture);
  86007. var textureSize = this.colorGradingTexture.getSize().height;
  86008. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  86009. 0.5 / textureSize, // textureOffset
  86010. textureSize, // textureSize
  86011. this.colorGradingTexture.level // weight
  86012. );
  86013. }
  86014. };
  86015. /**
  86016. * Clones the current image processing instance.
  86017. * @return The cloned image processing
  86018. */
  86019. ImageProcessingConfiguration.prototype.clone = function () {
  86020. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  86021. };
  86022. /**
  86023. * Serializes the current image processing instance to a json representation.
  86024. * @return a JSON representation
  86025. */
  86026. ImageProcessingConfiguration.prototype.serialize = function () {
  86027. return BABYLON.SerializationHelper.Serialize(this);
  86028. };
  86029. /**
  86030. * Parses the image processing from a json representation.
  86031. * @param source the JSON source to parse
  86032. * @return The parsed image processing
  86033. */
  86034. ImageProcessingConfiguration.Parse = function (source) {
  86035. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  86036. };
  86037. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  86038. /**
  86039. * Used to apply the vignette as a mix with the pixel color.
  86040. */
  86041. get: function () {
  86042. return this._VIGNETTEMODE_MULTIPLY;
  86043. },
  86044. enumerable: true,
  86045. configurable: true
  86046. });
  86047. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  86048. /**
  86049. * Used to apply the vignette as a replacement of the pixel color.
  86050. */
  86051. get: function () {
  86052. return this._VIGNETTEMODE_OPAQUE;
  86053. },
  86054. enumerable: true,
  86055. configurable: true
  86056. });
  86057. /**
  86058. * Default tone mapping applied in BabylonJS.
  86059. */
  86060. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  86061. /**
  86062. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  86063. * to other engines rendering to increase portability.
  86064. */
  86065. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  86066. // Static constants associated to the image processing.
  86067. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  86068. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  86069. __decorate([
  86070. BABYLON.serializeAsColorCurves()
  86071. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  86072. __decorate([
  86073. BABYLON.serialize()
  86074. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  86075. __decorate([
  86076. BABYLON.serializeAsTexture()
  86077. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  86078. __decorate([
  86079. BABYLON.serialize()
  86080. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  86081. __decorate([
  86082. BABYLON.serialize()
  86083. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  86084. __decorate([
  86085. BABYLON.serialize()
  86086. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  86087. __decorate([
  86088. BABYLON.serialize()
  86089. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  86090. __decorate([
  86091. BABYLON.serialize()
  86092. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  86093. __decorate([
  86094. BABYLON.serialize()
  86095. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  86096. __decorate([
  86097. BABYLON.serialize()
  86098. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  86099. __decorate([
  86100. BABYLON.serialize()
  86101. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  86102. __decorate([
  86103. BABYLON.serialize()
  86104. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  86105. __decorate([
  86106. BABYLON.serialize()
  86107. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  86108. __decorate([
  86109. BABYLON.serialize()
  86110. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  86111. __decorate([
  86112. BABYLON.serializeAsColor4()
  86113. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  86114. __decorate([
  86115. BABYLON.serialize()
  86116. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  86117. __decorate([
  86118. BABYLON.serialize()
  86119. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  86120. __decorate([
  86121. BABYLON.serialize()
  86122. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  86123. __decorate([
  86124. BABYLON.serialize()
  86125. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  86126. __decorate([
  86127. BABYLON.serialize()
  86128. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  86129. return ImageProcessingConfiguration;
  86130. }());
  86131. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  86132. })(BABYLON || (BABYLON = {}));
  86133. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  86134. var BABYLON;
  86135. (function (BABYLON) {
  86136. /**
  86137. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  86138. * It can help converting any input color in a desired output one. This can then be used to create effects
  86139. * from sepia, black and white to sixties or futuristic rendering...
  86140. *
  86141. * The only supported format is currently 3dl.
  86142. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  86143. */
  86144. var ColorGradingTexture = /** @class */ (function (_super) {
  86145. __extends(ColorGradingTexture, _super);
  86146. /**
  86147. * Instantiates a ColorGradingTexture from the following parameters.
  86148. *
  86149. * @param url The location of the color gradind data (currently only supporting 3dl)
  86150. * @param scene The scene the texture will be used in
  86151. */
  86152. function ColorGradingTexture(url, scene) {
  86153. var _this = _super.call(this, scene) || this;
  86154. if (!url) {
  86155. return _this;
  86156. }
  86157. _this._engine = scene.getEngine();
  86158. _this._textureMatrix = BABYLON.Matrix.Identity();
  86159. _this.name = url;
  86160. _this.url = url;
  86161. _this.hasAlpha = false;
  86162. _this.isCube = false;
  86163. _this.is3D = _this._engine.webGLVersion > 1;
  86164. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86165. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86166. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86167. _this.anisotropicFilteringLevel = 1;
  86168. _this._texture = _this._getFromCache(url, true);
  86169. if (!_this._texture) {
  86170. if (!scene.useDelayedTextureLoading) {
  86171. _this.loadTexture();
  86172. }
  86173. else {
  86174. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86175. }
  86176. }
  86177. return _this;
  86178. }
  86179. /**
  86180. * Returns the texture matrix used in most of the material.
  86181. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  86182. */
  86183. ColorGradingTexture.prototype.getTextureMatrix = function () {
  86184. return this._textureMatrix;
  86185. };
  86186. /**
  86187. * Occurs when the file being loaded is a .3dl LUT file.
  86188. */
  86189. ColorGradingTexture.prototype.load3dlTexture = function () {
  86190. var engine = this._engine;
  86191. var texture;
  86192. if (engine.webGLVersion === 1) {
  86193. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86194. }
  86195. else {
  86196. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86197. }
  86198. this._texture = texture;
  86199. var callback = function (text) {
  86200. if (typeof text !== "string") {
  86201. return;
  86202. }
  86203. var data = null;
  86204. var tempData = null;
  86205. var line;
  86206. var lines = text.split('\n');
  86207. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  86208. var maxColor = 0;
  86209. for (var i = 0; i < lines.length; i++) {
  86210. line = lines[i];
  86211. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  86212. continue;
  86213. if (line.indexOf('#') === 0)
  86214. continue;
  86215. var words = line.split(" ");
  86216. if (size === 0) {
  86217. // Number of space + one
  86218. size = words.length;
  86219. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  86220. tempData = new Float32Array(size * size * size * 4);
  86221. continue;
  86222. }
  86223. if (size != 0) {
  86224. var r = Math.max(parseInt(words[0]), 0);
  86225. var g = Math.max(parseInt(words[1]), 0);
  86226. var b = Math.max(parseInt(words[2]), 0);
  86227. maxColor = Math.max(r, maxColor);
  86228. maxColor = Math.max(g, maxColor);
  86229. maxColor = Math.max(b, maxColor);
  86230. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  86231. if (tempData) {
  86232. tempData[pixelStorageIndex + 0] = r;
  86233. tempData[pixelStorageIndex + 1] = g;
  86234. tempData[pixelStorageIndex + 2] = b;
  86235. }
  86236. pixelIndexSlice++;
  86237. if (pixelIndexSlice % size == 0) {
  86238. pixelIndexH++;
  86239. pixelIndexSlice = 0;
  86240. if (pixelIndexH % size == 0) {
  86241. pixelIndexW++;
  86242. pixelIndexH = 0;
  86243. }
  86244. }
  86245. }
  86246. }
  86247. if (tempData && data) {
  86248. for (var i = 0; i < tempData.length; i++) {
  86249. if (i > 0 && (i + 1) % 4 === 0) {
  86250. data[i] = 255;
  86251. }
  86252. else {
  86253. var value = tempData[i];
  86254. data[i] = (value / maxColor * 255);
  86255. }
  86256. }
  86257. }
  86258. if (texture.is3D) {
  86259. texture.updateSize(size, size, size);
  86260. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86261. }
  86262. else {
  86263. texture.updateSize(size * size, size);
  86264. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86265. }
  86266. };
  86267. var scene = this.getScene();
  86268. if (scene) {
  86269. scene._loadFile(this.url, callback);
  86270. }
  86271. else {
  86272. this._engine._loadFile(this.url, callback);
  86273. }
  86274. return this._texture;
  86275. };
  86276. /**
  86277. * Starts the loading process of the texture.
  86278. */
  86279. ColorGradingTexture.prototype.loadTexture = function () {
  86280. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  86281. this.load3dlTexture();
  86282. }
  86283. };
  86284. /**
  86285. * Clones the color gradind texture.
  86286. */
  86287. ColorGradingTexture.prototype.clone = function () {
  86288. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  86289. // Base texture
  86290. newTexture.level = this.level;
  86291. return newTexture;
  86292. };
  86293. /**
  86294. * Called during delayed load for textures.
  86295. */
  86296. ColorGradingTexture.prototype.delayLoad = function () {
  86297. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86298. return;
  86299. }
  86300. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86301. this._texture = this._getFromCache(this.url, true);
  86302. if (!this._texture) {
  86303. this.loadTexture();
  86304. }
  86305. };
  86306. /**
  86307. * Parses a color grading texture serialized by Babylon.
  86308. * @param parsedTexture The texture information being parsedTexture
  86309. * @param scene The scene to load the texture in
  86310. * @param rootUrl The root url of the data assets to load
  86311. * @return A color gradind texture
  86312. */
  86313. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86314. var texture = null;
  86315. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86316. texture = new ColorGradingTexture(parsedTexture.name, scene);
  86317. texture.name = parsedTexture.name;
  86318. texture.level = parsedTexture.level;
  86319. }
  86320. return texture;
  86321. };
  86322. /**
  86323. * Serializes the LUT texture to json format.
  86324. */
  86325. ColorGradingTexture.prototype.serialize = function () {
  86326. if (!this.name) {
  86327. return null;
  86328. }
  86329. var serializationObject = {};
  86330. serializationObject.name = this.name;
  86331. serializationObject.level = this.level;
  86332. serializationObject.customType = "BABYLON.ColorGradingTexture";
  86333. return serializationObject;
  86334. };
  86335. /**
  86336. * Empty line regex stored for GC.
  86337. */
  86338. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  86339. return ColorGradingTexture;
  86340. }(BABYLON.BaseTexture));
  86341. BABYLON.ColorGradingTexture = ColorGradingTexture;
  86342. })(BABYLON || (BABYLON = {}));
  86343. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  86344. var BABYLON;
  86345. (function (BABYLON) {
  86346. /**
  86347. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86348. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86349. * 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;
  86350. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86351. */
  86352. var ColorCurves = /** @class */ (function () {
  86353. function ColorCurves() {
  86354. this._dirty = true;
  86355. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  86356. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  86357. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  86358. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  86359. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  86360. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  86361. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  86362. this._globalHue = 30;
  86363. this._globalDensity = 0;
  86364. this._globalSaturation = 0;
  86365. this._globalExposure = 0;
  86366. this._highlightsHue = 30;
  86367. this._highlightsDensity = 0;
  86368. this._highlightsSaturation = 0;
  86369. this._highlightsExposure = 0;
  86370. this._midtonesHue = 30;
  86371. this._midtonesDensity = 0;
  86372. this._midtonesSaturation = 0;
  86373. this._midtonesExposure = 0;
  86374. this._shadowsHue = 30;
  86375. this._shadowsDensity = 0;
  86376. this._shadowsSaturation = 0;
  86377. this._shadowsExposure = 0;
  86378. }
  86379. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  86380. /**
  86381. * Gets the global Hue value.
  86382. * 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).
  86383. */
  86384. get: function () {
  86385. return this._globalHue;
  86386. },
  86387. /**
  86388. * Sets the global Hue value.
  86389. * 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).
  86390. */
  86391. set: function (value) {
  86392. this._globalHue = value;
  86393. this._dirty = true;
  86394. },
  86395. enumerable: true,
  86396. configurable: true
  86397. });
  86398. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  86399. /**
  86400. * Gets the global Density value.
  86401. * 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.
  86402. * Values less than zero provide a filter of opposite hue.
  86403. */
  86404. get: function () {
  86405. return this._globalDensity;
  86406. },
  86407. /**
  86408. * Sets the global Density value.
  86409. * 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.
  86410. * Values less than zero provide a filter of opposite hue.
  86411. */
  86412. set: function (value) {
  86413. this._globalDensity = value;
  86414. this._dirty = true;
  86415. },
  86416. enumerable: true,
  86417. configurable: true
  86418. });
  86419. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  86420. /**
  86421. * Gets the global Saturation value.
  86422. * 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.
  86423. */
  86424. get: function () {
  86425. return this._globalSaturation;
  86426. },
  86427. /**
  86428. * Sets the global Saturation value.
  86429. * 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.
  86430. */
  86431. set: function (value) {
  86432. this._globalSaturation = value;
  86433. this._dirty = true;
  86434. },
  86435. enumerable: true,
  86436. configurable: true
  86437. });
  86438. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  86439. /**
  86440. * Gets the global Exposure value.
  86441. * 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.
  86442. */
  86443. get: function () {
  86444. return this._globalExposure;
  86445. },
  86446. /**
  86447. * Sets the global Exposure value.
  86448. * 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.
  86449. */
  86450. set: function (value) {
  86451. this._globalExposure = value;
  86452. this._dirty = true;
  86453. },
  86454. enumerable: true,
  86455. configurable: true
  86456. });
  86457. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  86458. /**
  86459. * Gets the highlights Hue value.
  86460. * 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).
  86461. */
  86462. get: function () {
  86463. return this._highlightsHue;
  86464. },
  86465. /**
  86466. * Sets the highlights Hue value.
  86467. * 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).
  86468. */
  86469. set: function (value) {
  86470. this._highlightsHue = value;
  86471. this._dirty = true;
  86472. },
  86473. enumerable: true,
  86474. configurable: true
  86475. });
  86476. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  86477. /**
  86478. * Gets the highlights Density value.
  86479. * 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.
  86480. * Values less than zero provide a filter of opposite hue.
  86481. */
  86482. get: function () {
  86483. return this._highlightsDensity;
  86484. },
  86485. /**
  86486. * Sets the highlights Density value.
  86487. * 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.
  86488. * Values less than zero provide a filter of opposite hue.
  86489. */
  86490. set: function (value) {
  86491. this._highlightsDensity = value;
  86492. this._dirty = true;
  86493. },
  86494. enumerable: true,
  86495. configurable: true
  86496. });
  86497. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  86498. /**
  86499. * Gets the highlights Saturation value.
  86500. * 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.
  86501. */
  86502. get: function () {
  86503. return this._highlightsSaturation;
  86504. },
  86505. /**
  86506. * Sets the highlights Saturation value.
  86507. * 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.
  86508. */
  86509. set: function (value) {
  86510. this._highlightsSaturation = value;
  86511. this._dirty = true;
  86512. },
  86513. enumerable: true,
  86514. configurable: true
  86515. });
  86516. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  86517. /**
  86518. * Gets the highlights Exposure value.
  86519. * 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.
  86520. */
  86521. get: function () {
  86522. return this._highlightsExposure;
  86523. },
  86524. /**
  86525. * Sets the highlights Exposure value.
  86526. * 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.
  86527. */
  86528. set: function (value) {
  86529. this._highlightsExposure = value;
  86530. this._dirty = true;
  86531. },
  86532. enumerable: true,
  86533. configurable: true
  86534. });
  86535. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  86536. /**
  86537. * Gets the midtones Hue value.
  86538. * 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).
  86539. */
  86540. get: function () {
  86541. return this._midtonesHue;
  86542. },
  86543. /**
  86544. * Sets the midtones Hue value.
  86545. * 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).
  86546. */
  86547. set: function (value) {
  86548. this._midtonesHue = value;
  86549. this._dirty = true;
  86550. },
  86551. enumerable: true,
  86552. configurable: true
  86553. });
  86554. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  86555. /**
  86556. * Gets the midtones Density value.
  86557. * 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.
  86558. * Values less than zero provide a filter of opposite hue.
  86559. */
  86560. get: function () {
  86561. return this._midtonesDensity;
  86562. },
  86563. /**
  86564. * Sets the midtones Density value.
  86565. * 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.
  86566. * Values less than zero provide a filter of opposite hue.
  86567. */
  86568. set: function (value) {
  86569. this._midtonesDensity = value;
  86570. this._dirty = true;
  86571. },
  86572. enumerable: true,
  86573. configurable: true
  86574. });
  86575. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  86576. /**
  86577. * Gets the midtones Saturation value.
  86578. * 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.
  86579. */
  86580. get: function () {
  86581. return this._midtonesSaturation;
  86582. },
  86583. /**
  86584. * Sets the midtones Saturation value.
  86585. * 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.
  86586. */
  86587. set: function (value) {
  86588. this._midtonesSaturation = value;
  86589. this._dirty = true;
  86590. },
  86591. enumerable: true,
  86592. configurable: true
  86593. });
  86594. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  86595. /**
  86596. * Gets the midtones Exposure value.
  86597. * 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.
  86598. */
  86599. get: function () {
  86600. return this._midtonesExposure;
  86601. },
  86602. /**
  86603. * Sets the midtones Exposure value.
  86604. * 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.
  86605. */
  86606. set: function (value) {
  86607. this._midtonesExposure = value;
  86608. this._dirty = true;
  86609. },
  86610. enumerable: true,
  86611. configurable: true
  86612. });
  86613. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  86614. /**
  86615. * Gets the shadows Hue value.
  86616. * 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).
  86617. */
  86618. get: function () {
  86619. return this._shadowsHue;
  86620. },
  86621. /**
  86622. * Sets the shadows Hue value.
  86623. * 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).
  86624. */
  86625. set: function (value) {
  86626. this._shadowsHue = value;
  86627. this._dirty = true;
  86628. },
  86629. enumerable: true,
  86630. configurable: true
  86631. });
  86632. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  86633. /**
  86634. * Gets the shadows Density value.
  86635. * 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.
  86636. * Values less than zero provide a filter of opposite hue.
  86637. */
  86638. get: function () {
  86639. return this._shadowsDensity;
  86640. },
  86641. /**
  86642. * Sets the shadows Density value.
  86643. * 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.
  86644. * Values less than zero provide a filter of opposite hue.
  86645. */
  86646. set: function (value) {
  86647. this._shadowsDensity = value;
  86648. this._dirty = true;
  86649. },
  86650. enumerable: true,
  86651. configurable: true
  86652. });
  86653. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  86654. /**
  86655. * Gets the shadows Saturation value.
  86656. * 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.
  86657. */
  86658. get: function () {
  86659. return this._shadowsSaturation;
  86660. },
  86661. /**
  86662. * Sets the shadows Saturation value.
  86663. * 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.
  86664. */
  86665. set: function (value) {
  86666. this._shadowsSaturation = value;
  86667. this._dirty = true;
  86668. },
  86669. enumerable: true,
  86670. configurable: true
  86671. });
  86672. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  86673. /**
  86674. * Gets the shadows Exposure value.
  86675. * 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.
  86676. */
  86677. get: function () {
  86678. return this._shadowsExposure;
  86679. },
  86680. /**
  86681. * Sets the shadows Exposure value.
  86682. * 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.
  86683. */
  86684. set: function (value) {
  86685. this._shadowsExposure = value;
  86686. this._dirty = true;
  86687. },
  86688. enumerable: true,
  86689. configurable: true
  86690. });
  86691. /**
  86692. * Returns the class name
  86693. * @returns The class name
  86694. */
  86695. ColorCurves.prototype.getClassName = function () {
  86696. return "ColorCurves";
  86697. };
  86698. /**
  86699. * Binds the color curves to the shader.
  86700. * @param colorCurves The color curve to bind
  86701. * @param effect The effect to bind to
  86702. * @param positiveUniform The positive uniform shader parameter
  86703. * @param neutralUniform The neutral uniform shader parameter
  86704. * @param negativeUniform The negative uniform shader parameter
  86705. */
  86706. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  86707. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  86708. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  86709. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  86710. if (colorCurves._dirty) {
  86711. colorCurves._dirty = false;
  86712. // Fill in global info.
  86713. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  86714. // Compute highlights info.
  86715. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  86716. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  86717. // Compute midtones info.
  86718. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  86719. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  86720. // Compute shadows info.
  86721. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  86722. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  86723. // Compute deltas (neutral is midtones).
  86724. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  86725. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  86726. }
  86727. if (effect) {
  86728. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  86729. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  86730. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  86731. }
  86732. };
  86733. /**
  86734. * Prepare the list of uniforms associated with the ColorCurves effects.
  86735. * @param uniformsList The list of uniforms used in the effect
  86736. */
  86737. ColorCurves.PrepareUniforms = function (uniformsList) {
  86738. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  86739. };
  86740. /**
  86741. * Returns color grading data based on a hue, density, saturation and exposure value.
  86742. * @param filterHue The hue of the color filter.
  86743. * @param filterDensity The density of the color filter.
  86744. * @param saturation The saturation.
  86745. * @param exposure The exposure.
  86746. * @param result The result data container.
  86747. */
  86748. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  86749. if (hue == null) {
  86750. return;
  86751. }
  86752. hue = ColorCurves.clamp(hue, 0, 360);
  86753. density = ColorCurves.clamp(density, -100, 100);
  86754. saturation = ColorCurves.clamp(saturation, -100, 100);
  86755. exposure = ColorCurves.clamp(exposure, -100, 100);
  86756. // Remap the slider/config filter density with non-linear mapping and also scale by half
  86757. // so that the maximum filter density is only 50% control. This provides fine control
  86758. // for small values and reasonable range.
  86759. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  86760. density *= 0.5;
  86761. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  86762. if (density < 0) {
  86763. density *= -1;
  86764. hue = (hue + 180) % 360;
  86765. }
  86766. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  86767. result.scaleToRef(2, result);
  86768. result.a = 1 + 0.01 * saturation;
  86769. };
  86770. /**
  86771. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  86772. * @param value The input slider value in range [-100,100].
  86773. * @returns Adjusted value.
  86774. */
  86775. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  86776. value /= 100;
  86777. var x = Math.abs(value);
  86778. x = Math.pow(x, 2);
  86779. if (value < 0) {
  86780. x *= -1;
  86781. }
  86782. x *= 100;
  86783. return x;
  86784. };
  86785. /**
  86786. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  86787. * @param hue The hue (H) input.
  86788. * @param saturation The saturation (S) input.
  86789. * @param brightness The brightness (B) input.
  86790. * @result An RGBA color represented as Vector4.
  86791. */
  86792. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  86793. var h = ColorCurves.clamp(hue, 0, 360);
  86794. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  86795. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  86796. if (s === 0) {
  86797. result.r = v;
  86798. result.g = v;
  86799. result.b = v;
  86800. }
  86801. else {
  86802. // sector 0 to 5
  86803. h /= 60;
  86804. var i = Math.floor(h);
  86805. // fractional part of h
  86806. var f = h - i;
  86807. var p = v * (1 - s);
  86808. var q = v * (1 - s * f);
  86809. var t = v * (1 - s * (1 - f));
  86810. switch (i) {
  86811. case 0:
  86812. result.r = v;
  86813. result.g = t;
  86814. result.b = p;
  86815. break;
  86816. case 1:
  86817. result.r = q;
  86818. result.g = v;
  86819. result.b = p;
  86820. break;
  86821. case 2:
  86822. result.r = p;
  86823. result.g = v;
  86824. result.b = t;
  86825. break;
  86826. case 3:
  86827. result.r = p;
  86828. result.g = q;
  86829. result.b = v;
  86830. break;
  86831. case 4:
  86832. result.r = t;
  86833. result.g = p;
  86834. result.b = v;
  86835. break;
  86836. default: // case 5:
  86837. result.r = v;
  86838. result.g = p;
  86839. result.b = q;
  86840. break;
  86841. }
  86842. }
  86843. result.a = 1;
  86844. };
  86845. /**
  86846. * Returns a value clamped between min and max
  86847. * @param value The value to clamp
  86848. * @param min The minimum of value
  86849. * @param max The maximum of value
  86850. * @returns The clamped value.
  86851. */
  86852. ColorCurves.clamp = function (value, min, max) {
  86853. return Math.min(Math.max(value, min), max);
  86854. };
  86855. /**
  86856. * Clones the current color curve instance.
  86857. * @return The cloned curves
  86858. */
  86859. ColorCurves.prototype.clone = function () {
  86860. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  86861. };
  86862. /**
  86863. * Serializes the current color curve instance to a json representation.
  86864. * @return a JSON representation
  86865. */
  86866. ColorCurves.prototype.serialize = function () {
  86867. return BABYLON.SerializationHelper.Serialize(this);
  86868. };
  86869. /**
  86870. * Parses the color curve from a json representation.
  86871. * @param source the JSON source to parse
  86872. * @return The parsed curves
  86873. */
  86874. ColorCurves.Parse = function (source) {
  86875. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  86876. };
  86877. __decorate([
  86878. BABYLON.serialize()
  86879. ], ColorCurves.prototype, "_globalHue", void 0);
  86880. __decorate([
  86881. BABYLON.serialize()
  86882. ], ColorCurves.prototype, "_globalDensity", void 0);
  86883. __decorate([
  86884. BABYLON.serialize()
  86885. ], ColorCurves.prototype, "_globalSaturation", void 0);
  86886. __decorate([
  86887. BABYLON.serialize()
  86888. ], ColorCurves.prototype, "_globalExposure", void 0);
  86889. __decorate([
  86890. BABYLON.serialize()
  86891. ], ColorCurves.prototype, "_highlightsHue", void 0);
  86892. __decorate([
  86893. BABYLON.serialize()
  86894. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  86895. __decorate([
  86896. BABYLON.serialize()
  86897. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  86898. __decorate([
  86899. BABYLON.serialize()
  86900. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  86901. __decorate([
  86902. BABYLON.serialize()
  86903. ], ColorCurves.prototype, "_midtonesHue", void 0);
  86904. __decorate([
  86905. BABYLON.serialize()
  86906. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  86907. __decorate([
  86908. BABYLON.serialize()
  86909. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  86910. __decorate([
  86911. BABYLON.serialize()
  86912. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  86913. return ColorCurves;
  86914. }());
  86915. BABYLON.ColorCurves = ColorCurves;
  86916. })(BABYLON || (BABYLON = {}));
  86917. //# sourceMappingURL=babylon.colorCurves.js.map
  86918. var BABYLON;
  86919. (function (BABYLON) {
  86920. var RefractionPostProcess = /** @class */ (function (_super) {
  86921. __extends(RefractionPostProcess, _super);
  86922. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  86923. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  86924. _this.color = color;
  86925. _this.depth = depth;
  86926. _this.colorLevel = colorLevel;
  86927. _this._ownRefractionTexture = true;
  86928. _this.onActivateObservable.add(function (cam) {
  86929. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  86930. });
  86931. _this.onApplyObservable.add(function (effect) {
  86932. effect.setColor3("baseColor", _this.color);
  86933. effect.setFloat("depth", _this.depth);
  86934. effect.setFloat("colorLevel", _this.colorLevel);
  86935. effect.setTexture("refractionSampler", _this._refTexture);
  86936. });
  86937. return _this;
  86938. }
  86939. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  86940. /**
  86941. * Gets or sets the refraction texture
  86942. * Please note that you are responsible for disposing the texture if you set it manually
  86943. */
  86944. get: function () {
  86945. return this._refTexture;
  86946. },
  86947. set: function (value) {
  86948. if (this._refTexture && this._ownRefractionTexture) {
  86949. this._refTexture.dispose();
  86950. }
  86951. this._refTexture = value;
  86952. this._ownRefractionTexture = false;
  86953. },
  86954. enumerable: true,
  86955. configurable: true
  86956. });
  86957. // Methods
  86958. RefractionPostProcess.prototype.dispose = function (camera) {
  86959. if (this._refTexture && this._ownRefractionTexture) {
  86960. this._refTexture.dispose();
  86961. this._refTexture = null;
  86962. }
  86963. _super.prototype.dispose.call(this, camera);
  86964. };
  86965. return RefractionPostProcess;
  86966. }(BABYLON.PostProcess));
  86967. BABYLON.RefractionPostProcess = RefractionPostProcess;
  86968. })(BABYLON || (BABYLON = {}));
  86969. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  86970. var BABYLON;
  86971. (function (BABYLON) {
  86972. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  86973. __extends(BlackAndWhitePostProcess, _super);
  86974. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  86975. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  86976. _this.degree = 1;
  86977. _this.onApplyObservable.add(function (effect) {
  86978. effect.setFloat("degree", _this.degree);
  86979. });
  86980. return _this;
  86981. }
  86982. return BlackAndWhitePostProcess;
  86983. }(BABYLON.PostProcess));
  86984. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  86985. })(BABYLON || (BABYLON = {}));
  86986. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  86987. var BABYLON;
  86988. (function (BABYLON) {
  86989. /**
  86990. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  86991. * input texture to perform effects such as edge detection or sharpening
  86992. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  86993. */
  86994. var ConvolutionPostProcess = /** @class */ (function (_super) {
  86995. __extends(ConvolutionPostProcess, _super);
  86996. /**
  86997. * Creates a new instance ConvolutionPostProcess
  86998. * @param name The name of the effect.
  86999. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  87000. * @param options The required width/height ratio to downsize to before computing the render pass.
  87001. * @param camera The camera to apply the render pass to.
  87002. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87003. * @param engine The engine which the post process will be applied. (default: current engine)
  87004. * @param reusable If the post process can be reused on the same frame. (default: false)
  87005. * @param textureType Type of textures used when performing the post process. (default: 0)
  87006. */
  87007. function ConvolutionPostProcess(name,
  87008. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  87009. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  87010. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87011. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87012. _this.kernel = kernel;
  87013. _this.onApply = function (effect) {
  87014. effect.setFloat2("screenSize", _this.width, _this.height);
  87015. effect.setArray("kernel", _this.kernel);
  87016. };
  87017. return _this;
  87018. }
  87019. // Statics
  87020. /**
  87021. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87022. */
  87023. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  87024. /**
  87025. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87026. */
  87027. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  87028. /**
  87029. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87030. */
  87031. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  87032. /**
  87033. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87034. */
  87035. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  87036. /**
  87037. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87038. */
  87039. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  87040. /**
  87041. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87042. */
  87043. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  87044. return ConvolutionPostProcess;
  87045. }(BABYLON.PostProcess));
  87046. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  87047. })(BABYLON || (BABYLON = {}));
  87048. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  87049. var BABYLON;
  87050. (function (BABYLON) {
  87051. var FilterPostProcess = /** @class */ (function (_super) {
  87052. __extends(FilterPostProcess, _super);
  87053. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  87054. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  87055. _this.kernelMatrix = kernelMatrix;
  87056. _this.onApply = function (effect) {
  87057. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  87058. };
  87059. return _this;
  87060. }
  87061. return FilterPostProcess;
  87062. }(BABYLON.PostProcess));
  87063. BABYLON.FilterPostProcess = FilterPostProcess;
  87064. })(BABYLON || (BABYLON = {}));
  87065. //# sourceMappingURL=babylon.filterPostProcess.js.map
  87066. var BABYLON;
  87067. (function (BABYLON) {
  87068. /**
  87069. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  87070. */
  87071. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  87072. __extends(VolumetricLightScatteringPostProcess, _super);
  87073. /**
  87074. * @constructor
  87075. * @param {string} name - The post-process name
  87076. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  87077. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  87078. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  87079. * @param {number} samples - The post-process quality, default 100
  87080. * @param {number} samplingMode - The post-process filtering mode
  87081. * @param {BABYLON.Engine} engine - The babylon engine
  87082. * @param {boolean} reusable - If the post-process is reusable
  87083. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  87084. */
  87085. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  87086. if (samples === void 0) { samples = 100; }
  87087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87088. 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;
  87089. _this._screenCoordinates = BABYLON.Vector2.Zero();
  87090. /**
  87091. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  87092. */
  87093. _this.customMeshPosition = BABYLON.Vector3.Zero();
  87094. /**
  87095. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  87096. */
  87097. _this.useCustomMeshPosition = false;
  87098. /**
  87099. * If the post-process should inverse the light scattering direction
  87100. */
  87101. _this.invert = true;
  87102. /**
  87103. * Array containing the excluded meshes not rendered in the internal pass
  87104. */
  87105. _this.excludedMeshes = new Array();
  87106. /**
  87107. * Controls the overall intensity of the post-process
  87108. */
  87109. _this.exposure = 0.3;
  87110. /**
  87111. * Dissipates each sample's contribution in range [0, 1]
  87112. */
  87113. _this.decay = 0.96815;
  87114. /**
  87115. * Controls the overall intensity of each sample
  87116. */
  87117. _this.weight = 0.58767;
  87118. /**
  87119. * Controls the density of each sample
  87120. */
  87121. _this.density = 0.926;
  87122. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  87123. engine = scene.getEngine();
  87124. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  87125. // Configure mesh
  87126. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  87127. // Configure
  87128. _this._createPass(scene, ratio.passRatio || ratio);
  87129. _this.onActivate = function (camera) {
  87130. if (!_this.isSupported) {
  87131. _this.dispose(camera);
  87132. }
  87133. _this.onActivate = null;
  87134. };
  87135. _this.onApplyObservable.add(function (effect) {
  87136. _this._updateMeshScreenCoordinates(scene);
  87137. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  87138. effect.setFloat("exposure", _this.exposure);
  87139. effect.setFloat("decay", _this.decay);
  87140. effect.setFloat("weight", _this.weight);
  87141. effect.setFloat("density", _this.density);
  87142. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  87143. });
  87144. return _this;
  87145. }
  87146. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  87147. /**
  87148. * @hidden
  87149. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  87150. */
  87151. get: function () {
  87152. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87153. return false;
  87154. },
  87155. set: function (useDiffuseColor) {
  87156. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87157. },
  87158. enumerable: true,
  87159. configurable: true
  87160. });
  87161. /**
  87162. * Returns the string "VolumetricLightScatteringPostProcess"
  87163. * @returns "VolumetricLightScatteringPostProcess"
  87164. */
  87165. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  87166. return "VolumetricLightScatteringPostProcess";
  87167. };
  87168. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  87169. var mesh = subMesh.getMesh();
  87170. // Render this.mesh as default
  87171. if (mesh === this.mesh && mesh.material) {
  87172. return mesh.material.isReady(mesh);
  87173. }
  87174. var defines = [];
  87175. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87176. var material = subMesh.getMaterial();
  87177. // Alpha test
  87178. if (material) {
  87179. if (material.needAlphaTesting()) {
  87180. defines.push("#define ALPHATEST");
  87181. }
  87182. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87183. attribs.push(BABYLON.VertexBuffer.UVKind);
  87184. defines.push("#define UV1");
  87185. }
  87186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  87187. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87188. defines.push("#define UV2");
  87189. }
  87190. }
  87191. // Bones
  87192. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  87193. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  87194. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  87195. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  87196. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  87197. }
  87198. else {
  87199. defines.push("#define NUM_BONE_INFLUENCERS 0");
  87200. }
  87201. // Instances
  87202. if (useInstances) {
  87203. defines.push("#define INSTANCES");
  87204. attribs.push("world0");
  87205. attribs.push("world1");
  87206. attribs.push("world2");
  87207. attribs.push("world3");
  87208. }
  87209. // Get correct effect
  87210. var join = defines.join("\n");
  87211. if (this._cachedDefines !== join) {
  87212. this._cachedDefines = join;
  87213. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  87214. }
  87215. return this._volumetricLightScatteringPass.isReady();
  87216. };
  87217. /**
  87218. * Sets the new light position for light scattering effect
  87219. * @param position The new custom light position
  87220. */
  87221. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  87222. this.customMeshPosition = position;
  87223. };
  87224. /**
  87225. * Returns the light position for light scattering effect
  87226. * @return {BABYLON.Vector3} The custom light position
  87227. */
  87228. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  87229. return this.customMeshPosition;
  87230. };
  87231. /**
  87232. * Disposes the internal assets and detaches the post-process from the camera
  87233. */
  87234. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  87235. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  87236. if (rttIndex !== -1) {
  87237. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  87238. }
  87239. this._volumetricLightScatteringRTT.dispose();
  87240. _super.prototype.dispose.call(this, camera);
  87241. };
  87242. /**
  87243. * Returns the render target texture used by the post-process
  87244. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  87245. */
  87246. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  87247. return this._volumetricLightScatteringRTT;
  87248. };
  87249. // Private methods
  87250. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  87251. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  87252. return true;
  87253. }
  87254. return false;
  87255. };
  87256. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  87257. var _this = this;
  87258. var engine = scene.getEngine();
  87259. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87260. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87261. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87262. this._volumetricLightScatteringRTT.renderList = null;
  87263. this._volumetricLightScatteringRTT.renderParticles = false;
  87264. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  87265. var camera = this.getCamera();
  87266. if (camera) {
  87267. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  87268. }
  87269. else {
  87270. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  87271. }
  87272. // Custom render function for submeshes
  87273. var renderSubMesh = function (subMesh) {
  87274. var mesh = subMesh.getRenderingMesh();
  87275. if (_this._meshExcluded(mesh)) {
  87276. return;
  87277. }
  87278. var material = subMesh.getMaterial();
  87279. if (!material) {
  87280. return;
  87281. }
  87282. var scene = mesh.getScene();
  87283. var engine = scene.getEngine();
  87284. // Culling
  87285. engine.setState(material.backFaceCulling);
  87286. // Managing instances
  87287. var batch = mesh._getInstancesRenderList(subMesh._id);
  87288. if (batch.mustReturn) {
  87289. return;
  87290. }
  87291. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  87292. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  87293. var effect = _this._volumetricLightScatteringPass;
  87294. if (mesh === _this.mesh) {
  87295. if (subMesh.effect) {
  87296. effect = subMesh.effect;
  87297. }
  87298. else {
  87299. effect = material.getEffect();
  87300. }
  87301. }
  87302. engine.enableEffect(effect);
  87303. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  87304. if (mesh === _this.mesh) {
  87305. material.bind(mesh.getWorldMatrix(), mesh);
  87306. }
  87307. else {
  87308. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  87309. // Alpha test
  87310. if (material && material.needAlphaTesting()) {
  87311. var alphaTexture = material.getAlphaTestTexture();
  87312. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  87313. if (alphaTexture) {
  87314. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  87315. }
  87316. }
  87317. // Bones
  87318. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  87319. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  87320. }
  87321. }
  87322. // Draw
  87323. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  87324. }
  87325. };
  87326. // Render target texture callbacks
  87327. var savedSceneClearColor;
  87328. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  87329. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  87330. savedSceneClearColor = scene.clearColor;
  87331. scene.clearColor = sceneClearColor;
  87332. });
  87333. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  87334. scene.clearColor = savedSceneClearColor;
  87335. });
  87336. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  87337. var engine = scene.getEngine();
  87338. var index;
  87339. if (depthOnlySubMeshes.length) {
  87340. engine.setColorWrite(false);
  87341. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  87342. renderSubMesh(depthOnlySubMeshes.data[index]);
  87343. }
  87344. engine.setColorWrite(true);
  87345. }
  87346. for (index = 0; index < opaqueSubMeshes.length; index++) {
  87347. renderSubMesh(opaqueSubMeshes.data[index]);
  87348. }
  87349. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  87350. renderSubMesh(alphaTestSubMeshes.data[index]);
  87351. }
  87352. if (transparentSubMeshes.length) {
  87353. // Sort sub meshes
  87354. for (index = 0; index < transparentSubMeshes.length; index++) {
  87355. var submesh = transparentSubMeshes.data[index];
  87356. var boundingInfo = submesh.getBoundingInfo();
  87357. if (boundingInfo && scene.activeCamera) {
  87358. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  87359. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  87360. }
  87361. }
  87362. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  87363. sortedArray.sort(function (a, b) {
  87364. // Alpha index first
  87365. if (a._alphaIndex > b._alphaIndex) {
  87366. return 1;
  87367. }
  87368. if (a._alphaIndex < b._alphaIndex) {
  87369. return -1;
  87370. }
  87371. // Then distance to camera
  87372. if (a._distanceToCamera < b._distanceToCamera) {
  87373. return 1;
  87374. }
  87375. if (a._distanceToCamera > b._distanceToCamera) {
  87376. return -1;
  87377. }
  87378. return 0;
  87379. });
  87380. // Render sub meshes
  87381. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  87382. for (index = 0; index < sortedArray.length; index++) {
  87383. renderSubMesh(sortedArray[index]);
  87384. }
  87385. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87386. }
  87387. };
  87388. };
  87389. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  87390. var transform = scene.getTransformMatrix();
  87391. var meshPosition;
  87392. if (this.useCustomMeshPosition) {
  87393. meshPosition = this.customMeshPosition;
  87394. }
  87395. else if (this.attachedNode) {
  87396. meshPosition = this.attachedNode.position;
  87397. }
  87398. else {
  87399. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  87400. }
  87401. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  87402. this._screenCoordinates.x = pos.x / this._viewPort.width;
  87403. this._screenCoordinates.y = pos.y / this._viewPort.height;
  87404. if (this.invert)
  87405. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  87406. };
  87407. // Static methods
  87408. /**
  87409. * Creates a default mesh for the Volumeric Light Scattering post-process
  87410. * @param name The mesh name
  87411. * @param scene The scene where to create the mesh
  87412. * @return {BABYLON.Mesh} the default mesh
  87413. */
  87414. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  87415. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  87416. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  87417. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  87418. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  87419. mesh.material = material;
  87420. return mesh;
  87421. };
  87422. __decorate([
  87423. BABYLON.serializeAsVector3()
  87424. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  87425. __decorate([
  87426. BABYLON.serialize()
  87427. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  87428. __decorate([
  87429. BABYLON.serialize()
  87430. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  87431. __decorate([
  87432. BABYLON.serializeAsMeshReference()
  87433. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  87434. __decorate([
  87435. BABYLON.serialize()
  87436. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  87437. __decorate([
  87438. BABYLON.serialize()
  87439. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  87440. __decorate([
  87441. BABYLON.serialize()
  87442. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  87443. __decorate([
  87444. BABYLON.serialize()
  87445. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  87446. __decorate([
  87447. BABYLON.serialize()
  87448. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  87449. return VolumetricLightScatteringPostProcess;
  87450. }(BABYLON.PostProcess));
  87451. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  87452. })(BABYLON || (BABYLON = {}));
  87453. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  87454. var BABYLON;
  87455. (function (BABYLON) {
  87456. /**
  87457. *
  87458. * This post-process allows the modification of rendered colors by using
  87459. * a 'look-up table' (LUT). This effect is also called Color Grading.
  87460. *
  87461. * The object needs to be provided an url to a texture containing the color
  87462. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  87463. * Use an image editing software to tweak the LUT to match your needs.
  87464. *
  87465. * For an example of a color LUT, see here:
  87466. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  87467. * For explanations on color grading, see here:
  87468. * @see http://udn.epicgames.com/Three/ColorGrading.html
  87469. *
  87470. */
  87471. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  87472. __extends(ColorCorrectionPostProcess, _super);
  87473. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  87474. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  87475. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87476. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  87477. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87478. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87479. _this.onApply = function (effect) {
  87480. effect.setTexture("colorTable", _this._colorTableTexture);
  87481. };
  87482. return _this;
  87483. }
  87484. return ColorCorrectionPostProcess;
  87485. }(BABYLON.PostProcess));
  87486. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  87487. })(BABYLON || (BABYLON = {}));
  87488. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  87489. var BABYLON;
  87490. (function (BABYLON) {
  87491. /** Defines operator used for tonemapping */
  87492. var TonemappingOperator;
  87493. (function (TonemappingOperator) {
  87494. /** Hable */
  87495. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  87496. /** Reinhard */
  87497. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  87498. /** HejiDawson */
  87499. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  87500. /** Photographic */
  87501. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  87502. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  87503. ;
  87504. /**
  87505. * Defines a post process to apply tone mapping
  87506. */
  87507. var TonemapPostProcess = /** @class */ (function (_super) {
  87508. __extends(TonemapPostProcess, _super);
  87509. /**
  87510. * Creates a new TonemapPostProcess
  87511. * @param name defines the name of the postprocess
  87512. * @param _operator defines the operator to use
  87513. * @param exposureAdjustment defines the required exposure adjustement
  87514. * @param camera defines the camera to use (can be null)
  87515. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  87516. * @param engine defines the hosting engine (can be ignore if camera is set)
  87517. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  87518. */
  87519. function TonemapPostProcess(name, _operator,
  87520. /** Defines the required exposure adjustement */
  87521. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  87522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87523. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87524. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  87525. _this._operator = _operator;
  87526. _this.exposureAdjustment = exposureAdjustment;
  87527. var defines = "#define ";
  87528. if (_this._operator === TonemappingOperator.Hable)
  87529. defines += "HABLE_TONEMAPPING";
  87530. else if (_this._operator === TonemappingOperator.Reinhard)
  87531. defines += "REINHARD_TONEMAPPING";
  87532. else if (_this._operator === TonemappingOperator.HejiDawson)
  87533. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  87534. else if (_this._operator === TonemappingOperator.Photographic)
  87535. defines += "PHOTOGRAPHIC_TONEMAPPING";
  87536. //sadly a second call to create the effect.
  87537. _this.updateEffect(defines);
  87538. _this.onApply = function (effect) {
  87539. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  87540. };
  87541. return _this;
  87542. }
  87543. return TonemapPostProcess;
  87544. }(BABYLON.PostProcess));
  87545. BABYLON.TonemapPostProcess = TonemapPostProcess;
  87546. })(BABYLON || (BABYLON = {}));
  87547. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  87548. var BABYLON;
  87549. (function (BABYLON) {
  87550. var DisplayPassPostProcess = /** @class */ (function (_super) {
  87551. __extends(DisplayPassPostProcess, _super);
  87552. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  87553. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  87554. }
  87555. return DisplayPassPostProcess;
  87556. }(BABYLON.PostProcess));
  87557. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  87558. })(BABYLON || (BABYLON = {}));
  87559. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  87560. var BABYLON;
  87561. (function (BABYLON) {
  87562. var HighlightsPostProcess = /** @class */ (function (_super) {
  87563. __extends(HighlightsPostProcess, _super);
  87564. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  87565. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87566. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87567. }
  87568. return HighlightsPostProcess;
  87569. }(BABYLON.PostProcess));
  87570. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  87571. })(BABYLON || (BABYLON = {}));
  87572. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  87573. var BABYLON;
  87574. (function (BABYLON) {
  87575. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  87576. __extends(ImageProcessingPostProcess, _super);
  87577. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  87578. if (camera === void 0) { camera = null; }
  87579. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87580. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  87581. _this._fromLinearSpace = true;
  87582. /**
  87583. * Defines cache preventing GC.
  87584. */
  87585. _this._defines = {
  87586. IMAGEPROCESSING: false,
  87587. VIGNETTE: false,
  87588. VIGNETTEBLENDMODEMULTIPLY: false,
  87589. VIGNETTEBLENDMODEOPAQUE: false,
  87590. TONEMAPPING: false,
  87591. TONEMAPPING_ACES: false,
  87592. CONTRAST: false,
  87593. COLORCURVES: false,
  87594. COLORGRADING: false,
  87595. COLORGRADING3D: false,
  87596. FROMLINEARSPACE: false,
  87597. SAMPLER3DGREENDEPTH: false,
  87598. SAMPLER3DBGRMAP: false,
  87599. IMAGEPROCESSINGPOSTPROCESS: false,
  87600. EXPOSURE: false,
  87601. };
  87602. // Setup the configuration as forced by the constructor. This would then not force the
  87603. // scene materials output in linear space and let untouched the default forward pass.
  87604. if (imageProcessingConfiguration) {
  87605. imageProcessingConfiguration.applyByPostProcess = true;
  87606. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  87607. // This will cause the shader to be compiled
  87608. _this.fromLinearSpace = false;
  87609. }
  87610. // Setup the default processing configuration to the scene.
  87611. else {
  87612. _this._attachImageProcessingConfiguration(null, true);
  87613. _this.imageProcessingConfiguration.applyByPostProcess = true;
  87614. }
  87615. _this.onApply = function (effect) {
  87616. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  87617. };
  87618. return _this;
  87619. }
  87620. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  87621. /**
  87622. * Gets the image processing configuration used either in this material.
  87623. */
  87624. get: function () {
  87625. return this._imageProcessingConfiguration;
  87626. },
  87627. /**
  87628. * Sets the Default image processing configuration used either in the this material.
  87629. *
  87630. * If sets to null, the scene one is in use.
  87631. */
  87632. set: function (value) {
  87633. this._attachImageProcessingConfiguration(value);
  87634. },
  87635. enumerable: true,
  87636. configurable: true
  87637. });
  87638. /**
  87639. * Attaches a new image processing configuration to the PBR Material.
  87640. * @param configuration
  87641. */
  87642. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  87643. var _this = this;
  87644. if (doNotBuild === void 0) { doNotBuild = false; }
  87645. if (configuration === this._imageProcessingConfiguration) {
  87646. return;
  87647. }
  87648. // Detaches observer.
  87649. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87650. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87651. }
  87652. // Pick the scene configuration if needed.
  87653. if (!configuration) {
  87654. var scene = null;
  87655. var engine = this.getEngine();
  87656. var camera = this.getCamera();
  87657. if (camera) {
  87658. scene = camera.getScene();
  87659. }
  87660. else if (engine && engine.scenes) {
  87661. var scenes = engine.scenes;
  87662. scene = scenes[scenes.length - 1];
  87663. }
  87664. else {
  87665. scene = BABYLON.Engine.LastCreatedScene;
  87666. }
  87667. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  87668. }
  87669. else {
  87670. this._imageProcessingConfiguration = configuration;
  87671. }
  87672. // Attaches observer.
  87673. if (this._imageProcessingConfiguration) {
  87674. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  87675. _this._updateParameters();
  87676. });
  87677. }
  87678. // Ensure the effect will be rebuilt.
  87679. if (!doNotBuild) {
  87680. this._updateParameters();
  87681. }
  87682. };
  87683. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  87684. /**
  87685. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  87686. */
  87687. get: function () {
  87688. return this.imageProcessingConfiguration.colorCurves;
  87689. },
  87690. /**
  87691. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  87692. */
  87693. set: function (value) {
  87694. this.imageProcessingConfiguration.colorCurves = value;
  87695. },
  87696. enumerable: true,
  87697. configurable: true
  87698. });
  87699. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  87700. /**
  87701. * Gets wether the color curves effect is enabled.
  87702. */
  87703. get: function () {
  87704. return this.imageProcessingConfiguration.colorCurvesEnabled;
  87705. },
  87706. /**
  87707. * Sets wether the color curves effect is enabled.
  87708. */
  87709. set: function (value) {
  87710. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87711. },
  87712. enumerable: true,
  87713. configurable: true
  87714. });
  87715. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  87716. /**
  87717. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  87718. */
  87719. get: function () {
  87720. return this.imageProcessingConfiguration.colorGradingTexture;
  87721. },
  87722. /**
  87723. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  87724. */
  87725. set: function (value) {
  87726. this.imageProcessingConfiguration.colorGradingTexture = value;
  87727. },
  87728. enumerable: true,
  87729. configurable: true
  87730. });
  87731. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  87732. /**
  87733. * Gets wether the color grading effect is enabled.
  87734. */
  87735. get: function () {
  87736. return this.imageProcessingConfiguration.colorGradingEnabled;
  87737. },
  87738. /**
  87739. * Gets wether the color grading effect is enabled.
  87740. */
  87741. set: function (value) {
  87742. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87743. },
  87744. enumerable: true,
  87745. configurable: true
  87746. });
  87747. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  87748. /**
  87749. * Gets exposure used in the effect.
  87750. */
  87751. get: function () {
  87752. return this.imageProcessingConfiguration.exposure;
  87753. },
  87754. /**
  87755. * Sets exposure used in the effect.
  87756. */
  87757. set: function (value) {
  87758. this.imageProcessingConfiguration.exposure = value;
  87759. },
  87760. enumerable: true,
  87761. configurable: true
  87762. });
  87763. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  87764. /**
  87765. * Gets wether tonemapping is enabled or not.
  87766. */
  87767. get: function () {
  87768. return this._imageProcessingConfiguration.toneMappingEnabled;
  87769. },
  87770. /**
  87771. * Sets wether tonemapping is enabled or not
  87772. */
  87773. set: function (value) {
  87774. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87775. },
  87776. enumerable: true,
  87777. configurable: true
  87778. });
  87779. ;
  87780. ;
  87781. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  87782. /**
  87783. * Gets contrast used in the effect.
  87784. */
  87785. get: function () {
  87786. return this.imageProcessingConfiguration.contrast;
  87787. },
  87788. /**
  87789. * Sets contrast used in the effect.
  87790. */
  87791. set: function (value) {
  87792. this.imageProcessingConfiguration.contrast = value;
  87793. },
  87794. enumerable: true,
  87795. configurable: true
  87796. });
  87797. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  87798. /**
  87799. * Gets Vignette stretch size.
  87800. */
  87801. get: function () {
  87802. return this.imageProcessingConfiguration.vignetteStretch;
  87803. },
  87804. /**
  87805. * Sets Vignette stretch size.
  87806. */
  87807. set: function (value) {
  87808. this.imageProcessingConfiguration.vignetteStretch = value;
  87809. },
  87810. enumerable: true,
  87811. configurable: true
  87812. });
  87813. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  87814. /**
  87815. * Gets Vignette centre X Offset.
  87816. */
  87817. get: function () {
  87818. return this.imageProcessingConfiguration.vignetteCentreX;
  87819. },
  87820. /**
  87821. * Sets Vignette centre X Offset.
  87822. */
  87823. set: function (value) {
  87824. this.imageProcessingConfiguration.vignetteCentreX = value;
  87825. },
  87826. enumerable: true,
  87827. configurable: true
  87828. });
  87829. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  87830. /**
  87831. * Gets Vignette centre Y Offset.
  87832. */
  87833. get: function () {
  87834. return this.imageProcessingConfiguration.vignetteCentreY;
  87835. },
  87836. /**
  87837. * Sets Vignette centre Y Offset.
  87838. */
  87839. set: function (value) {
  87840. this.imageProcessingConfiguration.vignetteCentreY = value;
  87841. },
  87842. enumerable: true,
  87843. configurable: true
  87844. });
  87845. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  87846. /**
  87847. * Gets Vignette weight or intensity of the vignette effect.
  87848. */
  87849. get: function () {
  87850. return this.imageProcessingConfiguration.vignetteWeight;
  87851. },
  87852. /**
  87853. * Sets Vignette weight or intensity of the vignette effect.
  87854. */
  87855. set: function (value) {
  87856. this.imageProcessingConfiguration.vignetteWeight = value;
  87857. },
  87858. enumerable: true,
  87859. configurable: true
  87860. });
  87861. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  87862. /**
  87863. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87864. * if vignetteEnabled is set to true.
  87865. */
  87866. get: function () {
  87867. return this.imageProcessingConfiguration.vignetteColor;
  87868. },
  87869. /**
  87870. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87871. * if vignetteEnabled is set to true.
  87872. */
  87873. set: function (value) {
  87874. this.imageProcessingConfiguration.vignetteColor = value;
  87875. },
  87876. enumerable: true,
  87877. configurable: true
  87878. });
  87879. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  87880. /**
  87881. * Gets Camera field of view used by the Vignette effect.
  87882. */
  87883. get: function () {
  87884. return this.imageProcessingConfiguration.vignetteCameraFov;
  87885. },
  87886. /**
  87887. * Sets Camera field of view used by the Vignette effect.
  87888. */
  87889. set: function (value) {
  87890. this.imageProcessingConfiguration.vignetteCameraFov = value;
  87891. },
  87892. enumerable: true,
  87893. configurable: true
  87894. });
  87895. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  87896. /**
  87897. * Gets the vignette blend mode allowing different kind of effect.
  87898. */
  87899. get: function () {
  87900. return this.imageProcessingConfiguration.vignetteBlendMode;
  87901. },
  87902. /**
  87903. * Sets the vignette blend mode allowing different kind of effect.
  87904. */
  87905. set: function (value) {
  87906. this.imageProcessingConfiguration.vignetteBlendMode = value;
  87907. },
  87908. enumerable: true,
  87909. configurable: true
  87910. });
  87911. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  87912. /**
  87913. * Gets wether the vignette effect is enabled.
  87914. */
  87915. get: function () {
  87916. return this.imageProcessingConfiguration.vignetteEnabled;
  87917. },
  87918. /**
  87919. * Sets wether the vignette effect is enabled.
  87920. */
  87921. set: function (value) {
  87922. this.imageProcessingConfiguration.vignetteEnabled = value;
  87923. },
  87924. enumerable: true,
  87925. configurable: true
  87926. });
  87927. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  87928. /**
  87929. * Gets wether the input of the processing is in Gamma or Linear Space.
  87930. */
  87931. get: function () {
  87932. return this._fromLinearSpace;
  87933. },
  87934. /**
  87935. * Sets wether the input of the processing is in Gamma or Linear Space.
  87936. */
  87937. set: function (value) {
  87938. if (this._fromLinearSpace === value) {
  87939. return;
  87940. }
  87941. this._fromLinearSpace = value;
  87942. this._updateParameters();
  87943. },
  87944. enumerable: true,
  87945. configurable: true
  87946. });
  87947. ImageProcessingPostProcess.prototype.getClassName = function () {
  87948. return "ImageProcessingPostProcess";
  87949. };
  87950. ImageProcessingPostProcess.prototype._updateParameters = function () {
  87951. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  87952. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  87953. var defines = "";
  87954. for (var define in this._defines) {
  87955. if (this._defines[define]) {
  87956. defines += "#define " + define + ";\r\n";
  87957. }
  87958. }
  87959. var samplers = ["textureSampler"];
  87960. var uniforms = ["scale"];
  87961. if (BABYLON.ImageProcessingConfiguration) {
  87962. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  87963. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  87964. }
  87965. this.updateEffect(defines, uniforms, samplers);
  87966. };
  87967. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  87968. _super.prototype.dispose.call(this, camera);
  87969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87971. }
  87972. if (this._imageProcessingConfiguration) {
  87973. this.imageProcessingConfiguration.applyByPostProcess = false;
  87974. }
  87975. };
  87976. __decorate([
  87977. BABYLON.serialize()
  87978. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  87979. return ImageProcessingPostProcess;
  87980. }(BABYLON.PostProcess));
  87981. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  87982. })(BABYLON || (BABYLON = {}));
  87983. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  87984. var BABYLON;
  87985. (function (BABYLON) {
  87986. /**
  87987. * Class used to store bone information
  87988. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  87989. */
  87990. var Bone = /** @class */ (function (_super) {
  87991. __extends(Bone, _super);
  87992. /**
  87993. * Create a new bone
  87994. * @param name defines the bone name
  87995. * @param skeleton defines the parent skeleton
  87996. * @param parentBone defines the parent (can be null if the bone is the root)
  87997. * @param localMatrix defines the local matrix
  87998. * @param restPose defines the rest pose matrix
  87999. * @param baseMatrix defines the base matrix
  88000. * @param index defines index of the bone in the hiearchy
  88001. */
  88002. function Bone(
  88003. /**
  88004. * defines the bone name
  88005. */
  88006. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  88007. if (parentBone === void 0) { parentBone = null; }
  88008. if (localMatrix === void 0) { localMatrix = null; }
  88009. if (restPose === void 0) { restPose = null; }
  88010. if (baseMatrix === void 0) { baseMatrix = null; }
  88011. if (index === void 0) { index = null; }
  88012. var _this = _super.call(this, name, skeleton.getScene()) || this;
  88013. _this.name = name;
  88014. /**
  88015. * Gets the list of child bones
  88016. */
  88017. _this.children = new Array();
  88018. /** Gets the animations associated with this bone */
  88019. _this.animations = new Array();
  88020. /**
  88021. * @hidden Internal only
  88022. * Set this value to map this bone to a different index in the transform matrices
  88023. * Set this value to -1 to exclude the bone from the transform matrices
  88024. */
  88025. _this._index = null;
  88026. _this._absoluteTransform = new BABYLON.Matrix();
  88027. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  88028. _this._scalingDeterminant = 1;
  88029. _this._worldTransform = new BABYLON.Matrix();
  88030. _this._needToDecompose = true;
  88031. _this._needToCompose = false;
  88032. _this._skeleton = skeleton;
  88033. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  88034. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  88035. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  88036. _this._index = index;
  88037. skeleton.bones.push(_this);
  88038. _this.setParent(parentBone, false);
  88039. if (baseMatrix || localMatrix) {
  88040. _this._updateDifferenceMatrix();
  88041. }
  88042. return _this;
  88043. }
  88044. Object.defineProperty(Bone.prototype, "_matrix", {
  88045. /** @hidden */
  88046. get: function () {
  88047. this._compose();
  88048. return this._localMatrix;
  88049. },
  88050. /** @hidden */
  88051. set: function (value) {
  88052. this._localMatrix.copyFrom(value);
  88053. this._needToDecompose = true;
  88054. },
  88055. enumerable: true,
  88056. configurable: true
  88057. });
  88058. // Members
  88059. /**
  88060. * Gets the parent skeleton
  88061. * @returns a skeleton
  88062. */
  88063. Bone.prototype.getSkeleton = function () {
  88064. return this._skeleton;
  88065. };
  88066. /**
  88067. * Gets parent bone
  88068. * @returns a bone or null if the bone is the root of the bone hierarchy
  88069. */
  88070. Bone.prototype.getParent = function () {
  88071. return this._parent;
  88072. };
  88073. /**
  88074. * Sets the parent bone
  88075. * @param parent defines the parent (can be null if the bone is the root)
  88076. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88077. */
  88078. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  88079. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88080. if (this._parent === parent) {
  88081. return;
  88082. }
  88083. if (this._parent) {
  88084. var index = this._parent.children.indexOf(this);
  88085. if (index !== -1) {
  88086. this._parent.children.splice(index, 1);
  88087. }
  88088. }
  88089. this._parent = parent;
  88090. if (this._parent) {
  88091. this._parent.children.push(this);
  88092. }
  88093. if (updateDifferenceMatrix) {
  88094. this._updateDifferenceMatrix();
  88095. }
  88096. this.markAsDirty();
  88097. };
  88098. /**
  88099. * Gets the local matrix
  88100. * @returns a matrix
  88101. */
  88102. Bone.prototype.getLocalMatrix = function () {
  88103. this._compose();
  88104. return this._localMatrix;
  88105. };
  88106. /**
  88107. * Gets the base matrix (initial matrix which remains unchanged)
  88108. * @returns a matrix
  88109. */
  88110. Bone.prototype.getBaseMatrix = function () {
  88111. return this._baseMatrix;
  88112. };
  88113. /**
  88114. * Gets the rest pose matrix
  88115. * @returns a matrix
  88116. */
  88117. Bone.prototype.getRestPose = function () {
  88118. return this._restPose;
  88119. };
  88120. /**
  88121. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  88122. */
  88123. Bone.prototype.getWorldMatrix = function () {
  88124. return this._worldTransform;
  88125. };
  88126. /**
  88127. * Sets the local matrix to rest pose matrix
  88128. */
  88129. Bone.prototype.returnToRest = function () {
  88130. this.updateMatrix(this._restPose.clone());
  88131. };
  88132. /**
  88133. * Gets the inverse of the absolute transform matrix.
  88134. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  88135. * @returns a matrix
  88136. */
  88137. Bone.prototype.getInvertedAbsoluteTransform = function () {
  88138. return this._invertedAbsoluteTransform;
  88139. };
  88140. /**
  88141. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  88142. * @returns a matrix
  88143. */
  88144. Bone.prototype.getAbsoluteTransform = function () {
  88145. return this._absoluteTransform;
  88146. };
  88147. Object.defineProperty(Bone.prototype, "position", {
  88148. // Properties (matches AbstractMesh properties)
  88149. /** Gets or sets current position (in local space) */
  88150. get: function () {
  88151. this._decompose();
  88152. return this._localPosition;
  88153. },
  88154. set: function (newPosition) {
  88155. this._decompose();
  88156. this._localPosition.copyFrom(newPosition);
  88157. this._markAsDirtyAndCompose();
  88158. },
  88159. enumerable: true,
  88160. configurable: true
  88161. });
  88162. Object.defineProperty(Bone.prototype, "rotation", {
  88163. /** Gets or sets current rotation (in local space) */
  88164. get: function () {
  88165. return this.getRotation();
  88166. },
  88167. set: function (newRotation) {
  88168. this.setRotation(newRotation);
  88169. },
  88170. enumerable: true,
  88171. configurable: true
  88172. });
  88173. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  88174. /** Gets or sets current rotation quaternion (in local space) */
  88175. get: function () {
  88176. this._decompose();
  88177. return this._localRotation;
  88178. },
  88179. set: function (newRotation) {
  88180. this.setRotationQuaternion(newRotation);
  88181. },
  88182. enumerable: true,
  88183. configurable: true
  88184. });
  88185. Object.defineProperty(Bone.prototype, "scaling", {
  88186. /** Gets or sets current scaling (in local space) */
  88187. get: function () {
  88188. return this.getScale();
  88189. },
  88190. set: function (newScaling) {
  88191. this.setScale(newScaling);
  88192. },
  88193. enumerable: true,
  88194. configurable: true
  88195. });
  88196. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  88197. /**
  88198. * Gets the animation properties override
  88199. */
  88200. get: function () {
  88201. return this._skeleton.animationPropertiesOverride;
  88202. },
  88203. enumerable: true,
  88204. configurable: true
  88205. });
  88206. // Methods
  88207. Bone.prototype._decompose = function () {
  88208. if (!this._needToDecompose) {
  88209. return;
  88210. }
  88211. this._needToDecompose = false;
  88212. if (!this._localScaling) {
  88213. this._localScaling = BABYLON.Vector3.Zero();
  88214. this._localRotation = BABYLON.Quaternion.Zero();
  88215. this._localPosition = BABYLON.Vector3.Zero();
  88216. }
  88217. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  88218. };
  88219. Bone.prototype._compose = function () {
  88220. if (!this._needToCompose) {
  88221. return;
  88222. }
  88223. this._needToCompose = false;
  88224. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  88225. };
  88226. /**
  88227. * Update the base and local matrices
  88228. * @param matrix defines the new base or local matrix
  88229. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88230. * @param updateLocalMatrix defines if the local matrix should be updated
  88231. */
  88232. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  88233. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88234. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  88235. this._baseMatrix.copyFrom(matrix);
  88236. if (updateDifferenceMatrix) {
  88237. this._updateDifferenceMatrix();
  88238. }
  88239. if (updateLocalMatrix) {
  88240. this._localMatrix.copyFrom(matrix);
  88241. this._markAsDirtyAndDecompose();
  88242. }
  88243. else {
  88244. this.markAsDirty();
  88245. }
  88246. };
  88247. /** @hidden */
  88248. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  88249. if (updateChildren === void 0) { updateChildren = true; }
  88250. if (!rootMatrix) {
  88251. rootMatrix = this._baseMatrix;
  88252. }
  88253. if (this._parent) {
  88254. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  88255. }
  88256. else {
  88257. this._absoluteTransform.copyFrom(rootMatrix);
  88258. }
  88259. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  88260. if (updateChildren) {
  88261. for (var index = 0; index < this.children.length; index++) {
  88262. this.children[index]._updateDifferenceMatrix();
  88263. }
  88264. }
  88265. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  88266. };
  88267. /**
  88268. * Flag the bone as dirty (Forcing it to update everything)
  88269. */
  88270. Bone.prototype.markAsDirty = function () {
  88271. this._currentRenderId++;
  88272. this._childRenderId++;
  88273. this._skeleton._markAsDirty();
  88274. };
  88275. Bone.prototype._markAsDirtyAndCompose = function () {
  88276. this.markAsDirty();
  88277. this._needToCompose = true;
  88278. };
  88279. Bone.prototype._markAsDirtyAndDecompose = function () {
  88280. this.markAsDirty();
  88281. this._needToDecompose = true;
  88282. };
  88283. /**
  88284. * Copy an animation range from another bone
  88285. * @param source defines the source bone
  88286. * @param rangeName defines the range name to copy
  88287. * @param frameOffset defines the frame offset
  88288. * @param rescaleAsRequired defines if rescaling must be applied if required
  88289. * @param skelDimensionsRatio defines the scaling ratio
  88290. * @returns true if operation was successful
  88291. */
  88292. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  88293. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  88294. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  88295. // all animation may be coming from a library skeleton, so may need to create animation
  88296. if (this.animations.length === 0) {
  88297. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  88298. this.animations[0].setKeys([]);
  88299. }
  88300. // get animation info / verify there is such a range from the source bone
  88301. var sourceRange = source.animations[0].getRange(rangeName);
  88302. if (!sourceRange) {
  88303. return false;
  88304. }
  88305. var from = sourceRange.from;
  88306. var to = sourceRange.to;
  88307. var sourceKeys = source.animations[0].getKeys();
  88308. // rescaling prep
  88309. var sourceBoneLength = source.length;
  88310. var sourceParent = source.getParent();
  88311. var parent = this.getParent();
  88312. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  88313. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  88314. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  88315. var destKeys = this.animations[0].getKeys();
  88316. // loop vars declaration
  88317. var orig;
  88318. var origTranslation;
  88319. var mat;
  88320. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  88321. orig = sourceKeys[key];
  88322. if (orig.frame >= from && orig.frame <= to) {
  88323. if (rescaleAsRequired) {
  88324. mat = orig.value.clone();
  88325. // scale based on parent ratio, when bone has parent
  88326. if (parentScalingReqd) {
  88327. origTranslation = mat.getTranslation();
  88328. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  88329. // scale based on skeleton dimension ratio when root bone, and value is passed
  88330. }
  88331. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  88332. origTranslation = mat.getTranslation();
  88333. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  88334. // use original when root bone, and no data for skelDimensionsRatio
  88335. }
  88336. else {
  88337. mat = orig.value;
  88338. }
  88339. }
  88340. else {
  88341. mat = orig.value;
  88342. }
  88343. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  88344. }
  88345. }
  88346. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  88347. return true;
  88348. };
  88349. /**
  88350. * Translate the bone in local or world space
  88351. * @param vec The amount to translate the bone
  88352. * @param space The space that the translation is in
  88353. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88354. */
  88355. Bone.prototype.translate = function (vec, space, mesh) {
  88356. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88357. var lm = this.getLocalMatrix();
  88358. if (space == BABYLON.Space.LOCAL) {
  88359. lm.m[12] += vec.x;
  88360. lm.m[13] += vec.y;
  88361. lm.m[14] += vec.z;
  88362. }
  88363. else {
  88364. var wm = null;
  88365. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88366. if (mesh) {
  88367. wm = mesh.getWorldMatrix();
  88368. }
  88369. this._skeleton.computeAbsoluteTransforms();
  88370. var tmat = Bone._tmpMats[0];
  88371. var tvec = Bone._tmpVecs[0];
  88372. if (this._parent) {
  88373. if (mesh && wm) {
  88374. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88375. tmat.multiplyToRef(wm, tmat);
  88376. }
  88377. else {
  88378. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88379. }
  88380. }
  88381. tmat.m[12] = 0;
  88382. tmat.m[13] = 0;
  88383. tmat.m[14] = 0;
  88384. tmat.invert();
  88385. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  88386. lm.m[12] += tvec.x;
  88387. lm.m[13] += tvec.y;
  88388. lm.m[14] += tvec.z;
  88389. }
  88390. this._markAsDirtyAndDecompose();
  88391. };
  88392. /**
  88393. * Set the postion of the bone in local or world space
  88394. * @param position The position to set the bone
  88395. * @param space The space that the position is in
  88396. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88397. */
  88398. Bone.prototype.setPosition = function (position, space, mesh) {
  88399. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88400. var lm = this.getLocalMatrix();
  88401. if (space == BABYLON.Space.LOCAL) {
  88402. lm.m[12] = position.x;
  88403. lm.m[13] = position.y;
  88404. lm.m[14] = position.z;
  88405. }
  88406. else {
  88407. var wm = null;
  88408. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88409. if (mesh) {
  88410. wm = mesh.getWorldMatrix();
  88411. }
  88412. this._skeleton.computeAbsoluteTransforms();
  88413. var tmat = Bone._tmpMats[0];
  88414. var vec = Bone._tmpVecs[0];
  88415. if (this._parent) {
  88416. if (mesh && wm) {
  88417. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88418. tmat.multiplyToRef(wm, tmat);
  88419. }
  88420. else {
  88421. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88422. }
  88423. }
  88424. tmat.invert();
  88425. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  88426. lm.m[12] = vec.x;
  88427. lm.m[13] = vec.y;
  88428. lm.m[14] = vec.z;
  88429. }
  88430. this._markAsDirtyAndDecompose();
  88431. };
  88432. /**
  88433. * Set the absolute position of the bone (world space)
  88434. * @param position The position to set the bone
  88435. * @param mesh The mesh that this bone is attached to
  88436. */
  88437. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  88438. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  88439. };
  88440. /**
  88441. * Scale the bone on the x, y and z axes (in local space)
  88442. * @param x The amount to scale the bone on the x axis
  88443. * @param y The amount to scale the bone on the y axis
  88444. * @param z The amount to scale the bone on the z axis
  88445. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  88446. */
  88447. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  88448. if (scaleChildren === void 0) { scaleChildren = false; }
  88449. var locMat = this.getLocalMatrix();
  88450. // Apply new scaling on top of current local matrix
  88451. var scaleMat = Bone._tmpMats[0];
  88452. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  88453. scaleMat.multiplyToRef(locMat, locMat);
  88454. // Invert scaling matrix and apply the inverse to all children
  88455. scaleMat.invert();
  88456. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  88457. var child = _a[_i];
  88458. var cm = child.getLocalMatrix();
  88459. cm.multiplyToRef(scaleMat, cm);
  88460. cm.m[12] *= x;
  88461. cm.m[13] *= y;
  88462. cm.m[14] *= z;
  88463. child._markAsDirtyAndDecompose();
  88464. }
  88465. this._markAsDirtyAndDecompose();
  88466. if (scaleChildren) {
  88467. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  88468. var child = _c[_b];
  88469. child.scale(x, y, z, scaleChildren);
  88470. }
  88471. }
  88472. };
  88473. /**
  88474. * Set the bone scaling in local space
  88475. * @param scale defines the scaling vector
  88476. */
  88477. Bone.prototype.setScale = function (scale) {
  88478. this._decompose();
  88479. this._localScaling.copyFrom(scale);
  88480. this._markAsDirtyAndCompose();
  88481. };
  88482. /**
  88483. * Gets the current scaling in local space
  88484. * @returns the current scaling vector
  88485. */
  88486. Bone.prototype.getScale = function () {
  88487. this._decompose();
  88488. return this._localScaling;
  88489. };
  88490. /**
  88491. * Gets the current scaling in local space and stores it in a target vector
  88492. * @param result defines the target vector
  88493. */
  88494. Bone.prototype.getScaleToRef = function (result) {
  88495. this._decompose();
  88496. result.copyFrom(this._localScaling);
  88497. };
  88498. /**
  88499. * Set the yaw, pitch, and roll of the bone in local or world space
  88500. * @param yaw The rotation of the bone on the y axis
  88501. * @param pitch The rotation of the bone on the x axis
  88502. * @param roll The rotation of the bone on the z axis
  88503. * @param space The space that the axes of rotation are in
  88504. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88505. */
  88506. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  88507. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88508. if (space === BABYLON.Space.LOCAL) {
  88509. var quat = Bone._tmpQuat;
  88510. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  88511. this.setRotationQuaternion(quat, space, mesh);
  88512. return;
  88513. }
  88514. var rotMatInv = Bone._tmpMats[0];
  88515. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88516. return;
  88517. }
  88518. var rotMat = Bone._tmpMats[1];
  88519. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  88520. rotMatInv.multiplyToRef(rotMat, rotMat);
  88521. this._rotateWithMatrix(rotMat, space, mesh);
  88522. };
  88523. /**
  88524. * Add a rotation to the bone on an axis in local or world space
  88525. * @param axis The axis to rotate the bone on
  88526. * @param amount The amount to rotate the bone
  88527. * @param space The space that the axis is in
  88528. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88529. */
  88530. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  88531. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88532. var rmat = Bone._tmpMats[0];
  88533. rmat.m[12] = 0;
  88534. rmat.m[13] = 0;
  88535. rmat.m[14] = 0;
  88536. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  88537. this._rotateWithMatrix(rmat, space, mesh);
  88538. };
  88539. /**
  88540. * Set the rotation of the bone to a particular axis angle in local or world space
  88541. * @param axis The axis to rotate the bone on
  88542. * @param angle The angle that the bone should be rotated to
  88543. * @param space The space that the axis is in
  88544. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88545. */
  88546. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  88547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88548. if (space === BABYLON.Space.LOCAL) {
  88549. var quat = Bone._tmpQuat;
  88550. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  88551. this.setRotationQuaternion(quat, space, mesh);
  88552. return;
  88553. }
  88554. var rotMatInv = Bone._tmpMats[0];
  88555. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88556. return;
  88557. }
  88558. var rotMat = Bone._tmpMats[1];
  88559. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  88560. rotMatInv.multiplyToRef(rotMat, rotMat);
  88561. this._rotateWithMatrix(rotMat, space, mesh);
  88562. };
  88563. /**
  88564. * Set the euler rotation of the bone in local of world space
  88565. * @param rotation The euler rotation that the bone should be set to
  88566. * @param space The space that the rotation is in
  88567. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88568. */
  88569. Bone.prototype.setRotation = function (rotation, space, mesh) {
  88570. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88571. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  88572. };
  88573. /**
  88574. * Set the quaternion rotation of the bone in local of world space
  88575. * @param quat The quaternion rotation that the bone should be set to
  88576. * @param space The space that the rotation is in
  88577. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88578. */
  88579. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  88580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88581. if (space === BABYLON.Space.LOCAL) {
  88582. this._decompose();
  88583. this._localRotation.copyFrom(quat);
  88584. this._markAsDirtyAndCompose();
  88585. return;
  88586. }
  88587. var rotMatInv = Bone._tmpMats[0];
  88588. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88589. return;
  88590. }
  88591. var rotMat = Bone._tmpMats[1];
  88592. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  88593. rotMatInv.multiplyToRef(rotMat, rotMat);
  88594. this._rotateWithMatrix(rotMat, space, mesh);
  88595. };
  88596. /**
  88597. * Set the rotation matrix of the bone in local of world space
  88598. * @param rotMat The rotation matrix that the bone should be set to
  88599. * @param space The space that the rotation is in
  88600. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88601. */
  88602. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  88603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88604. if (space === BABYLON.Space.LOCAL) {
  88605. var quat = Bone._tmpQuat;
  88606. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  88607. this.setRotationQuaternion(quat, space, mesh);
  88608. return;
  88609. }
  88610. var rotMatInv = Bone._tmpMats[0];
  88611. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88612. return;
  88613. }
  88614. var rotMat2 = Bone._tmpMats[1];
  88615. rotMat2.copyFrom(rotMat);
  88616. rotMatInv.multiplyToRef(rotMat, rotMat2);
  88617. this._rotateWithMatrix(rotMat2, space, mesh);
  88618. };
  88619. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  88620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88621. var lmat = this.getLocalMatrix();
  88622. var lx = lmat.m[12];
  88623. var ly = lmat.m[13];
  88624. var lz = lmat.m[14];
  88625. var parent = this.getParent();
  88626. var parentScale = Bone._tmpMats[3];
  88627. var parentScaleInv = Bone._tmpMats[4];
  88628. if (parent && space == BABYLON.Space.WORLD) {
  88629. if (mesh) {
  88630. parentScale.copyFrom(mesh.getWorldMatrix());
  88631. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  88632. }
  88633. else {
  88634. parentScale.copyFrom(parent.getAbsoluteTransform());
  88635. }
  88636. parentScaleInv.copyFrom(parentScale);
  88637. parentScaleInv.invert();
  88638. lmat.multiplyToRef(parentScale, lmat);
  88639. lmat.multiplyToRef(rmat, lmat);
  88640. lmat.multiplyToRef(parentScaleInv, lmat);
  88641. }
  88642. else {
  88643. if (space == BABYLON.Space.WORLD && mesh) {
  88644. parentScale.copyFrom(mesh.getWorldMatrix());
  88645. parentScaleInv.copyFrom(parentScale);
  88646. parentScaleInv.invert();
  88647. lmat.multiplyToRef(parentScale, lmat);
  88648. lmat.multiplyToRef(rmat, lmat);
  88649. lmat.multiplyToRef(parentScaleInv, lmat);
  88650. }
  88651. else {
  88652. lmat.multiplyToRef(rmat, lmat);
  88653. }
  88654. }
  88655. lmat.m[12] = lx;
  88656. lmat.m[13] = ly;
  88657. lmat.m[14] = lz;
  88658. this.computeAbsoluteTransforms();
  88659. this._markAsDirtyAndDecompose();
  88660. };
  88661. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  88662. var scaleMatrix = Bone._tmpMats[2];
  88663. rotMatInv.copyFrom(this.getAbsoluteTransform());
  88664. if (mesh) {
  88665. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  88666. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  88667. }
  88668. rotMatInv.invert();
  88669. if (isNaN(rotMatInv.m[0])) {
  88670. // Matrix failed to invert.
  88671. // This can happen if scale is zero for example.
  88672. return false;
  88673. }
  88674. scaleMatrix.m[0] *= this._scalingDeterminant;
  88675. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  88676. return true;
  88677. };
  88678. /**
  88679. * Get the position of the bone in local or world space
  88680. * @param space The space that the returned position is in
  88681. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88682. * @returns The position of the bone
  88683. */
  88684. Bone.prototype.getPosition = function (space, mesh) {
  88685. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88686. if (mesh === void 0) { mesh = null; }
  88687. var pos = BABYLON.Vector3.Zero();
  88688. this.getPositionToRef(space, mesh, pos);
  88689. return pos;
  88690. };
  88691. /**
  88692. * Copy the position of the bone to a vector3 in local or world space
  88693. * @param space The space that the returned position is in
  88694. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88695. * @param result The vector3 to copy the position to
  88696. */
  88697. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  88698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88699. if (space == BABYLON.Space.LOCAL) {
  88700. var lm = this.getLocalMatrix();
  88701. result.x = lm.m[12];
  88702. result.y = lm.m[13];
  88703. result.z = lm.m[14];
  88704. }
  88705. else {
  88706. var wm = null;
  88707. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88708. if (mesh) {
  88709. wm = mesh.getWorldMatrix();
  88710. }
  88711. this._skeleton.computeAbsoluteTransforms();
  88712. var tmat = Bone._tmpMats[0];
  88713. if (mesh && wm) {
  88714. tmat.copyFrom(this.getAbsoluteTransform());
  88715. tmat.multiplyToRef(wm, tmat);
  88716. }
  88717. else {
  88718. tmat = this.getAbsoluteTransform();
  88719. }
  88720. result.x = tmat.m[12];
  88721. result.y = tmat.m[13];
  88722. result.z = tmat.m[14];
  88723. }
  88724. };
  88725. /**
  88726. * Get the absolute position of the bone (world space)
  88727. * @param mesh The mesh that this bone is attached to
  88728. * @returns The absolute position of the bone
  88729. */
  88730. Bone.prototype.getAbsolutePosition = function (mesh) {
  88731. if (mesh === void 0) { mesh = null; }
  88732. var pos = BABYLON.Vector3.Zero();
  88733. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  88734. return pos;
  88735. };
  88736. /**
  88737. * Copy the absolute position of the bone (world space) to the result param
  88738. * @param mesh The mesh that this bone is attached to
  88739. * @param result The vector3 to copy the absolute position to
  88740. */
  88741. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  88742. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  88743. };
  88744. /**
  88745. * Compute the absolute transforms of this bone and its children
  88746. */
  88747. Bone.prototype.computeAbsoluteTransforms = function () {
  88748. this._compose();
  88749. if (this._parent) {
  88750. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  88751. }
  88752. else {
  88753. this._absoluteTransform.copyFrom(this._localMatrix);
  88754. var poseMatrix = this._skeleton.getPoseMatrix();
  88755. if (poseMatrix) {
  88756. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  88757. }
  88758. }
  88759. var children = this.children;
  88760. var len = children.length;
  88761. for (var i = 0; i < len; i++) {
  88762. children[i].computeAbsoluteTransforms();
  88763. }
  88764. };
  88765. /**
  88766. * Get the world direction from an axis that is in the local space of the bone
  88767. * @param localAxis The local direction that is used to compute the world direction
  88768. * @param mesh The mesh that this bone is attached to
  88769. * @returns The world direction
  88770. */
  88771. Bone.prototype.getDirection = function (localAxis, mesh) {
  88772. if (mesh === void 0) { mesh = null; }
  88773. var result = BABYLON.Vector3.Zero();
  88774. this.getDirectionToRef(localAxis, mesh, result);
  88775. return result;
  88776. };
  88777. /**
  88778. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  88779. * @param localAxis The local direction that is used to compute the world direction
  88780. * @param mesh The mesh that this bone is attached to
  88781. * @param result The vector3 that the world direction will be copied to
  88782. */
  88783. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  88784. if (mesh === void 0) { mesh = null; }
  88785. var wm = null;
  88786. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88787. if (mesh) {
  88788. wm = mesh.getWorldMatrix();
  88789. }
  88790. this._skeleton.computeAbsoluteTransforms();
  88791. var mat = Bone._tmpMats[0];
  88792. mat.copyFrom(this.getAbsoluteTransform());
  88793. if (mesh && wm) {
  88794. mat.multiplyToRef(wm, mat);
  88795. }
  88796. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  88797. result.normalize();
  88798. };
  88799. /**
  88800. * Get the euler rotation of the bone in local or world space
  88801. * @param space The space that the rotation should be in
  88802. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88803. * @returns The euler rotation
  88804. */
  88805. Bone.prototype.getRotation = function (space, mesh) {
  88806. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88807. if (mesh === void 0) { mesh = null; }
  88808. var result = BABYLON.Vector3.Zero();
  88809. this.getRotationToRef(space, mesh, result);
  88810. return result;
  88811. };
  88812. /**
  88813. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  88814. * @param space The space that the rotation should be in
  88815. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88816. * @param result The vector3 that the rotation should be copied to
  88817. */
  88818. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  88819. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88820. if (mesh === void 0) { mesh = null; }
  88821. var quat = Bone._tmpQuat;
  88822. this.getRotationQuaternionToRef(space, mesh, quat);
  88823. quat.toEulerAnglesToRef(result);
  88824. };
  88825. /**
  88826. * Get the quaternion rotation of the bone in either local or world space
  88827. * @param space The space that the rotation should be in
  88828. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88829. * @returns The quaternion rotation
  88830. */
  88831. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  88832. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88833. if (mesh === void 0) { mesh = null; }
  88834. var result = BABYLON.Quaternion.Identity();
  88835. this.getRotationQuaternionToRef(space, mesh, result);
  88836. return result;
  88837. };
  88838. /**
  88839. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  88840. * @param space The space that the rotation should be in
  88841. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88842. * @param result The quaternion that the rotation should be copied to
  88843. */
  88844. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  88845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88846. if (mesh === void 0) { mesh = null; }
  88847. if (space == BABYLON.Space.LOCAL) {
  88848. this._decompose();
  88849. result.copyFrom(this._localRotation);
  88850. }
  88851. else {
  88852. var mat = Bone._tmpMats[0];
  88853. var amat = this.getAbsoluteTransform();
  88854. if (mesh) {
  88855. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88856. }
  88857. else {
  88858. mat.copyFrom(amat);
  88859. }
  88860. mat.m[0] *= this._scalingDeterminant;
  88861. mat.m[1] *= this._scalingDeterminant;
  88862. mat.m[2] *= this._scalingDeterminant;
  88863. mat.decompose(undefined, result, undefined);
  88864. }
  88865. };
  88866. /**
  88867. * Get the rotation matrix of the bone in local or world space
  88868. * @param space The space that the rotation should be in
  88869. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88870. * @returns The rotation matrix
  88871. */
  88872. Bone.prototype.getRotationMatrix = function (space, mesh) {
  88873. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88874. var result = BABYLON.Matrix.Identity();
  88875. this.getRotationMatrixToRef(space, mesh, result);
  88876. return result;
  88877. };
  88878. /**
  88879. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  88880. * @param space The space that the rotation should be in
  88881. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88882. * @param result The quaternion that the rotation should be copied to
  88883. */
  88884. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  88885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88886. if (space == BABYLON.Space.LOCAL) {
  88887. this.getLocalMatrix().getRotationMatrixToRef(result);
  88888. }
  88889. else {
  88890. var mat = Bone._tmpMats[0];
  88891. var amat = this.getAbsoluteTransform();
  88892. if (mesh) {
  88893. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88894. }
  88895. else {
  88896. mat.copyFrom(amat);
  88897. }
  88898. mat.m[0] *= this._scalingDeterminant;
  88899. mat.m[1] *= this._scalingDeterminant;
  88900. mat.m[2] *= this._scalingDeterminant;
  88901. mat.getRotationMatrixToRef(result);
  88902. }
  88903. };
  88904. /**
  88905. * Get the world position of a point that is in the local space of the bone
  88906. * @param position The local position
  88907. * @param mesh The mesh that this bone is attached to
  88908. * @returns The world position
  88909. */
  88910. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  88911. if (mesh === void 0) { mesh = null; }
  88912. var result = BABYLON.Vector3.Zero();
  88913. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  88914. return result;
  88915. };
  88916. /**
  88917. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  88918. * @param position The local position
  88919. * @param mesh The mesh that this bone is attached to
  88920. * @param result The vector3 that the world position should be copied to
  88921. */
  88922. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  88923. if (mesh === void 0) { mesh = null; }
  88924. var wm = null;
  88925. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88926. if (mesh) {
  88927. wm = mesh.getWorldMatrix();
  88928. }
  88929. this._skeleton.computeAbsoluteTransforms();
  88930. var tmat = Bone._tmpMats[0];
  88931. if (mesh && wm) {
  88932. tmat.copyFrom(this.getAbsoluteTransform());
  88933. tmat.multiplyToRef(wm, tmat);
  88934. }
  88935. else {
  88936. tmat = this.getAbsoluteTransform();
  88937. }
  88938. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  88939. };
  88940. /**
  88941. * Get the local position of a point that is in world space
  88942. * @param position The world position
  88943. * @param mesh The mesh that this bone is attached to
  88944. * @returns The local position
  88945. */
  88946. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  88947. if (mesh === void 0) { mesh = null; }
  88948. var result = BABYLON.Vector3.Zero();
  88949. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  88950. return result;
  88951. };
  88952. /**
  88953. * Get the local position of a point that is in world space and copy it to the result param
  88954. * @param position The world position
  88955. * @param mesh The mesh that this bone is attached to
  88956. * @param result The vector3 that the local position should be copied to
  88957. */
  88958. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  88959. if (mesh === void 0) { mesh = null; }
  88960. var wm = null;
  88961. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88962. if (mesh) {
  88963. wm = mesh.getWorldMatrix();
  88964. }
  88965. this._skeleton.computeAbsoluteTransforms();
  88966. var tmat = Bone._tmpMats[0];
  88967. tmat.copyFrom(this.getAbsoluteTransform());
  88968. if (mesh && wm) {
  88969. tmat.multiplyToRef(wm, tmat);
  88970. }
  88971. tmat.invert();
  88972. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  88973. };
  88974. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88975. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  88976. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88977. return Bone;
  88978. }(BABYLON.Node));
  88979. BABYLON.Bone = Bone;
  88980. })(BABYLON || (BABYLON = {}));
  88981. //# sourceMappingURL=babylon.bone.js.map
  88982. var BABYLON;
  88983. (function (BABYLON) {
  88984. /**
  88985. * Class used to apply inverse kinematics to bones
  88986. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  88987. */
  88988. var BoneIKController = /** @class */ (function () {
  88989. /**
  88990. * Creates a new BoneIKController
  88991. * @param mesh defines the mesh to control
  88992. * @param bone defines the bone to control
  88993. * @param options defines options to set up the controller
  88994. */
  88995. function BoneIKController(mesh, bone, options) {
  88996. /**
  88997. * Gets or sets the target position
  88998. */
  88999. this.targetPosition = BABYLON.Vector3.Zero();
  89000. /**
  89001. * Gets or sets the pole target position
  89002. */
  89003. this.poleTargetPosition = BABYLON.Vector3.Zero();
  89004. /**
  89005. * Gets or sets the pole target local offset
  89006. */
  89007. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  89008. /**
  89009. * Gets or sets the pole angle
  89010. */
  89011. this.poleAngle = 0;
  89012. /**
  89013. * 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)
  89014. */
  89015. this.slerpAmount = 1;
  89016. this._bone1Quat = BABYLON.Quaternion.Identity();
  89017. this._bone1Mat = BABYLON.Matrix.Identity();
  89018. this._bone2Ang = Math.PI;
  89019. this._maxAngle = Math.PI;
  89020. this._rightHandedSystem = false;
  89021. this._bendAxis = BABYLON.Vector3.Right();
  89022. this._slerping = false;
  89023. this._adjustRoll = 0;
  89024. this._bone2 = bone;
  89025. this._bone1 = bone.getParent();
  89026. if (!this._bone1) {
  89027. return;
  89028. }
  89029. this.mesh = mesh;
  89030. var bonePos = bone.getPosition();
  89031. if (bone.getAbsoluteTransform().determinant() > 0) {
  89032. this._rightHandedSystem = true;
  89033. this._bendAxis.x = 0;
  89034. this._bendAxis.y = 0;
  89035. this._bendAxis.z = -1;
  89036. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  89037. this._adjustRoll = Math.PI * .5;
  89038. this._bendAxis.z = 1;
  89039. }
  89040. }
  89041. if (this._bone1.length) {
  89042. var boneScale1 = this._bone1.getScale();
  89043. var boneScale2 = this._bone2.getScale();
  89044. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  89045. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  89046. }
  89047. else if (this._bone1.children[0]) {
  89048. mesh.computeWorldMatrix(true);
  89049. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  89050. var pos2 = this._bone2.getAbsolutePosition(mesh);
  89051. var pos3 = this._bone1.getAbsolutePosition(mesh);
  89052. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  89053. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  89054. }
  89055. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  89056. this.maxAngle = Math.PI;
  89057. if (options) {
  89058. if (options.targetMesh) {
  89059. this.targetMesh = options.targetMesh;
  89060. this.targetMesh.computeWorldMatrix(true);
  89061. }
  89062. if (options.poleTargetMesh) {
  89063. this.poleTargetMesh = options.poleTargetMesh;
  89064. this.poleTargetMesh.computeWorldMatrix(true);
  89065. }
  89066. else if (options.poleTargetBone) {
  89067. this.poleTargetBone = options.poleTargetBone;
  89068. }
  89069. else if (this._bone1.getParent()) {
  89070. this.poleTargetBone = this._bone1.getParent();
  89071. }
  89072. if (options.poleTargetLocalOffset) {
  89073. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  89074. }
  89075. if (options.poleAngle) {
  89076. this.poleAngle = options.poleAngle;
  89077. }
  89078. if (options.bendAxis) {
  89079. this._bendAxis.copyFrom(options.bendAxis);
  89080. }
  89081. if (options.maxAngle) {
  89082. this.maxAngle = options.maxAngle;
  89083. }
  89084. if (options.slerpAmount) {
  89085. this.slerpAmount = options.slerpAmount;
  89086. }
  89087. }
  89088. }
  89089. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  89090. /**
  89091. * Gets or sets maximum allowed angle
  89092. */
  89093. get: function () {
  89094. return this._maxAngle;
  89095. },
  89096. set: function (value) {
  89097. this._setMaxAngle(value);
  89098. },
  89099. enumerable: true,
  89100. configurable: true
  89101. });
  89102. BoneIKController.prototype._setMaxAngle = function (ang) {
  89103. if (ang < 0) {
  89104. ang = 0;
  89105. }
  89106. if (ang > Math.PI || ang == undefined) {
  89107. ang = Math.PI;
  89108. }
  89109. this._maxAngle = ang;
  89110. var a = this._bone1Length;
  89111. var b = this._bone2Length;
  89112. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  89113. };
  89114. /**
  89115. * Force the controller to update the bones
  89116. */
  89117. BoneIKController.prototype.update = function () {
  89118. var bone1 = this._bone1;
  89119. if (!bone1) {
  89120. return;
  89121. }
  89122. var target = this.targetPosition;
  89123. var poleTarget = this.poleTargetPosition;
  89124. var mat1 = BoneIKController._tmpMats[0];
  89125. var mat2 = BoneIKController._tmpMats[1];
  89126. if (this.targetMesh) {
  89127. target.copyFrom(this.targetMesh.getAbsolutePosition());
  89128. }
  89129. if (this.poleTargetBone) {
  89130. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  89131. }
  89132. else if (this.poleTargetMesh) {
  89133. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  89134. }
  89135. var bonePos = BoneIKController._tmpVecs[0];
  89136. var zaxis = BoneIKController._tmpVecs[1];
  89137. var xaxis = BoneIKController._tmpVecs[2];
  89138. var yaxis = BoneIKController._tmpVecs[3];
  89139. var upAxis = BoneIKController._tmpVecs[4];
  89140. var _tmpQuat = BoneIKController._tmpQuat;
  89141. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  89142. poleTarget.subtractToRef(bonePos, upAxis);
  89143. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  89144. upAxis.y = 1;
  89145. }
  89146. else {
  89147. upAxis.normalize();
  89148. }
  89149. target.subtractToRef(bonePos, yaxis);
  89150. yaxis.normalize();
  89151. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  89152. zaxis.normalize();
  89153. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  89154. xaxis.normalize();
  89155. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  89156. var a = this._bone1Length;
  89157. var b = this._bone2Length;
  89158. var c = BABYLON.Vector3.Distance(bonePos, target);
  89159. if (this._maxReach > 0) {
  89160. c = Math.min(this._maxReach, c);
  89161. }
  89162. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  89163. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  89164. if (acosa > 1) {
  89165. acosa = 1;
  89166. }
  89167. if (acosb > 1) {
  89168. acosb = 1;
  89169. }
  89170. if (acosa < -1) {
  89171. acosa = -1;
  89172. }
  89173. if (acosb < -1) {
  89174. acosb = -1;
  89175. }
  89176. var angA = Math.acos(acosa);
  89177. var angB = Math.acos(acosb);
  89178. var angC = -angA - angB;
  89179. if (this._rightHandedSystem) {
  89180. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  89181. mat2.multiplyToRef(mat1, mat1);
  89182. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  89183. mat2.multiplyToRef(mat1, mat1);
  89184. }
  89185. else {
  89186. var _tmpVec = BoneIKController._tmpVecs[5];
  89187. _tmpVec.copyFrom(this._bendAxis);
  89188. _tmpVec.x *= -1;
  89189. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  89190. mat2.multiplyToRef(mat1, mat1);
  89191. }
  89192. if (this.poleAngle) {
  89193. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  89194. mat1.multiplyToRef(mat2, mat1);
  89195. }
  89196. if (this._bone1) {
  89197. if (this.slerpAmount < 1) {
  89198. if (!this._slerping) {
  89199. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  89200. }
  89201. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  89202. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  89203. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  89204. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  89205. this._slerping = true;
  89206. }
  89207. else {
  89208. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  89209. this._bone1Mat.copyFrom(mat1);
  89210. this._slerping = false;
  89211. }
  89212. }
  89213. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  89214. this._bone2Ang = angC;
  89215. };
  89216. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89217. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  89218. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89219. return BoneIKController;
  89220. }());
  89221. BABYLON.BoneIKController = BoneIKController;
  89222. })(BABYLON || (BABYLON = {}));
  89223. //# sourceMappingURL=babylon.boneIKController.js.map
  89224. var BABYLON;
  89225. (function (BABYLON) {
  89226. /**
  89227. * Class used to make a bone look toward a point in space
  89228. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  89229. */
  89230. var BoneLookController = /** @class */ (function () {
  89231. /**
  89232. * Create a BoneLookController
  89233. * @param mesh the mesh that the bone belongs to
  89234. * @param bone the bone that will be looking to the target
  89235. * @param target the target Vector3 to look at
  89236. * @param settings optional settings:
  89237. * * maxYaw: the maximum angle the bone will yaw to
  89238. * * minYaw: the minimum angle the bone will yaw to
  89239. * * maxPitch: the maximum angle the bone will pitch to
  89240. * * minPitch: the minimum angle the bone will yaw to
  89241. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  89242. * * upAxis: the up axis of the coordinate system
  89243. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  89244. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  89245. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  89246. * * adjustYaw: used to make an adjustment to the yaw of the bone
  89247. * * adjustPitch: used to make an adjustment to the pitch of the bone
  89248. * * adjustRoll: used to make an adjustment to the roll of the bone
  89249. **/
  89250. function BoneLookController(mesh, bone, target, options) {
  89251. /**
  89252. * The up axis of the coordinate system that is used when the bone is rotated
  89253. */
  89254. this.upAxis = BABYLON.Vector3.Up();
  89255. /**
  89256. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  89257. */
  89258. this.upAxisSpace = BABYLON.Space.LOCAL;
  89259. /**
  89260. * Used to make an adjustment to the yaw of the bone
  89261. */
  89262. this.adjustYaw = 0;
  89263. /**
  89264. * Used to make an adjustment to the pitch of the bone
  89265. */
  89266. this.adjustPitch = 0;
  89267. /**
  89268. * Used to make an adjustment to the roll of the bone
  89269. */
  89270. this.adjustRoll = 0;
  89271. /**
  89272. * 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)
  89273. */
  89274. this.slerpAmount = 1;
  89275. this._boneQuat = BABYLON.Quaternion.Identity();
  89276. this._slerping = false;
  89277. this._firstFrameSkipped = false;
  89278. this._fowardAxis = BABYLON.Vector3.Forward();
  89279. this.mesh = mesh;
  89280. this.bone = bone;
  89281. this.target = target;
  89282. if (options) {
  89283. if (options.adjustYaw) {
  89284. this.adjustYaw = options.adjustYaw;
  89285. }
  89286. if (options.adjustPitch) {
  89287. this.adjustPitch = options.adjustPitch;
  89288. }
  89289. if (options.adjustRoll) {
  89290. this.adjustRoll = options.adjustRoll;
  89291. }
  89292. if (options.maxYaw != null) {
  89293. this.maxYaw = options.maxYaw;
  89294. }
  89295. else {
  89296. this.maxYaw = Math.PI;
  89297. }
  89298. if (options.minYaw != null) {
  89299. this.minYaw = options.minYaw;
  89300. }
  89301. else {
  89302. this.minYaw = -Math.PI;
  89303. }
  89304. if (options.maxPitch != null) {
  89305. this.maxPitch = options.maxPitch;
  89306. }
  89307. else {
  89308. this.maxPitch = Math.PI;
  89309. }
  89310. if (options.minPitch != null) {
  89311. this.minPitch = options.minPitch;
  89312. }
  89313. else {
  89314. this.minPitch = -Math.PI;
  89315. }
  89316. if (options.slerpAmount != null) {
  89317. this.slerpAmount = options.slerpAmount;
  89318. }
  89319. if (options.upAxis != null) {
  89320. this.upAxis = options.upAxis;
  89321. }
  89322. if (options.upAxisSpace != null) {
  89323. this.upAxisSpace = options.upAxisSpace;
  89324. }
  89325. if (options.yawAxis != null || options.pitchAxis != null) {
  89326. var newYawAxis = BABYLON.Axis.Y;
  89327. var newPitchAxis = BABYLON.Axis.X;
  89328. if (options.yawAxis != null) {
  89329. newYawAxis = options.yawAxis.clone();
  89330. newYawAxis.normalize();
  89331. }
  89332. if (options.pitchAxis != null) {
  89333. newPitchAxis = options.pitchAxis.clone();
  89334. newPitchAxis.normalize();
  89335. }
  89336. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  89337. this._transformYawPitch = BABYLON.Matrix.Identity();
  89338. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  89339. this._transformYawPitchInv = this._transformYawPitch.clone();
  89340. this._transformYawPitch.invert();
  89341. }
  89342. }
  89343. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  89344. this.upAxisSpace = BABYLON.Space.LOCAL;
  89345. }
  89346. }
  89347. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  89348. /**
  89349. * Gets or sets the minimum yaw angle that the bone can look to
  89350. */
  89351. get: function () {
  89352. return this._minYaw;
  89353. },
  89354. set: function (value) {
  89355. this._minYaw = value;
  89356. this._minYawSin = Math.sin(value);
  89357. this._minYawCos = Math.cos(value);
  89358. if (this._maxYaw != null) {
  89359. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  89360. this._yawRange = this._maxYaw - this._minYaw;
  89361. }
  89362. },
  89363. enumerable: true,
  89364. configurable: true
  89365. });
  89366. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  89367. /**
  89368. * Gets or sets the maximum yaw angle that the bone can look to
  89369. */
  89370. get: function () {
  89371. return this._maxYaw;
  89372. },
  89373. set: function (value) {
  89374. this._maxYaw = value;
  89375. this._maxYawSin = Math.sin(value);
  89376. this._maxYawCos = Math.cos(value);
  89377. if (this._minYaw != null) {
  89378. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  89379. this._yawRange = this._maxYaw - this._minYaw;
  89380. }
  89381. },
  89382. enumerable: true,
  89383. configurable: true
  89384. });
  89385. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  89386. /**
  89387. * Gets or sets the minimum pitch angle that the bone can look to
  89388. */
  89389. get: function () {
  89390. return this._minPitch;
  89391. },
  89392. set: function (value) {
  89393. this._minPitch = value;
  89394. this._minPitchTan = Math.tan(value);
  89395. },
  89396. enumerable: true,
  89397. configurable: true
  89398. });
  89399. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  89400. /**
  89401. * Gets or sets the maximum pitch angle that the bone can look to
  89402. */
  89403. get: function () {
  89404. return this._maxPitch;
  89405. },
  89406. set: function (value) {
  89407. this._maxPitch = value;
  89408. this._maxPitchTan = Math.tan(value);
  89409. },
  89410. enumerable: true,
  89411. configurable: true
  89412. });
  89413. /**
  89414. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  89415. */
  89416. BoneLookController.prototype.update = function () {
  89417. //skip the first frame when slerping so that the mesh rotation is correct
  89418. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  89419. this._firstFrameSkipped = true;
  89420. return;
  89421. }
  89422. var bone = this.bone;
  89423. var bonePos = BoneLookController._tmpVecs[0];
  89424. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  89425. var target = this.target;
  89426. var _tmpMat1 = BoneLookController._tmpMats[0];
  89427. var _tmpMat2 = BoneLookController._tmpMats[1];
  89428. var mesh = this.mesh;
  89429. var parentBone = bone.getParent();
  89430. var upAxis = BoneLookController._tmpVecs[1];
  89431. upAxis.copyFrom(this.upAxis);
  89432. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  89433. if (this._transformYawPitch) {
  89434. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  89435. }
  89436. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  89437. }
  89438. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  89439. mesh.getDirectionToRef(upAxis, upAxis);
  89440. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  89441. upAxis.normalize();
  89442. }
  89443. }
  89444. var checkYaw = false;
  89445. var checkPitch = false;
  89446. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  89447. checkYaw = true;
  89448. }
  89449. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  89450. checkPitch = true;
  89451. }
  89452. if (checkYaw || checkPitch) {
  89453. var spaceMat = BoneLookController._tmpMats[2];
  89454. var spaceMatInv = BoneLookController._tmpMats[3];
  89455. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  89456. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  89457. }
  89458. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  89459. spaceMat.copyFrom(mesh.getWorldMatrix());
  89460. }
  89461. else {
  89462. var forwardAxis = BoneLookController._tmpVecs[2];
  89463. forwardAxis.copyFrom(this._fowardAxis);
  89464. if (this._transformYawPitch) {
  89465. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  89466. }
  89467. if (parentBone) {
  89468. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  89469. }
  89470. else {
  89471. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  89472. }
  89473. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  89474. rightAxis.normalize();
  89475. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  89476. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  89477. }
  89478. spaceMat.invertToRef(spaceMatInv);
  89479. var xzlen = null;
  89480. if (checkPitch) {
  89481. var localTarget = BoneLookController._tmpVecs[3];
  89482. target.subtractToRef(bonePos, localTarget);
  89483. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  89484. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  89485. var pitch = Math.atan2(localTarget.y, xzlen);
  89486. var newPitch = pitch;
  89487. if (pitch > this._maxPitch) {
  89488. localTarget.y = this._maxPitchTan * xzlen;
  89489. newPitch = this._maxPitch;
  89490. }
  89491. else if (pitch < this._minPitch) {
  89492. localTarget.y = this._minPitchTan * xzlen;
  89493. newPitch = this._minPitch;
  89494. }
  89495. if (pitch != newPitch) {
  89496. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  89497. localTarget.addInPlace(bonePos);
  89498. target = localTarget;
  89499. }
  89500. }
  89501. if (checkYaw) {
  89502. var localTarget = BoneLookController._tmpVecs[4];
  89503. target.subtractToRef(bonePos, localTarget);
  89504. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  89505. var yaw = Math.atan2(localTarget.x, localTarget.z);
  89506. var newYaw = yaw;
  89507. if (yaw > this._maxYaw || yaw < this._minYaw) {
  89508. if (xzlen == null) {
  89509. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  89510. }
  89511. if (this._yawRange > Math.PI) {
  89512. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  89513. localTarget.z = this._maxYawCos * xzlen;
  89514. localTarget.x = this._maxYawSin * xzlen;
  89515. newYaw = this._maxYaw;
  89516. }
  89517. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  89518. localTarget.z = this._minYawCos * xzlen;
  89519. localTarget.x = this._minYawSin * xzlen;
  89520. newYaw = this._minYaw;
  89521. }
  89522. }
  89523. else {
  89524. if (yaw > this._maxYaw) {
  89525. localTarget.z = this._maxYawCos * xzlen;
  89526. localTarget.x = this._maxYawSin * xzlen;
  89527. newYaw = this._maxYaw;
  89528. }
  89529. else if (yaw < this._minYaw) {
  89530. localTarget.z = this._minYawCos * xzlen;
  89531. localTarget.x = this._minYawSin * xzlen;
  89532. newYaw = this._minYaw;
  89533. }
  89534. }
  89535. }
  89536. if (this._slerping && this._yawRange > Math.PI) {
  89537. //are we going to be crossing into the min/max region?
  89538. var boneFwd = BoneLookController._tmpVecs[8];
  89539. boneFwd.copyFrom(BABYLON.Axis.Z);
  89540. if (this._transformYawPitch) {
  89541. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  89542. }
  89543. var boneRotMat = BoneLookController._tmpMats[4];
  89544. this._boneQuat.toRotationMatrix(boneRotMat);
  89545. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  89546. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  89547. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  89548. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  89549. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  89550. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  89551. if (angBtwTar > angBtwMidYaw) {
  89552. if (xzlen == null) {
  89553. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  89554. }
  89555. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  89556. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  89557. if (angBtwMin < angBtwMax) {
  89558. newYaw = boneYaw + Math.PI * .75;
  89559. localTarget.z = Math.cos(newYaw) * xzlen;
  89560. localTarget.x = Math.sin(newYaw) * xzlen;
  89561. }
  89562. else {
  89563. newYaw = boneYaw - Math.PI * .75;
  89564. localTarget.z = Math.cos(newYaw) * xzlen;
  89565. localTarget.x = Math.sin(newYaw) * xzlen;
  89566. }
  89567. }
  89568. }
  89569. if (yaw != newYaw) {
  89570. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  89571. localTarget.addInPlace(bonePos);
  89572. target = localTarget;
  89573. }
  89574. }
  89575. }
  89576. var zaxis = BoneLookController._tmpVecs[5];
  89577. var xaxis = BoneLookController._tmpVecs[6];
  89578. var yaxis = BoneLookController._tmpVecs[7];
  89579. var _tmpQuat = BoneLookController._tmpQuat;
  89580. target.subtractToRef(bonePos, zaxis);
  89581. zaxis.normalize();
  89582. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  89583. xaxis.normalize();
  89584. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  89585. yaxis.normalize();
  89586. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  89587. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  89588. return;
  89589. }
  89590. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  89591. return;
  89592. }
  89593. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  89594. return;
  89595. }
  89596. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  89597. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  89598. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  89599. }
  89600. if (this.slerpAmount < 1) {
  89601. if (!this._slerping) {
  89602. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  89603. }
  89604. if (this._transformYawPitch) {
  89605. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  89606. }
  89607. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  89608. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  89609. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  89610. this._slerping = true;
  89611. }
  89612. else {
  89613. if (this._transformYawPitch) {
  89614. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  89615. }
  89616. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  89617. this._slerping = false;
  89618. }
  89619. };
  89620. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  89621. var angDiff = ang2 - ang1;
  89622. angDiff %= Math.PI * 2;
  89623. if (angDiff > Math.PI) {
  89624. angDiff -= Math.PI * 2;
  89625. }
  89626. else if (angDiff < -Math.PI) {
  89627. angDiff += Math.PI * 2;
  89628. }
  89629. return angDiff;
  89630. };
  89631. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  89632. ang1 %= (2 * Math.PI);
  89633. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  89634. ang2 %= (2 * Math.PI);
  89635. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  89636. var ab = 0;
  89637. if (ang1 < ang2) {
  89638. ab = ang2 - ang1;
  89639. }
  89640. else {
  89641. ab = ang1 - ang2;
  89642. }
  89643. if (ab > Math.PI) {
  89644. ab = Math.PI * 2 - ab;
  89645. }
  89646. return ab;
  89647. };
  89648. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  89649. ang %= (2 * Math.PI);
  89650. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  89651. ang1 %= (2 * Math.PI);
  89652. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  89653. ang2 %= (2 * Math.PI);
  89654. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  89655. if (ang1 < ang2) {
  89656. if (ang > ang1 && ang < ang2) {
  89657. return true;
  89658. }
  89659. }
  89660. else {
  89661. if (ang > ang2 && ang < ang1) {
  89662. return true;
  89663. }
  89664. }
  89665. return false;
  89666. };
  89667. 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()];
  89668. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  89669. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89670. return BoneLookController;
  89671. }());
  89672. BABYLON.BoneLookController = BoneLookController;
  89673. })(BABYLON || (BABYLON = {}));
  89674. //# sourceMappingURL=babylon.boneLookController.js.map
  89675. var BABYLON;
  89676. (function (BABYLON) {
  89677. /**
  89678. * Class used to handle skinning animations
  89679. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  89680. */
  89681. var Skeleton = /** @class */ (function () {
  89682. /**
  89683. * Creates a new skeleton
  89684. * @param name defines the skeleton name
  89685. * @param id defines the skeleton Id
  89686. * @param scene defines the hosting scene
  89687. */
  89688. function Skeleton(
  89689. /** defines the skeleton name */
  89690. name,
  89691. /** defines the skeleton Id */
  89692. id, scene) {
  89693. this.name = name;
  89694. this.id = id;
  89695. /**
  89696. * Gets the list of child bones
  89697. */
  89698. this.bones = new Array();
  89699. /**
  89700. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  89701. */
  89702. this.needInitialSkinMatrix = false;
  89703. this._isDirty = true;
  89704. this._meshesWithPoseMatrix = new Array();
  89705. this._identity = BABYLON.Matrix.Identity();
  89706. this._ranges = {};
  89707. this._lastAbsoluteTransformsUpdateId = -1;
  89708. /**
  89709. * Specifies if the skeleton should be serialized
  89710. */
  89711. this.doNotSerialize = false;
  89712. this._animationPropertiesOverride = null;
  89713. // Events
  89714. /**
  89715. * An observable triggered before computing the skeleton's matrices
  89716. */
  89717. this.onBeforeComputeObservable = new BABYLON.Observable();
  89718. this.bones = [];
  89719. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89720. scene.skeletons.push(this);
  89721. //make sure it will recalculate the matrix next time prepare is called.
  89722. this._isDirty = true;
  89723. }
  89724. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  89725. /**
  89726. * Gets or sets the animation properties override
  89727. */
  89728. get: function () {
  89729. if (!this._animationPropertiesOverride) {
  89730. return this._scene.animationPropertiesOverride;
  89731. }
  89732. return this._animationPropertiesOverride;
  89733. },
  89734. set: function (value) {
  89735. this._animationPropertiesOverride = value;
  89736. },
  89737. enumerable: true,
  89738. configurable: true
  89739. });
  89740. // Members
  89741. /**
  89742. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  89743. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  89744. * @returns a Float32Array containing matrices data
  89745. */
  89746. Skeleton.prototype.getTransformMatrices = function (mesh) {
  89747. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  89748. return mesh._bonesTransformMatrices;
  89749. }
  89750. if (!this._transformMatrices) {
  89751. this.prepare();
  89752. }
  89753. return this._transformMatrices;
  89754. };
  89755. /**
  89756. * Gets the current hosting scene
  89757. * @returns a scene object
  89758. */
  89759. Skeleton.prototype.getScene = function () {
  89760. return this._scene;
  89761. };
  89762. // Methods
  89763. /**
  89764. * Gets a string representing the current skeleton data
  89765. * @param fullDetails defines a boolean indicating if we want a verbose version
  89766. * @returns a string representing the current skeleton data
  89767. */
  89768. Skeleton.prototype.toString = function (fullDetails) {
  89769. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  89770. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  89771. if (fullDetails) {
  89772. ret += ", Ranges: {";
  89773. var first = true;
  89774. for (var name_1 in this._ranges) {
  89775. if (first) {
  89776. ret += ", ";
  89777. first = false;
  89778. }
  89779. ret += name_1;
  89780. }
  89781. ret += "}";
  89782. }
  89783. return ret;
  89784. };
  89785. /**
  89786. * Get bone's index searching by name
  89787. * @param name defines bone's name to search for
  89788. * @return the indice of the bone. Returns -1 if not found
  89789. */
  89790. Skeleton.prototype.getBoneIndexByName = function (name) {
  89791. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  89792. if (this.bones[boneIndex].name === name) {
  89793. return boneIndex;
  89794. }
  89795. }
  89796. return -1;
  89797. };
  89798. /**
  89799. * Creater a new animation range
  89800. * @param name defines the name of the range
  89801. * @param from defines the start key
  89802. * @param to defines the end key
  89803. */
  89804. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  89805. // check name not already in use
  89806. if (!this._ranges[name]) {
  89807. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  89808. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89809. if (this.bones[i].animations[0]) {
  89810. this.bones[i].animations[0].createRange(name, from, to);
  89811. }
  89812. }
  89813. }
  89814. };
  89815. /**
  89816. * Delete a specific animation range
  89817. * @param name defines the name of the range
  89818. * @param deleteFrames defines if frames must be removed as well
  89819. */
  89820. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  89821. if (deleteFrames === void 0) { deleteFrames = true; }
  89822. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89823. if (this.bones[i].animations[0]) {
  89824. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  89825. }
  89826. }
  89827. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  89828. };
  89829. /**
  89830. * Gets a specific animation range
  89831. * @param name defines the name of the range to look for
  89832. * @returns the requested animation range or null if not found
  89833. */
  89834. Skeleton.prototype.getAnimationRange = function (name) {
  89835. return this._ranges[name];
  89836. };
  89837. /**
  89838. * Gets the list of all animation ranges defined on this skeleton
  89839. * @returns an array
  89840. */
  89841. Skeleton.prototype.getAnimationRanges = function () {
  89842. var animationRanges = [];
  89843. var name;
  89844. var i = 0;
  89845. for (name in this._ranges) {
  89846. animationRanges[i] = this._ranges[name];
  89847. i++;
  89848. }
  89849. return animationRanges;
  89850. };
  89851. /**
  89852. * Copy animation range from a source skeleton.
  89853. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  89854. * @param source defines the source skeleton
  89855. * @param name defines the name of the range to copy
  89856. * @param rescaleAsRequired defines if rescaling must be applied if required
  89857. * @returns true if operation was successful
  89858. */
  89859. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  89860. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89861. if (this._ranges[name] || !source.getAnimationRange(name)) {
  89862. return false;
  89863. }
  89864. var ret = true;
  89865. var frameOffset = this._getHighestAnimationFrame() + 1;
  89866. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  89867. var boneDict = {};
  89868. var sourceBones = source.bones;
  89869. var nBones;
  89870. var i;
  89871. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  89872. boneDict[sourceBones[i].name] = sourceBones[i];
  89873. }
  89874. if (this.bones.length !== sourceBones.length) {
  89875. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  89876. ret = false;
  89877. }
  89878. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  89879. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  89880. var boneName = this.bones[i].name;
  89881. var sourceBone = boneDict[boneName];
  89882. if (sourceBone) {
  89883. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  89884. }
  89885. else {
  89886. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  89887. ret = false;
  89888. }
  89889. }
  89890. // do not call createAnimationRange(), since it also is done to bones, which was already done
  89891. var range = source.getAnimationRange(name);
  89892. if (range) {
  89893. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  89894. }
  89895. return ret;
  89896. };
  89897. /**
  89898. * Forces the skeleton to go to rest pose
  89899. */
  89900. Skeleton.prototype.returnToRest = function () {
  89901. for (var index = 0; index < this.bones.length; index++) {
  89902. this.bones[index].returnToRest();
  89903. }
  89904. };
  89905. Skeleton.prototype._getHighestAnimationFrame = function () {
  89906. var ret = 0;
  89907. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89908. if (this.bones[i].animations[0]) {
  89909. var highest = this.bones[i].animations[0].getHighestFrame();
  89910. if (ret < highest) {
  89911. ret = highest;
  89912. }
  89913. }
  89914. }
  89915. return ret;
  89916. };
  89917. /**
  89918. * Begin a specific animation range
  89919. * @param name defines the name of the range to start
  89920. * @param loop defines if looping must be turned on (false by default)
  89921. * @param speedRatio defines the speed ratio to apply (1 by default)
  89922. * @param onAnimationEnd defines a callback which will be called when animation will end
  89923. * @returns a new animatable
  89924. */
  89925. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  89926. var range = this.getAnimationRange(name);
  89927. if (!range) {
  89928. return null;
  89929. }
  89930. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  89931. };
  89932. /** @hidden */
  89933. Skeleton.prototype._markAsDirty = function () {
  89934. this._isDirty = true;
  89935. };
  89936. /** @hidden */
  89937. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  89938. this._meshesWithPoseMatrix.push(mesh);
  89939. };
  89940. /** @hidden */
  89941. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  89942. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  89943. if (index > -1) {
  89944. this._meshesWithPoseMatrix.splice(index, 1);
  89945. }
  89946. };
  89947. /** @hidden */
  89948. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  89949. this.onBeforeComputeObservable.notifyObservers(this);
  89950. for (var index = 0; index < this.bones.length; index++) {
  89951. var bone = this.bones[index];
  89952. var parentBone = bone.getParent();
  89953. if (parentBone) {
  89954. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  89955. }
  89956. else {
  89957. if (initialSkinMatrix) {
  89958. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  89959. }
  89960. else {
  89961. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  89962. }
  89963. }
  89964. if (bone._index !== -1) {
  89965. var mappedIndex = bone._index === null ? index : bone._index;
  89966. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  89967. }
  89968. }
  89969. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  89970. };
  89971. /**
  89972. * Build all resources required to render a skeleton
  89973. */
  89974. Skeleton.prototype.prepare = function () {
  89975. if (!this._isDirty) {
  89976. return;
  89977. }
  89978. if (this.needInitialSkinMatrix) {
  89979. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  89980. var mesh = this._meshesWithPoseMatrix[index];
  89981. var poseMatrix = mesh.getPoseMatrix();
  89982. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  89983. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  89984. }
  89985. if (this._synchronizedWithMesh !== mesh) {
  89986. this._synchronizedWithMesh = mesh;
  89987. // Prepare bones
  89988. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  89989. var bone = this.bones[boneIndex];
  89990. if (!bone.getParent()) {
  89991. var matrix = bone.getBaseMatrix();
  89992. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  89993. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  89994. }
  89995. }
  89996. }
  89997. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  89998. }
  89999. }
  90000. else {
  90001. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  90002. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90003. }
  90004. this._computeTransformMatrices(this._transformMatrices, null);
  90005. }
  90006. this._isDirty = false;
  90007. this._scene._activeBones.addCount(this.bones.length, false);
  90008. };
  90009. /**
  90010. * Gets the list of animatables currently running for this skeleton
  90011. * @returns an array of animatables
  90012. */
  90013. Skeleton.prototype.getAnimatables = function () {
  90014. if (!this._animatables || this._animatables.length !== this.bones.length) {
  90015. this._animatables = [];
  90016. for (var index = 0; index < this.bones.length; index++) {
  90017. this._animatables.push(this.bones[index]);
  90018. }
  90019. }
  90020. return this._animatables;
  90021. };
  90022. /**
  90023. * Clone the current skeleton
  90024. * @param name defines the name of the new skeleton
  90025. * @param id defines the id of the enw skeleton
  90026. * @returns the new skeleton
  90027. */
  90028. Skeleton.prototype.clone = function (name, id) {
  90029. var result = new Skeleton(name, id || name, this._scene);
  90030. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90031. for (var index = 0; index < this.bones.length; index++) {
  90032. var source = this.bones[index];
  90033. var parentBone = null;
  90034. var parent_1 = source.getParent();
  90035. if (parent_1) {
  90036. var parentIndex = this.bones.indexOf(parent_1);
  90037. parentBone = result.bones[parentIndex];
  90038. }
  90039. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  90040. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  90041. }
  90042. if (this._ranges) {
  90043. result._ranges = {};
  90044. for (var rangeName in this._ranges) {
  90045. var range = this._ranges[rangeName];
  90046. if (range) {
  90047. result._ranges[rangeName] = range.clone();
  90048. }
  90049. }
  90050. }
  90051. this._isDirty = true;
  90052. return result;
  90053. };
  90054. /**
  90055. * Enable animation blending for this skeleton
  90056. * @param blendingSpeed defines the blending speed to apply
  90057. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  90058. */
  90059. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  90060. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  90061. this.bones.forEach(function (bone) {
  90062. bone.animations.forEach(function (animation) {
  90063. animation.enableBlending = true;
  90064. animation.blendingSpeed = blendingSpeed;
  90065. });
  90066. });
  90067. };
  90068. /**
  90069. * Releases all resources associated with the current skeleton
  90070. */
  90071. Skeleton.prototype.dispose = function () {
  90072. this._meshesWithPoseMatrix = [];
  90073. // Animations
  90074. this.getScene().stopAnimation(this);
  90075. // Remove from scene
  90076. this.getScene().removeSkeleton(this);
  90077. };
  90078. /**
  90079. * Serialize the skeleton in a JSON object
  90080. * @returns a JSON object
  90081. */
  90082. Skeleton.prototype.serialize = function () {
  90083. var serializationObject = {};
  90084. serializationObject.name = this.name;
  90085. serializationObject.id = this.id;
  90086. if (this.dimensionsAtRest) {
  90087. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  90088. }
  90089. serializationObject.bones = [];
  90090. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90091. for (var index = 0; index < this.bones.length; index++) {
  90092. var bone = this.bones[index];
  90093. var parent_2 = bone.getParent();
  90094. var serializedBone = {
  90095. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  90096. name: bone.name,
  90097. matrix: bone.getBaseMatrix().toArray(),
  90098. rest: bone.getRestPose().toArray()
  90099. };
  90100. serializationObject.bones.push(serializedBone);
  90101. if (bone.length) {
  90102. serializedBone.length = bone.length;
  90103. }
  90104. if (bone.metadata) {
  90105. serializedBone.metadata = bone.metadata;
  90106. }
  90107. if (bone.animations && bone.animations.length > 0) {
  90108. serializedBone.animation = bone.animations[0].serialize();
  90109. }
  90110. serializationObject.ranges = [];
  90111. for (var name in this._ranges) {
  90112. var source = this._ranges[name];
  90113. if (!source) {
  90114. continue;
  90115. }
  90116. var range = {};
  90117. range.name = name;
  90118. range.from = source.from;
  90119. range.to = source.to;
  90120. serializationObject.ranges.push(range);
  90121. }
  90122. }
  90123. return serializationObject;
  90124. };
  90125. /**
  90126. * Creates a new skeleton from serialized data
  90127. * @param parsedSkeleton defines the serialized data
  90128. * @param scene defines the hosting scene
  90129. * @returns a new skeleton
  90130. */
  90131. Skeleton.Parse = function (parsedSkeleton, scene) {
  90132. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  90133. if (parsedSkeleton.dimensionsAtRest) {
  90134. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  90135. }
  90136. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  90137. var index;
  90138. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  90139. var parsedBone = parsedSkeleton.bones[index];
  90140. var parentBone = null;
  90141. if (parsedBone.parentBoneIndex > -1) {
  90142. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  90143. }
  90144. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  90145. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  90146. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  90147. bone.id = parsedBone.id;
  90148. }
  90149. if (parsedBone.length) {
  90150. bone.length = parsedBone.length;
  90151. }
  90152. if (parsedBone.metadata) {
  90153. bone.metadata = parsedBone.metadata;
  90154. }
  90155. if (parsedBone.animation) {
  90156. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  90157. }
  90158. }
  90159. // placed after bones, so createAnimationRange can cascade down
  90160. if (parsedSkeleton.ranges) {
  90161. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  90162. var data = parsedSkeleton.ranges[index];
  90163. skeleton.createAnimationRange(data.name, data.from, data.to);
  90164. }
  90165. }
  90166. return skeleton;
  90167. };
  90168. /**
  90169. * Compute all node absolute transforms
  90170. * @param forceUpdate defines if computation must be done even if cache is up to date
  90171. */
  90172. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  90173. if (forceUpdate === void 0) { forceUpdate = false; }
  90174. var renderId = this._scene.getRenderId();
  90175. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  90176. this.bones[0].computeAbsoluteTransforms();
  90177. this._lastAbsoluteTransformsUpdateId = renderId;
  90178. }
  90179. };
  90180. /**
  90181. * Gets the root pose matrix
  90182. * @returns a matrix
  90183. */
  90184. Skeleton.prototype.getPoseMatrix = function () {
  90185. var poseMatrix = null;
  90186. if (this._meshesWithPoseMatrix.length > 0) {
  90187. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  90188. }
  90189. return poseMatrix;
  90190. };
  90191. /**
  90192. * Sorts bones per internal index
  90193. */
  90194. Skeleton.prototype.sortBones = function () {
  90195. var bones = new Array();
  90196. var visited = new Array(this.bones.length);
  90197. for (var index = 0; index < this.bones.length; index++) {
  90198. this._sortBones(index, bones, visited);
  90199. }
  90200. this.bones = bones;
  90201. };
  90202. Skeleton.prototype._sortBones = function (index, bones, visited) {
  90203. if (visited[index]) {
  90204. return;
  90205. }
  90206. visited[index] = true;
  90207. var bone = this.bones[index];
  90208. if (bone._index === undefined) {
  90209. bone._index = index;
  90210. }
  90211. var parentBone = bone.getParent();
  90212. if (parentBone) {
  90213. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  90214. }
  90215. bones.push(bone);
  90216. };
  90217. return Skeleton;
  90218. }());
  90219. BABYLON.Skeleton = Skeleton;
  90220. })(BABYLON || (BABYLON = {}));
  90221. //# sourceMappingURL=babylon.skeleton.js.map
  90222. var BABYLON;
  90223. (function (BABYLON) {
  90224. ;
  90225. /**
  90226. * This groups tools to convert HDR texture to native colors array.
  90227. */
  90228. var HDRTools = /** @class */ (function () {
  90229. function HDRTools() {
  90230. }
  90231. HDRTools.Ldexp = function (mantissa, exponent) {
  90232. if (exponent > 1023) {
  90233. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  90234. }
  90235. if (exponent < -1074) {
  90236. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  90237. }
  90238. return mantissa * Math.pow(2, exponent);
  90239. };
  90240. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  90241. if (exponent > 0) { /*nonzero pixel*/
  90242. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  90243. float32array[index + 0] = red * exponent;
  90244. float32array[index + 1] = green * exponent;
  90245. float32array[index + 2] = blue * exponent;
  90246. }
  90247. else {
  90248. float32array[index + 0] = 0;
  90249. float32array[index + 1] = 0;
  90250. float32array[index + 2] = 0;
  90251. }
  90252. };
  90253. HDRTools.readStringLine = function (uint8array, startIndex) {
  90254. var line = "";
  90255. var character = "";
  90256. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  90257. character = String.fromCharCode(uint8array[i]);
  90258. if (character == "\n") {
  90259. break;
  90260. }
  90261. line += character;
  90262. }
  90263. return line;
  90264. };
  90265. /**
  90266. * Reads header information from an RGBE texture stored in a native array.
  90267. * More information on this format are available here:
  90268. * https://en.wikipedia.org/wiki/RGBE_image_format
  90269. *
  90270. * @param uint8array The binary file stored in native array.
  90271. * @return The header information.
  90272. */
  90273. HDRTools.RGBE_ReadHeader = function (uint8array) {
  90274. var height = 0;
  90275. var width = 0;
  90276. var line = this.readStringLine(uint8array, 0);
  90277. if (line[0] != '#' || line[1] != '?') {
  90278. throw "Bad HDR Format.";
  90279. }
  90280. var endOfHeader = false;
  90281. var findFormat = false;
  90282. var lineIndex = 0;
  90283. do {
  90284. lineIndex += (line.length + 1);
  90285. line = this.readStringLine(uint8array, lineIndex);
  90286. if (line == "FORMAT=32-bit_rle_rgbe") {
  90287. findFormat = true;
  90288. }
  90289. else if (line.length == 0) {
  90290. endOfHeader = true;
  90291. }
  90292. } while (!endOfHeader);
  90293. if (!findFormat) {
  90294. throw "HDR Bad header format, unsupported FORMAT";
  90295. }
  90296. lineIndex += (line.length + 1);
  90297. line = this.readStringLine(uint8array, lineIndex);
  90298. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  90299. var match = sizeRegexp.exec(line);
  90300. // TODO. Support +Y and -X if needed.
  90301. if (!match || match.length < 3) {
  90302. throw "HDR Bad header format, no size";
  90303. }
  90304. width = parseInt(match[2]);
  90305. height = parseInt(match[1]);
  90306. if (width < 8 || width > 0x7fff) {
  90307. throw "HDR Bad header format, unsupported size";
  90308. }
  90309. lineIndex += (line.length + 1);
  90310. return {
  90311. height: height,
  90312. width: width,
  90313. dataPosition: lineIndex
  90314. };
  90315. };
  90316. /**
  90317. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  90318. * This RGBE texture needs to store the information as a panorama.
  90319. *
  90320. * More information on this format are available here:
  90321. * https://en.wikipedia.org/wiki/RGBE_image_format
  90322. *
  90323. * @param buffer The binary file stored in an array buffer.
  90324. * @param size The expected size of the extracted cubemap.
  90325. * @return The Cube Map information.
  90326. */
  90327. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  90328. var uint8array = new Uint8Array(buffer);
  90329. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  90330. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  90331. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  90332. return cubeMapData;
  90333. };
  90334. /**
  90335. * Returns the pixels data extracted from an RGBE texture.
  90336. * This pixels will be stored left to right up to down in the R G B order in one array.
  90337. *
  90338. * More information on this format are available here:
  90339. * https://en.wikipedia.org/wiki/RGBE_image_format
  90340. *
  90341. * @param uint8array The binary file stored in an array buffer.
  90342. * @param hdrInfo The header information of the file.
  90343. * @return The pixels data in RGB right to left up to down order.
  90344. */
  90345. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  90346. // Keep for multi format supports.
  90347. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  90348. };
  90349. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  90350. var num_scanlines = hdrInfo.height;
  90351. var scanline_width = hdrInfo.width;
  90352. var a, b, c, d, count;
  90353. var dataIndex = hdrInfo.dataPosition;
  90354. var index = 0, endIndex = 0, i = 0;
  90355. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  90356. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  90357. // 3 channels of 4 bytes per pixel in float.
  90358. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  90359. var resultArray = new Float32Array(resultBuffer);
  90360. // read in each successive scanline
  90361. while (num_scanlines > 0) {
  90362. a = uint8array[dataIndex++];
  90363. b = uint8array[dataIndex++];
  90364. c = uint8array[dataIndex++];
  90365. d = uint8array[dataIndex++];
  90366. if (a != 2 || b != 2 || (c & 0x80)) {
  90367. // this file is not run length encoded
  90368. throw "HDR Bad header format, not RLE";
  90369. }
  90370. if (((c << 8) | d) != scanline_width) {
  90371. throw "HDR Bad header format, wrong scan line width";
  90372. }
  90373. index = 0;
  90374. // read each of the four channels for the scanline into the buffer
  90375. for (i = 0; i < 4; i++) {
  90376. endIndex = (i + 1) * scanline_width;
  90377. while (index < endIndex) {
  90378. a = uint8array[dataIndex++];
  90379. b = uint8array[dataIndex++];
  90380. if (a > 128) {
  90381. // a run of the same value
  90382. count = a - 128;
  90383. if ((count == 0) || (count > endIndex - index)) {
  90384. throw "HDR Bad Format, bad scanline data (run)";
  90385. }
  90386. while (count-- > 0) {
  90387. scanLineArray[index++] = b;
  90388. }
  90389. }
  90390. else {
  90391. // a non-run
  90392. count = a;
  90393. if ((count == 0) || (count > endIndex - index)) {
  90394. throw "HDR Bad Format, bad scanline data (non-run)";
  90395. }
  90396. scanLineArray[index++] = b;
  90397. if (--count > 0) {
  90398. for (var j = 0; j < count; j++) {
  90399. scanLineArray[index++] = uint8array[dataIndex++];
  90400. }
  90401. }
  90402. }
  90403. }
  90404. }
  90405. // now convert data from buffer into floats
  90406. for (i = 0; i < scanline_width; i++) {
  90407. a = scanLineArray[i];
  90408. b = scanLineArray[i + scanline_width];
  90409. c = scanLineArray[i + 2 * scanline_width];
  90410. d = scanLineArray[i + 3 * scanline_width];
  90411. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  90412. }
  90413. num_scanlines--;
  90414. }
  90415. return resultArray;
  90416. };
  90417. return HDRTools;
  90418. }());
  90419. BABYLON.HDRTools = HDRTools;
  90420. })(BABYLON || (BABYLON = {}));
  90421. //# sourceMappingURL=babylon.hdr.js.map
  90422. var BABYLON;
  90423. (function (BABYLON) {
  90424. /**
  90425. * This represents a texture coming from an HDR input.
  90426. *
  90427. * The only supported format is currently panorama picture stored in RGBE format.
  90428. * Example of such files can be found on HDRLib: http://hdrlib.com/
  90429. */
  90430. var HDRCubeTexture = /** @class */ (function (_super) {
  90431. __extends(HDRCubeTexture, _super);
  90432. /**
  90433. * Instantiates an HDRTexture from the following parameters.
  90434. *
  90435. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  90436. * @param scene The scene the texture will be used in
  90437. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  90438. * @param noMipmap Forces to not generate the mipmap if true
  90439. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  90440. * @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)
  90441. * @param reserved Reserved flag for internal use.
  90442. */
  90443. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  90444. if (noMipmap === void 0) { noMipmap = false; }
  90445. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90446. if (gammaSpace === void 0) { gammaSpace = false; }
  90447. if (reserved === void 0) { reserved = false; }
  90448. if (onLoad === void 0) { onLoad = null; }
  90449. if (onError === void 0) { onError = null; }
  90450. var _this = _super.call(this, scene) || this;
  90451. _this._generateHarmonics = true;
  90452. _this._onLoad = null;
  90453. _this._onError = null;
  90454. /**
  90455. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  90456. */
  90457. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  90458. _this._isBlocking = true;
  90459. _this._rotationY = 0;
  90460. /**
  90461. * Gets or sets the center of the bounding box associated with the cube texture
  90462. * It must define where the camera used to render the texture was set
  90463. */
  90464. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  90465. if (!url) {
  90466. return _this;
  90467. }
  90468. _this.name = url;
  90469. _this.url = url;
  90470. _this.hasAlpha = false;
  90471. _this.isCube = true;
  90472. _this._textureMatrix = BABYLON.Matrix.Identity();
  90473. _this._onLoad = onLoad;
  90474. _this._onError = onError;
  90475. _this.gammaSpace = gammaSpace;
  90476. _this._noMipmap = noMipmap;
  90477. _this._size = size;
  90478. _this._texture = _this._getFromCache(url, _this._noMipmap);
  90479. if (!_this._texture) {
  90480. if (!scene.useDelayedTextureLoading) {
  90481. _this.loadTexture();
  90482. }
  90483. else {
  90484. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  90485. }
  90486. }
  90487. return _this;
  90488. }
  90489. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  90490. /**
  90491. * Gets wether or not the texture is blocking during loading.
  90492. */
  90493. get: function () {
  90494. return this._isBlocking;
  90495. },
  90496. /**
  90497. * Sets wether or not the texture is blocking during loading.
  90498. */
  90499. set: function (value) {
  90500. this._isBlocking = value;
  90501. },
  90502. enumerable: true,
  90503. configurable: true
  90504. });
  90505. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  90506. /**
  90507. * Gets texture matrix rotation angle around Y axis radians.
  90508. */
  90509. get: function () {
  90510. return this._rotationY;
  90511. },
  90512. /**
  90513. * Sets texture matrix rotation angle around Y axis in radians.
  90514. */
  90515. set: function (value) {
  90516. this._rotationY = value;
  90517. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  90518. },
  90519. enumerable: true,
  90520. configurable: true
  90521. });
  90522. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  90523. get: function () {
  90524. return this._boundingBoxSize;
  90525. },
  90526. /**
  90527. * Gets or sets the size of the bounding box associated with the cube texture
  90528. * When defined, the cubemap will switch to local mode
  90529. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  90530. * @example https://www.babylonjs-playground.com/#RNASML
  90531. */
  90532. set: function (value) {
  90533. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  90534. return;
  90535. }
  90536. this._boundingBoxSize = value;
  90537. var scene = this.getScene();
  90538. if (scene) {
  90539. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  90540. }
  90541. },
  90542. enumerable: true,
  90543. configurable: true
  90544. });
  90545. /**
  90546. * Occurs when the file is raw .hdr file.
  90547. */
  90548. HDRCubeTexture.prototype.loadTexture = function () {
  90549. var _this = this;
  90550. var callback = function (buffer) {
  90551. _this.lodGenerationOffset = 0.0;
  90552. _this.lodGenerationScale = 0.8;
  90553. var scene = _this.getScene();
  90554. if (!scene) {
  90555. return null;
  90556. }
  90557. // Extract the raw linear data.
  90558. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  90559. // Generate harmonics if needed.
  90560. if (_this._generateHarmonics) {
  90561. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  90562. _this.sphericalPolynomial = sphericalPolynomial;
  90563. }
  90564. var results = [];
  90565. var byteArray = null;
  90566. // Push each faces.
  90567. for (var j = 0; j < 6; j++) {
  90568. // Create uintarray fallback.
  90569. if (!scene.getEngine().getCaps().textureFloat) {
  90570. // 3 channels of 1 bytes per pixel in bytes.
  90571. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  90572. byteArray = new Uint8Array(byteBuffer);
  90573. }
  90574. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  90575. // If special cases.
  90576. if (_this.gammaSpace || byteArray) {
  90577. for (var i = 0; i < _this._size * _this._size; i++) {
  90578. // Put in gamma space if requested.
  90579. if (_this.gammaSpace) {
  90580. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  90581. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  90582. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  90583. }
  90584. // Convert to int texture for fallback.
  90585. if (byteArray) {
  90586. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  90587. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  90588. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  90589. // May use luminance instead if the result is not accurate.
  90590. var max = Math.max(Math.max(r, g), b);
  90591. if (max > 255) {
  90592. var scale = 255 / max;
  90593. r *= scale;
  90594. g *= scale;
  90595. b *= scale;
  90596. }
  90597. byteArray[(i * 3) + 0] = r;
  90598. byteArray[(i * 3) + 1] = g;
  90599. byteArray[(i * 3) + 2] = b;
  90600. }
  90601. }
  90602. }
  90603. if (byteArray) {
  90604. results.push(byteArray);
  90605. }
  90606. else {
  90607. results.push(dataFace);
  90608. }
  90609. }
  90610. return results;
  90611. };
  90612. var scene = this.getScene();
  90613. if (scene) {
  90614. 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);
  90615. }
  90616. };
  90617. HDRCubeTexture.prototype.clone = function () {
  90618. var scene = this.getScene();
  90619. if (!scene) {
  90620. return this;
  90621. }
  90622. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  90623. // Base texture
  90624. newTexture.level = this.level;
  90625. newTexture.wrapU = this.wrapU;
  90626. newTexture.wrapV = this.wrapV;
  90627. newTexture.coordinatesIndex = this.coordinatesIndex;
  90628. newTexture.coordinatesMode = this.coordinatesMode;
  90629. return newTexture;
  90630. };
  90631. // Methods
  90632. HDRCubeTexture.prototype.delayLoad = function () {
  90633. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  90634. return;
  90635. }
  90636. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  90637. this._texture = this._getFromCache(this.url, this._noMipmap);
  90638. if (!this._texture) {
  90639. this.loadTexture();
  90640. }
  90641. };
  90642. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  90643. return this._textureMatrix;
  90644. };
  90645. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  90646. this._textureMatrix = value;
  90647. };
  90648. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  90649. var texture = null;
  90650. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  90651. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  90652. texture.name = parsedTexture.name;
  90653. texture.hasAlpha = parsedTexture.hasAlpha;
  90654. texture.level = parsedTexture.level;
  90655. texture.coordinatesMode = parsedTexture.coordinatesMode;
  90656. texture.isBlocking = parsedTexture.isBlocking;
  90657. }
  90658. if (texture) {
  90659. if (parsedTexture.boundingBoxPosition) {
  90660. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  90661. }
  90662. if (parsedTexture.boundingBoxSize) {
  90663. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  90664. }
  90665. if (parsedTexture.rotationY) {
  90666. texture.rotationY = parsedTexture.rotationY;
  90667. }
  90668. }
  90669. return texture;
  90670. };
  90671. HDRCubeTexture.prototype.serialize = function () {
  90672. if (!this.name) {
  90673. return null;
  90674. }
  90675. var serializationObject = {};
  90676. serializationObject.name = this.name;
  90677. serializationObject.hasAlpha = this.hasAlpha;
  90678. serializationObject.isCube = true;
  90679. serializationObject.level = this.level;
  90680. serializationObject.size = this._size;
  90681. serializationObject.coordinatesMode = this.coordinatesMode;
  90682. serializationObject.useInGammaSpace = this.gammaSpace;
  90683. serializationObject.generateHarmonics = this._generateHarmonics;
  90684. serializationObject.customType = "BABYLON.HDRCubeTexture";
  90685. serializationObject.noMipmap = this._noMipmap;
  90686. serializationObject.isBlocking = this._isBlocking;
  90687. serializationObject.rotationY = this._rotationY;
  90688. return serializationObject;
  90689. };
  90690. HDRCubeTexture._facesMapping = [
  90691. "right",
  90692. "left",
  90693. "up",
  90694. "down",
  90695. "front",
  90696. "back"
  90697. ];
  90698. return HDRCubeTexture;
  90699. }(BABYLON.BaseTexture));
  90700. BABYLON.HDRCubeTexture = HDRCubeTexture;
  90701. })(BABYLON || (BABYLON = {}));
  90702. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  90703. var BABYLON;
  90704. (function (BABYLON) {
  90705. /**
  90706. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  90707. */
  90708. var PanoramaToCubeMapTools = /** @class */ (function () {
  90709. function PanoramaToCubeMapTools() {
  90710. }
  90711. /**
  90712. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  90713. *
  90714. * @param float32Array The source data.
  90715. * @param inputWidth The width of the input panorama.
  90716. * @param inputhHeight The height of the input panorama.
  90717. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  90718. * @return The cubemap data
  90719. */
  90720. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  90721. if (!float32Array) {
  90722. throw "ConvertPanoramaToCubemap: input cannot be null";
  90723. }
  90724. if (float32Array.length != inputWidth * inputHeight * 3) {
  90725. throw "ConvertPanoramaToCubemap: input size is wrong";
  90726. }
  90727. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  90728. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  90729. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  90730. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  90731. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  90732. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  90733. return {
  90734. front: textureFront,
  90735. back: textureBack,
  90736. left: textureLeft,
  90737. right: textureRight,
  90738. up: textureUp,
  90739. down: textureDown,
  90740. size: size,
  90741. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  90742. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  90743. gammaSpace: false,
  90744. };
  90745. };
  90746. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  90747. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  90748. var textureArray = new Float32Array(buffer);
  90749. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  90750. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  90751. var dy = 1 / texSize;
  90752. var fy = 0;
  90753. for (var y = 0; y < texSize; y++) {
  90754. var xv1 = faceData[0];
  90755. var xv2 = faceData[2];
  90756. for (var x = 0; x < texSize; x++) {
  90757. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  90758. v.normalize();
  90759. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  90760. // 3 channels per pixels
  90761. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  90762. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  90763. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  90764. xv1 = xv1.add(rotDX1);
  90765. xv2 = xv2.add(rotDX2);
  90766. }
  90767. fy += dy;
  90768. }
  90769. return textureArray;
  90770. };
  90771. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  90772. var theta = Math.atan2(vDir.z, vDir.x);
  90773. var phi = Math.acos(vDir.y);
  90774. while (theta < -Math.PI)
  90775. theta += 2 * Math.PI;
  90776. while (theta > Math.PI)
  90777. theta -= 2 * Math.PI;
  90778. var dx = theta / Math.PI;
  90779. var dy = phi / Math.PI;
  90780. // recenter.
  90781. dx = dx * 0.5 + 0.5;
  90782. var px = Math.round(dx * inputWidth);
  90783. if (px < 0)
  90784. px = 0;
  90785. else if (px >= inputWidth)
  90786. px = inputWidth - 1;
  90787. var py = Math.round(dy * inputHeight);
  90788. if (py < 0)
  90789. py = 0;
  90790. else if (py >= inputHeight)
  90791. py = inputHeight - 1;
  90792. var inputY = (inputHeight - py - 1);
  90793. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  90794. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  90795. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  90796. return {
  90797. r: r,
  90798. g: g,
  90799. b: b
  90800. };
  90801. };
  90802. PanoramaToCubeMapTools.FACE_FRONT = [
  90803. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90804. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90805. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90806. new BABYLON.Vector3(1.0, 1.0, -1.0)
  90807. ];
  90808. PanoramaToCubeMapTools.FACE_BACK = [
  90809. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90810. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90811. new BABYLON.Vector3(1.0, 1.0, 1.0),
  90812. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  90813. ];
  90814. PanoramaToCubeMapTools.FACE_RIGHT = [
  90815. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90816. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90817. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90818. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90819. ];
  90820. PanoramaToCubeMapTools.FACE_LEFT = [
  90821. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90822. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90823. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90824. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  90825. ];
  90826. PanoramaToCubeMapTools.FACE_DOWN = [
  90827. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90828. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90829. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90830. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90831. ];
  90832. PanoramaToCubeMapTools.FACE_UP = [
  90833. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90834. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90835. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90836. new BABYLON.Vector3(1.0, -1.0, -1.0)
  90837. ];
  90838. return PanoramaToCubeMapTools;
  90839. }());
  90840. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  90841. })(BABYLON || (BABYLON = {}));
  90842. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  90843. var BABYLON;
  90844. (function (BABYLON) {
  90845. var IndexedVector2 = /** @class */ (function (_super) {
  90846. __extends(IndexedVector2, _super);
  90847. function IndexedVector2(original, index) {
  90848. var _this = _super.call(this, original.x, original.y) || this;
  90849. _this.index = index;
  90850. return _this;
  90851. }
  90852. return IndexedVector2;
  90853. }(BABYLON.Vector2));
  90854. var PolygonPoints = /** @class */ (function () {
  90855. function PolygonPoints() {
  90856. this.elements = new Array();
  90857. }
  90858. PolygonPoints.prototype.add = function (originalPoints) {
  90859. var _this = this;
  90860. var result = new Array();
  90861. originalPoints.forEach(function (point) {
  90862. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  90863. var newPoint = new IndexedVector2(point, _this.elements.length);
  90864. result.push(newPoint);
  90865. _this.elements.push(newPoint);
  90866. }
  90867. });
  90868. return result;
  90869. };
  90870. PolygonPoints.prototype.computeBounds = function () {
  90871. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90872. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90873. this.elements.forEach(function (point) {
  90874. // x
  90875. if (point.x < lmin.x) {
  90876. lmin.x = point.x;
  90877. }
  90878. else if (point.x > lmax.x) {
  90879. lmax.x = point.x;
  90880. }
  90881. // y
  90882. if (point.y < lmin.y) {
  90883. lmin.y = point.y;
  90884. }
  90885. else if (point.y > lmax.y) {
  90886. lmax.y = point.y;
  90887. }
  90888. });
  90889. return {
  90890. min: lmin,
  90891. max: lmax,
  90892. width: lmax.x - lmin.x,
  90893. height: lmax.y - lmin.y
  90894. };
  90895. };
  90896. return PolygonPoints;
  90897. }());
  90898. var Polygon = /** @class */ (function () {
  90899. function Polygon() {
  90900. }
  90901. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  90902. return [
  90903. new BABYLON.Vector2(xmin, ymin),
  90904. new BABYLON.Vector2(xmax, ymin),
  90905. new BABYLON.Vector2(xmax, ymax),
  90906. new BABYLON.Vector2(xmin, ymax)
  90907. ];
  90908. };
  90909. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  90910. if (cx === void 0) { cx = 0; }
  90911. if (cy === void 0) { cy = 0; }
  90912. if (numberOfSides === void 0) { numberOfSides = 32; }
  90913. var result = new Array();
  90914. var angle = 0;
  90915. var increment = (Math.PI * 2) / numberOfSides;
  90916. for (var i = 0; i < numberOfSides; i++) {
  90917. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  90918. angle -= increment;
  90919. }
  90920. return result;
  90921. };
  90922. Polygon.Parse = function (input) {
  90923. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  90924. var i, result = [];
  90925. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  90926. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  90927. }
  90928. return result;
  90929. };
  90930. Polygon.StartingAt = function (x, y) {
  90931. return BABYLON.Path2.StartingAt(x, y);
  90932. };
  90933. return Polygon;
  90934. }());
  90935. BABYLON.Polygon = Polygon;
  90936. var PolygonMeshBuilder = /** @class */ (function () {
  90937. function PolygonMeshBuilder(name, contours, scene) {
  90938. this._points = new PolygonPoints();
  90939. this._outlinepoints = new PolygonPoints();
  90940. this._holes = new Array();
  90941. this._epoints = new Array();
  90942. this._eholes = new Array();
  90943. this._name = name;
  90944. this._scene = scene;
  90945. var points;
  90946. if (contours instanceof BABYLON.Path2) {
  90947. points = contours.getPoints();
  90948. }
  90949. else {
  90950. points = contours;
  90951. }
  90952. this._addToepoint(points);
  90953. this._points.add(points);
  90954. this._outlinepoints.add(points);
  90955. if (typeof earcut === 'undefined') {
  90956. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  90957. }
  90958. }
  90959. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  90960. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  90961. var p = points_1[_i];
  90962. this._epoints.push(p.x, p.y);
  90963. }
  90964. };
  90965. PolygonMeshBuilder.prototype.addHole = function (hole) {
  90966. this._points.add(hole);
  90967. var holepoints = new PolygonPoints();
  90968. holepoints.add(hole);
  90969. this._holes.push(holepoints);
  90970. this._eholes.push(this._epoints.length / 2);
  90971. this._addToepoint(hole);
  90972. return this;
  90973. };
  90974. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  90975. var _this = this;
  90976. if (updatable === void 0) { updatable = false; }
  90977. if (depth === void 0) { depth = 0; }
  90978. var result = new BABYLON.Mesh(this._name, this._scene);
  90979. var normals = new Array();
  90980. var positions = new Array();
  90981. var uvs = new Array();
  90982. var bounds = this._points.computeBounds();
  90983. this._points.elements.forEach(function (p) {
  90984. normals.push(0, 1.0, 0);
  90985. positions.push(p.x, 0, p.y);
  90986. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  90987. });
  90988. var indices = new Array();
  90989. var res = earcut(this._epoints, this._eholes, 2);
  90990. for (var i = 0; i < res.length; i++) {
  90991. indices.push(res[i]);
  90992. }
  90993. if (depth > 0) {
  90994. var positionscount = (positions.length / 3); //get the current pointcount
  90995. this._points.elements.forEach(function (p) {
  90996. normals.push(0, -1.0, 0);
  90997. positions.push(p.x, -depth, p.y);
  90998. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  90999. });
  91000. var totalCount = indices.length;
  91001. for (var i = 0; i < totalCount; i += 3) {
  91002. var i0 = indices[i + 0];
  91003. var i1 = indices[i + 1];
  91004. var i2 = indices[i + 2];
  91005. indices.push(i2 + positionscount);
  91006. indices.push(i1 + positionscount);
  91007. indices.push(i0 + positionscount);
  91008. }
  91009. //Add the sides
  91010. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  91011. this._holes.forEach(function (hole) {
  91012. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  91013. });
  91014. }
  91015. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  91016. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  91017. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  91018. result.setIndices(indices);
  91019. return result;
  91020. };
  91021. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  91022. var StartIndex = positions.length / 3;
  91023. var ulength = 0;
  91024. for (var i = 0; i < points.elements.length; i++) {
  91025. var p = points.elements[i];
  91026. var p1;
  91027. if ((i + 1) > points.elements.length - 1) {
  91028. p1 = points.elements[0];
  91029. }
  91030. else {
  91031. p1 = points.elements[i + 1];
  91032. }
  91033. positions.push(p.x, 0, p.y);
  91034. positions.push(p.x, -depth, p.y);
  91035. positions.push(p1.x, 0, p1.y);
  91036. positions.push(p1.x, -depth, p1.y);
  91037. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  91038. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  91039. var v3 = v2.subtract(v1);
  91040. var v4 = new BABYLON.Vector3(0, 1, 0);
  91041. var vn = BABYLON.Vector3.Cross(v3, v4);
  91042. vn = vn.normalize();
  91043. uvs.push(ulength / bounds.width, 0);
  91044. uvs.push(ulength / bounds.width, 1);
  91045. ulength += v3.length();
  91046. uvs.push((ulength / bounds.width), 0);
  91047. uvs.push((ulength / bounds.width), 1);
  91048. if (!flip) {
  91049. normals.push(-vn.x, -vn.y, -vn.z);
  91050. normals.push(-vn.x, -vn.y, -vn.z);
  91051. normals.push(-vn.x, -vn.y, -vn.z);
  91052. normals.push(-vn.x, -vn.y, -vn.z);
  91053. indices.push(StartIndex);
  91054. indices.push(StartIndex + 1);
  91055. indices.push(StartIndex + 2);
  91056. indices.push(StartIndex + 1);
  91057. indices.push(StartIndex + 3);
  91058. indices.push(StartIndex + 2);
  91059. }
  91060. else {
  91061. normals.push(vn.x, vn.y, vn.z);
  91062. normals.push(vn.x, vn.y, vn.z);
  91063. normals.push(vn.x, vn.y, vn.z);
  91064. normals.push(vn.x, vn.y, vn.z);
  91065. indices.push(StartIndex);
  91066. indices.push(StartIndex + 2);
  91067. indices.push(StartIndex + 1);
  91068. indices.push(StartIndex + 1);
  91069. indices.push(StartIndex + 2);
  91070. indices.push(StartIndex + 3);
  91071. }
  91072. StartIndex += 4;
  91073. }
  91074. ;
  91075. };
  91076. return PolygonMeshBuilder;
  91077. }());
  91078. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  91079. })(BABYLON || (BABYLON = {}));
  91080. //# sourceMappingURL=babylon.polygonMesh.js.map
  91081. var BABYLON;
  91082. (function (BABYLON) {
  91083. /**
  91084. * Unique ID when we import meshes from Babylon to CSG
  91085. */
  91086. var currentCSGMeshId = 0;
  91087. /**
  91088. * Represents a vertex of a polygon. Use your own vertex class instead of this
  91089. * one to provide additional features like texture coordinates and vertex
  91090. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  91091. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  91092. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  91093. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  91094. * is not used anywhere else.
  91095. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  91096. */
  91097. var Vertex = /** @class */ (function () {
  91098. /**
  91099. * Initializes the vertex
  91100. * @param pos The position of the vertex
  91101. * @param normal The normal of the vertex
  91102. * @param uv The texture coordinate of the vertex
  91103. */
  91104. function Vertex(
  91105. /**
  91106. * The position of the vertex
  91107. */
  91108. pos,
  91109. /**
  91110. * The normal of the vertex
  91111. */
  91112. normal,
  91113. /**
  91114. * The texture coordinate of the vertex
  91115. */
  91116. uv) {
  91117. this.pos = pos;
  91118. this.normal = normal;
  91119. this.uv = uv;
  91120. }
  91121. /**
  91122. * Make a clone, or deep copy, of the vertex
  91123. * @returns A new Vertex
  91124. */
  91125. Vertex.prototype.clone = function () {
  91126. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  91127. };
  91128. /**
  91129. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  91130. * orientation of a polygon is flipped.
  91131. */
  91132. Vertex.prototype.flip = function () {
  91133. this.normal = this.normal.scale(-1);
  91134. };
  91135. /**
  91136. * Create a new vertex between this vertex and `other` by linearly
  91137. * interpolating all properties using a parameter of `t`. Subclasses should
  91138. * override this to interpolate additional properties.
  91139. * @param other the vertex to interpolate against
  91140. * @param t The factor used to linearly interpolate between the vertices
  91141. */
  91142. Vertex.prototype.interpolate = function (other, t) {
  91143. 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));
  91144. };
  91145. return Vertex;
  91146. }());
  91147. /**
  91148. * Represents a plane in 3D space.
  91149. */
  91150. var Plane = /** @class */ (function () {
  91151. /**
  91152. * Initializes the plane
  91153. * @param normal The normal for the plane
  91154. * @param w
  91155. */
  91156. function Plane(normal, w) {
  91157. this.normal = normal;
  91158. this.w = w;
  91159. }
  91160. /**
  91161. * Construct a plane from three points
  91162. * @param a Point a
  91163. * @param b Point b
  91164. * @param c Point c
  91165. */
  91166. Plane.FromPoints = function (a, b, c) {
  91167. var v0 = c.subtract(a);
  91168. var v1 = b.subtract(a);
  91169. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  91170. return null;
  91171. }
  91172. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  91173. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  91174. };
  91175. /**
  91176. * Clone, or make a deep copy of the plane
  91177. * @returns a new Plane
  91178. */
  91179. Plane.prototype.clone = function () {
  91180. return new Plane(this.normal.clone(), this.w);
  91181. };
  91182. /**
  91183. * Flip the face of the plane
  91184. */
  91185. Plane.prototype.flip = function () {
  91186. this.normal.scaleInPlace(-1);
  91187. this.w = -this.w;
  91188. };
  91189. /**
  91190. * Split `polygon` by this plane if needed, then put the polygon or polygon
  91191. * fragments in the appropriate lists. Coplanar polygons go into either
  91192. `* coplanarFront` or `coplanarBack` depending on their orientation with
  91193. * respect to this plane. Polygons in front or in back of this plane go into
  91194. * either `front` or `back`
  91195. * @param polygon The polygon to be split
  91196. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  91197. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  91198. * @param front Will contain the polygons in front of the plane
  91199. * @param back Will contain the polygons begind the plane
  91200. */
  91201. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  91202. var COPLANAR = 0;
  91203. var FRONT = 1;
  91204. var BACK = 2;
  91205. var SPANNING = 3;
  91206. // Classify each point as well as the entire polygon into one of the above
  91207. // four classes.
  91208. var polygonType = 0;
  91209. var types = [];
  91210. var i;
  91211. var t;
  91212. for (i = 0; i < polygon.vertices.length; i++) {
  91213. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  91214. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  91215. polygonType |= type;
  91216. types.push(type);
  91217. }
  91218. // Put the polygon in the correct list, splitting it when necessary
  91219. switch (polygonType) {
  91220. case COPLANAR:
  91221. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  91222. break;
  91223. case FRONT:
  91224. front.push(polygon);
  91225. break;
  91226. case BACK:
  91227. back.push(polygon);
  91228. break;
  91229. case SPANNING:
  91230. var f = [], b = [];
  91231. for (i = 0; i < polygon.vertices.length; i++) {
  91232. var j = (i + 1) % polygon.vertices.length;
  91233. var ti = types[i], tj = types[j];
  91234. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  91235. if (ti !== BACK)
  91236. f.push(vi);
  91237. if (ti !== FRONT)
  91238. b.push(ti !== BACK ? vi.clone() : vi);
  91239. if ((ti | tj) === SPANNING) {
  91240. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  91241. var v = vi.interpolate(vj, t);
  91242. f.push(v);
  91243. b.push(v.clone());
  91244. }
  91245. }
  91246. var poly;
  91247. if (f.length >= 3) {
  91248. poly = new Polygon(f, polygon.shared);
  91249. if (poly.plane)
  91250. front.push(poly);
  91251. }
  91252. if (b.length >= 3) {
  91253. poly = new Polygon(b, polygon.shared);
  91254. if (poly.plane)
  91255. back.push(poly);
  91256. }
  91257. break;
  91258. }
  91259. };
  91260. /**
  91261. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  91262. * point is on the plane
  91263. */
  91264. Plane.EPSILON = 1e-5;
  91265. return Plane;
  91266. }());
  91267. /**
  91268. * Represents a convex polygon. The vertices used to initialize a polygon must
  91269. * be coplanar and form a convex loop.
  91270. *
  91271. * Each convex polygon has a `shared` property, which is shared between all
  91272. * polygons that are clones of each other or were split from the same polygon.
  91273. * This can be used to define per-polygon properties (such as surface color)
  91274. */
  91275. var Polygon = /** @class */ (function () {
  91276. /**
  91277. * Initializes the polygon
  91278. * @param vertices The vertices of the polygon
  91279. * @param shared The properties shared across all polygons
  91280. */
  91281. function Polygon(vertices, shared) {
  91282. this.vertices = vertices;
  91283. this.shared = shared;
  91284. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  91285. }
  91286. /**
  91287. * Clones, or makes a deep copy, or the polygon
  91288. */
  91289. Polygon.prototype.clone = function () {
  91290. var vertices = this.vertices.map(function (v) { return v.clone(); });
  91291. return new Polygon(vertices, this.shared);
  91292. };
  91293. /**
  91294. * Flips the faces of the polygon
  91295. */
  91296. Polygon.prototype.flip = function () {
  91297. this.vertices.reverse().map(function (v) { v.flip(); });
  91298. this.plane.flip();
  91299. };
  91300. return Polygon;
  91301. }());
  91302. /**
  91303. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  91304. * by picking a polygon to split along. That polygon (and all other coplanar
  91305. * polygons) are added directly to that node and the other polygons are added to
  91306. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  91307. * no distinction between internal and leaf nodes
  91308. */
  91309. var Node = /** @class */ (function () {
  91310. /**
  91311. * Initializes the node
  91312. * @param polygons A collection of polygons held in the node
  91313. */
  91314. function Node(polygons) {
  91315. this.plane = null;
  91316. this.front = null;
  91317. this.back = null;
  91318. this.polygons = new Array();
  91319. if (polygons) {
  91320. this.build(polygons);
  91321. }
  91322. }
  91323. /**
  91324. * Clones, or makes a deep copy, of the node
  91325. * @returns The cloned node
  91326. */
  91327. Node.prototype.clone = function () {
  91328. var node = new Node();
  91329. node.plane = this.plane && this.plane.clone();
  91330. node.front = this.front && this.front.clone();
  91331. node.back = this.back && this.back.clone();
  91332. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  91333. return node;
  91334. };
  91335. /**
  91336. * Convert solid space to empty space and empty space to solid space
  91337. */
  91338. Node.prototype.invert = function () {
  91339. for (var i = 0; i < this.polygons.length; i++) {
  91340. this.polygons[i].flip();
  91341. }
  91342. if (this.plane) {
  91343. this.plane.flip();
  91344. }
  91345. if (this.front) {
  91346. this.front.invert();
  91347. }
  91348. if (this.back) {
  91349. this.back.invert();
  91350. }
  91351. var temp = this.front;
  91352. this.front = this.back;
  91353. this.back = temp;
  91354. };
  91355. /**
  91356. * Recursively remove all polygons in `polygons` that are inside this BSP
  91357. * tree.
  91358. * @param polygons Polygons to remove from the BSP
  91359. * @returns Polygons clipped from the BSP
  91360. */
  91361. Node.prototype.clipPolygons = function (polygons) {
  91362. if (!this.plane)
  91363. return polygons.slice();
  91364. var front = new Array(), back = new Array();
  91365. for (var i = 0; i < polygons.length; i++) {
  91366. this.plane.splitPolygon(polygons[i], front, back, front, back);
  91367. }
  91368. if (this.front) {
  91369. front = this.front.clipPolygons(front);
  91370. }
  91371. if (this.back) {
  91372. back = this.back.clipPolygons(back);
  91373. }
  91374. else {
  91375. back = [];
  91376. }
  91377. return front.concat(back);
  91378. };
  91379. /**
  91380. * Remove all polygons in this BSP tree that are inside the other BSP tree
  91381. * `bsp`.
  91382. * @param bsp BSP containing polygons to remove from this BSP
  91383. */
  91384. Node.prototype.clipTo = function (bsp) {
  91385. this.polygons = bsp.clipPolygons(this.polygons);
  91386. if (this.front)
  91387. this.front.clipTo(bsp);
  91388. if (this.back)
  91389. this.back.clipTo(bsp);
  91390. };
  91391. /**
  91392. * Return a list of all polygons in this BSP tree
  91393. * @returns List of all polygons in this BSP tree
  91394. */
  91395. Node.prototype.allPolygons = function () {
  91396. var polygons = this.polygons.slice();
  91397. if (this.front)
  91398. polygons = polygons.concat(this.front.allPolygons());
  91399. if (this.back)
  91400. polygons = polygons.concat(this.back.allPolygons());
  91401. return polygons;
  91402. };
  91403. /**
  91404. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  91405. * new polygons are filtered down to the bottom of the tree and become new
  91406. * nodes there. Each set of polygons is partitioned using the first polygon
  91407. * (no heuristic is used to pick a good split)
  91408. * @param polygons Polygons used to construct the BSP tree
  91409. */
  91410. Node.prototype.build = function (polygons) {
  91411. if (!polygons.length)
  91412. return;
  91413. if (!this.plane)
  91414. this.plane = polygons[0].plane.clone();
  91415. var front = new Array(), back = new Array();
  91416. for (var i = 0; i < polygons.length; i++) {
  91417. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  91418. }
  91419. if (front.length) {
  91420. if (!this.front)
  91421. this.front = new Node();
  91422. this.front.build(front);
  91423. }
  91424. if (back.length) {
  91425. if (!this.back)
  91426. this.back = new Node();
  91427. this.back.build(back);
  91428. }
  91429. };
  91430. return Node;
  91431. }());
  91432. /**
  91433. * Class for building Constructive Solid Geometry
  91434. */
  91435. var CSG = /** @class */ (function () {
  91436. function CSG() {
  91437. this.polygons = new Array();
  91438. }
  91439. /**
  91440. * Convert the BABYLON.Mesh to BABYLON.CSG
  91441. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  91442. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  91443. */
  91444. CSG.FromMesh = function (mesh) {
  91445. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  91446. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  91447. if (mesh instanceof BABYLON.Mesh) {
  91448. mesh.computeWorldMatrix(true);
  91449. matrix = mesh.getWorldMatrix();
  91450. meshPosition = mesh.position.clone();
  91451. meshRotation = mesh.rotation.clone();
  91452. if (mesh.rotationQuaternion) {
  91453. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  91454. }
  91455. meshScaling = mesh.scaling.clone();
  91456. }
  91457. else {
  91458. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  91459. }
  91460. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  91461. var subMeshes = mesh.subMeshes;
  91462. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  91463. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  91464. vertices = [];
  91465. for (var j = 0; j < 3; j++) {
  91466. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  91467. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  91468. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  91469. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  91470. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  91471. vertex = new Vertex(position, normal, uv);
  91472. vertices.push(vertex);
  91473. }
  91474. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  91475. // To handle the case of degenerated triangle
  91476. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  91477. if (polygon.plane)
  91478. polygons.push(polygon);
  91479. }
  91480. }
  91481. var csg = CSG.FromPolygons(polygons);
  91482. csg.matrix = matrix;
  91483. csg.position = meshPosition;
  91484. csg.rotation = meshRotation;
  91485. csg.scaling = meshScaling;
  91486. csg.rotationQuaternion = meshRotationQuaternion;
  91487. currentCSGMeshId++;
  91488. return csg;
  91489. };
  91490. /**
  91491. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  91492. * @param polygons Polygons used to construct a BABYLON.CSG solid
  91493. */
  91494. CSG.FromPolygons = function (polygons) {
  91495. var csg = new CSG();
  91496. csg.polygons = polygons;
  91497. return csg;
  91498. };
  91499. /**
  91500. * Clones, or makes a deep copy, of the BABYLON.CSG
  91501. * @returns A new BABYLON.CSG
  91502. */
  91503. CSG.prototype.clone = function () {
  91504. var csg = new CSG();
  91505. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  91506. csg.copyTransformAttributes(this);
  91507. return csg;
  91508. };
  91509. /**
  91510. * Unions this CSG with another CSG
  91511. * @param csg The CSG to union against this CSG
  91512. * @returns The unioned CSG
  91513. */
  91514. CSG.prototype.union = function (csg) {
  91515. var a = new Node(this.clone().polygons);
  91516. var b = new Node(csg.clone().polygons);
  91517. a.clipTo(b);
  91518. b.clipTo(a);
  91519. b.invert();
  91520. b.clipTo(a);
  91521. b.invert();
  91522. a.build(b.allPolygons());
  91523. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  91524. };
  91525. /**
  91526. * Unions this CSG with another CSG in place
  91527. * @param csg The CSG to union against this CSG
  91528. */
  91529. CSG.prototype.unionInPlace = function (csg) {
  91530. var a = new Node(this.polygons);
  91531. var b = new Node(csg.polygons);
  91532. a.clipTo(b);
  91533. b.clipTo(a);
  91534. b.invert();
  91535. b.clipTo(a);
  91536. b.invert();
  91537. a.build(b.allPolygons());
  91538. this.polygons = a.allPolygons();
  91539. };
  91540. /**
  91541. * Subtracts this CSG with another CSG
  91542. * @param csg The CSG to subtract against this CSG
  91543. * @returns A new BABYLON.CSG
  91544. */
  91545. CSG.prototype.subtract = function (csg) {
  91546. var a = new Node(this.clone().polygons);
  91547. var b = new Node(csg.clone().polygons);
  91548. a.invert();
  91549. a.clipTo(b);
  91550. b.clipTo(a);
  91551. b.invert();
  91552. b.clipTo(a);
  91553. b.invert();
  91554. a.build(b.allPolygons());
  91555. a.invert();
  91556. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  91557. };
  91558. /**
  91559. * Subtracts this CSG with another CSG in place
  91560. * @param csg The CSG to subtact against this CSG
  91561. */
  91562. CSG.prototype.subtractInPlace = function (csg) {
  91563. var a = new Node(this.polygons);
  91564. var b = new Node(csg.polygons);
  91565. a.invert();
  91566. a.clipTo(b);
  91567. b.clipTo(a);
  91568. b.invert();
  91569. b.clipTo(a);
  91570. b.invert();
  91571. a.build(b.allPolygons());
  91572. a.invert();
  91573. this.polygons = a.allPolygons();
  91574. };
  91575. /**
  91576. * Intersect this CSG with another CSG
  91577. * @param csg The CSG to intersect against this CSG
  91578. * @returns A new BABYLON.CSG
  91579. */
  91580. CSG.prototype.intersect = function (csg) {
  91581. var a = new Node(this.clone().polygons);
  91582. var b = new Node(csg.clone().polygons);
  91583. a.invert();
  91584. b.clipTo(a);
  91585. b.invert();
  91586. a.clipTo(b);
  91587. b.clipTo(a);
  91588. a.build(b.allPolygons());
  91589. a.invert();
  91590. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  91591. };
  91592. /**
  91593. * Intersects this CSG with another CSG in place
  91594. * @param csg The CSG to intersect against this CSG
  91595. */
  91596. CSG.prototype.intersectInPlace = function (csg) {
  91597. var a = new Node(this.polygons);
  91598. var b = new Node(csg.polygons);
  91599. a.invert();
  91600. b.clipTo(a);
  91601. b.invert();
  91602. a.clipTo(b);
  91603. b.clipTo(a);
  91604. a.build(b.allPolygons());
  91605. a.invert();
  91606. this.polygons = a.allPolygons();
  91607. };
  91608. /**
  91609. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  91610. * not modified.
  91611. * @returns A new BABYLON.CSG solid with solid and empty space switched
  91612. */
  91613. CSG.prototype.inverse = function () {
  91614. var csg = this.clone();
  91615. csg.inverseInPlace();
  91616. return csg;
  91617. };
  91618. /**
  91619. * Inverses the BABYLON.CSG in place
  91620. */
  91621. CSG.prototype.inverseInPlace = function () {
  91622. this.polygons.map(function (p) { p.flip(); });
  91623. };
  91624. /**
  91625. * This is used to keep meshes transformations so they can be restored
  91626. * when we build back a Babylon Mesh
  91627. * NB : All CSG operations are performed in world coordinates
  91628. * @param csg The BABYLON.CSG to copy the transform attributes from
  91629. * @returns This BABYLON.CSG
  91630. */
  91631. CSG.prototype.copyTransformAttributes = function (csg) {
  91632. this.matrix = csg.matrix;
  91633. this.position = csg.position;
  91634. this.rotation = csg.rotation;
  91635. this.scaling = csg.scaling;
  91636. this.rotationQuaternion = csg.rotationQuaternion;
  91637. return this;
  91638. };
  91639. /**
  91640. * Build Raw mesh from CSG
  91641. * Coordinates here are in world space
  91642. * @param name The name of the mesh geometry
  91643. * @param scene The BABYLON.Scene
  91644. * @param keepSubMeshes Specifies if the submeshes should be kept
  91645. * @returns A new BABYLON.Mesh
  91646. */
  91647. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  91648. var matrix = this.matrix.clone();
  91649. matrix.invert();
  91650. 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;
  91651. if (keepSubMeshes) {
  91652. // Sort Polygons, since subMeshes are indices range
  91653. polygons.sort(function (a, b) {
  91654. if (a.shared.meshId === b.shared.meshId) {
  91655. return a.shared.subMeshId - b.shared.subMeshId;
  91656. }
  91657. else {
  91658. return a.shared.meshId - b.shared.meshId;
  91659. }
  91660. });
  91661. }
  91662. for (var i = 0, il = polygons.length; i < il; i++) {
  91663. polygon = polygons[i];
  91664. // Building SubMeshes
  91665. if (!subMesh_dict[polygon.shared.meshId]) {
  91666. subMesh_dict[polygon.shared.meshId] = {};
  91667. }
  91668. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  91669. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  91670. indexStart: +Infinity,
  91671. indexEnd: -Infinity,
  91672. materialIndex: polygon.shared.materialIndex
  91673. };
  91674. }
  91675. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  91676. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  91677. polygonIndices[0] = 0;
  91678. polygonIndices[1] = j - 1;
  91679. polygonIndices[2] = j;
  91680. for (var k = 0; k < 3; k++) {
  91681. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  91682. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  91683. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  91684. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  91685. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  91686. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  91687. // Check if 2 points can be merged
  91688. if (!(typeof vertex_idx !== 'undefined' &&
  91689. normals[vertex_idx * 3] === localNormal.x &&
  91690. normals[vertex_idx * 3 + 1] === localNormal.y &&
  91691. normals[vertex_idx * 3 + 2] === localNormal.z &&
  91692. uvs[vertex_idx * 2] === uv.x &&
  91693. uvs[vertex_idx * 2 + 1] === uv.y)) {
  91694. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  91695. uvs.push(uv.x, uv.y);
  91696. normals.push(normal.x, normal.y, normal.z);
  91697. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  91698. }
  91699. indices.push(vertex_idx);
  91700. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  91701. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  91702. currentIndex++;
  91703. }
  91704. }
  91705. }
  91706. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  91707. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  91708. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  91709. mesh.setIndices(indices, null);
  91710. if (keepSubMeshes) {
  91711. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  91712. var materialIndexOffset = 0, materialMaxIndex;
  91713. mesh.subMeshes = new Array();
  91714. for (var m in subMesh_dict) {
  91715. materialMaxIndex = -1;
  91716. for (var sm in subMesh_dict[m]) {
  91717. subMesh_obj = subMesh_dict[m][sm];
  91718. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  91719. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  91720. }
  91721. materialIndexOffset += ++materialMaxIndex;
  91722. }
  91723. }
  91724. return mesh;
  91725. };
  91726. /**
  91727. * Build Mesh from CSG taking material and transforms into account
  91728. * @param name The name of the BABYLON.Mesh
  91729. * @param material The material of the BABYLON.Mesh
  91730. * @param scene The BABYLON.Scene
  91731. * @param keepSubMeshes Specifies if submeshes should be kept
  91732. * @returns The new BABYLON.Mesh
  91733. */
  91734. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  91735. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  91736. mesh.material = material;
  91737. mesh.position.copyFrom(this.position);
  91738. mesh.rotation.copyFrom(this.rotation);
  91739. if (this.rotationQuaternion) {
  91740. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  91741. }
  91742. mesh.scaling.copyFrom(this.scaling);
  91743. mesh.computeWorldMatrix(true);
  91744. return mesh;
  91745. };
  91746. return CSG;
  91747. }());
  91748. BABYLON.CSG = CSG;
  91749. })(BABYLON || (BABYLON = {}));
  91750. //# sourceMappingURL=babylon.csg.js.map
  91751. var BABYLON;
  91752. (function (BABYLON) {
  91753. /**
  91754. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  91755. * It controls one of the indiviual texture used in the effect.
  91756. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91757. */
  91758. var LensFlare = /** @class */ (function () {
  91759. /**
  91760. * Instantiates a new Lens Flare.
  91761. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  91762. * It controls one of the indiviual texture used in the effect.
  91763. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91764. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  91765. * @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.
  91766. * @param color Define the lens color
  91767. * @param imgUrl Define the lens texture url
  91768. * @param system Define the `lensFlareSystem` this flare is part of
  91769. */
  91770. function LensFlare(
  91771. /**
  91772. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  91773. */
  91774. size,
  91775. /**
  91776. * 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.
  91777. */
  91778. position, color, imgUrl, system) {
  91779. this.size = size;
  91780. this.position = position;
  91781. /**
  91782. * Define the alpha mode to render this particular lens.
  91783. */
  91784. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91785. this.color = color || new BABYLON.Color3(1, 1, 1);
  91786. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  91787. this._system = system;
  91788. system.lensFlares.push(this);
  91789. }
  91790. /**
  91791. * Creates a new Lens Flare.
  91792. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  91793. * It controls one of the indiviual texture used in the effect.
  91794. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91795. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  91796. * @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.
  91797. * @param color Define the lens color
  91798. * @param imgUrl Define the lens texture url
  91799. * @param system Define the `lensFlareSystem` this flare is part of
  91800. * @returns The newly created Lens Flare
  91801. */
  91802. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  91803. return new LensFlare(size, position, color, imgUrl, system);
  91804. };
  91805. /**
  91806. * Dispose and release the lens flare with its associated resources.
  91807. */
  91808. LensFlare.prototype.dispose = function () {
  91809. if (this.texture) {
  91810. this.texture.dispose();
  91811. }
  91812. // Remove from scene
  91813. var index = this._system.lensFlares.indexOf(this);
  91814. this._system.lensFlares.splice(index, 1);
  91815. };
  91816. ;
  91817. return LensFlare;
  91818. }());
  91819. BABYLON.LensFlare = LensFlare;
  91820. })(BABYLON || (BABYLON = {}));
  91821. //# sourceMappingURL=babylon.lensFlare.js.map
  91822. var BABYLON;
  91823. (function (BABYLON) {
  91824. // Adds the parser to the scene parsers.
  91825. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  91826. // Lens flares
  91827. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  91828. if (!container.lensFlareSystems) {
  91829. container.lensFlareSystems = new Array();
  91830. }
  91831. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  91832. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  91833. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  91834. container.lensFlareSystems.push(lf);
  91835. }
  91836. }
  91837. });
  91838. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  91839. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91840. if (this.lensFlareSystems[index].name === name) {
  91841. return this.lensFlareSystems[index];
  91842. }
  91843. }
  91844. return null;
  91845. };
  91846. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  91847. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91848. if (this.lensFlareSystems[index].id === id) {
  91849. return this.lensFlareSystems[index];
  91850. }
  91851. }
  91852. return null;
  91853. };
  91854. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  91855. var index = this.lensFlareSystems.indexOf(toRemove);
  91856. if (index !== -1) {
  91857. this.lensFlareSystems.splice(index, 1);
  91858. }
  91859. return index;
  91860. };
  91861. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  91862. this.lensFlareSystems.push(newLensFlareSystem);
  91863. };
  91864. /**
  91865. * Defines the lens flare scene component responsible to manage any lens flares
  91866. * in a given scene.
  91867. */
  91868. var LensFlareSystemSceneComponent = /** @class */ (function () {
  91869. /**
  91870. * Creates a new instance of the component for the given scene
  91871. * @param scene Defines the scene to register the component in
  91872. */
  91873. function LensFlareSystemSceneComponent(scene) {
  91874. /**
  91875. * The component name helpfull to identify the component in the list of scene components.
  91876. */
  91877. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  91878. this.scene = scene;
  91879. scene.lensFlareSystems = new Array();
  91880. }
  91881. /**
  91882. * Registers the component in a given scene
  91883. */
  91884. LensFlareSystemSceneComponent.prototype.register = function () {
  91885. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  91886. };
  91887. /**
  91888. * Rebuilds the elements related to this component in case of
  91889. * context lost for instance.
  91890. */
  91891. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  91892. // Nothing to do for lens flare
  91893. };
  91894. /**
  91895. * Adds all the element from the container to the scene
  91896. * @param container the container holding the elements
  91897. */
  91898. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  91899. var _this = this;
  91900. if (!container.lensFlareSystems) {
  91901. return;
  91902. }
  91903. container.lensFlareSystems.forEach(function (o) {
  91904. _this.scene.addLensFlareSystem(o);
  91905. });
  91906. };
  91907. /**
  91908. * Removes all the elements in the container from the scene
  91909. * @param container contains the elements to remove
  91910. */
  91911. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  91912. var _this = this;
  91913. if (!container.lensFlareSystems) {
  91914. return;
  91915. }
  91916. container.lensFlareSystems.forEach(function (o) {
  91917. _this.scene.removeLensFlareSystem(o);
  91918. });
  91919. };
  91920. /**
  91921. * Serializes the component data to the specified json object
  91922. * @param serializationObject The object to serialize to
  91923. */
  91924. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  91925. // Lens flares
  91926. serializationObject.lensFlareSystems = [];
  91927. var lensFlareSystems = this.scene.lensFlareSystems;
  91928. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  91929. var lensFlareSystem = lensFlareSystems_1[_i];
  91930. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  91931. }
  91932. };
  91933. /**
  91934. * Disposes the component and the associated ressources.
  91935. */
  91936. LensFlareSystemSceneComponent.prototype.dispose = function () {
  91937. var lensFlareSystems = this.scene.lensFlareSystems;
  91938. while (lensFlareSystems.length) {
  91939. lensFlareSystems[0].dispose();
  91940. }
  91941. };
  91942. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  91943. // Lens flares
  91944. if (this.scene.lensFlaresEnabled) {
  91945. var lensFlareSystems = this.scene.lensFlareSystems;
  91946. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91947. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  91948. var lensFlareSystem = lensFlareSystems_2[_i];
  91949. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  91950. lensFlareSystem.render();
  91951. }
  91952. }
  91953. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91954. }
  91955. };
  91956. return LensFlareSystemSceneComponent;
  91957. }());
  91958. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  91959. })(BABYLON || (BABYLON = {}));
  91960. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  91961. var BABYLON;
  91962. (function (BABYLON) {
  91963. /**
  91964. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91965. * It is usually composed of several `BABYLON.lensFlare`.
  91966. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91967. */
  91968. var LensFlareSystem = /** @class */ (function () {
  91969. /**
  91970. * Instantiates a lens flare system.
  91971. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91972. * It is usually composed of several `BABYLON.lensFlare`.
  91973. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91974. * @param name Define the name of the lens flare system in the scene
  91975. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  91976. * @param scene Define the scene the lens flare system belongs to
  91977. */
  91978. function LensFlareSystem(
  91979. /**
  91980. * Define the name of the lens flare system
  91981. */
  91982. name, emitter, scene) {
  91983. this.name = name;
  91984. /**
  91985. * List of lens flares used in this system.
  91986. */
  91987. this.lensFlares = new Array();
  91988. /**
  91989. * Define a limit from the border the lens flare can be visible.
  91990. */
  91991. this.borderLimit = 300;
  91992. /**
  91993. * Define a viewport border we do not want to see the lens flare in.
  91994. */
  91995. this.viewportBorder = 0;
  91996. /**
  91997. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  91998. */
  91999. this.layerMask = 0x0FFFFFFF;
  92000. this._vertexBuffers = {};
  92001. this._isEnabled = true;
  92002. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92003. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  92004. if (!component) {
  92005. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  92006. scene._addComponent(component);
  92007. }
  92008. this._emitter = emitter;
  92009. this.id = name;
  92010. scene.lensFlareSystems.push(this);
  92011. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  92012. var engine = scene.getEngine();
  92013. // VBO
  92014. var vertices = [];
  92015. vertices.push(1, 1);
  92016. vertices.push(-1, 1);
  92017. vertices.push(-1, -1);
  92018. vertices.push(1, -1);
  92019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92020. // Indices
  92021. var indices = [];
  92022. indices.push(0);
  92023. indices.push(1);
  92024. indices.push(2);
  92025. indices.push(0);
  92026. indices.push(2);
  92027. indices.push(3);
  92028. this._indexBuffer = engine.createIndexBuffer(indices);
  92029. // Effects
  92030. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  92031. }
  92032. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  92033. /**
  92034. * Define if the lens flare system is enabled.
  92035. */
  92036. get: function () {
  92037. return this._isEnabled;
  92038. },
  92039. set: function (value) {
  92040. this._isEnabled = value;
  92041. },
  92042. enumerable: true,
  92043. configurable: true
  92044. });
  92045. /**
  92046. * Get the scene the effects belongs to.
  92047. * @returns the scene holding the lens flare system
  92048. */
  92049. LensFlareSystem.prototype.getScene = function () {
  92050. return this._scene;
  92051. };
  92052. /**
  92053. * Get the emitter of the lens flare system.
  92054. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92055. * @returns the emitter of the lens flare system
  92056. */
  92057. LensFlareSystem.prototype.getEmitter = function () {
  92058. return this._emitter;
  92059. };
  92060. /**
  92061. * Set the emitter of the lens flare system.
  92062. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92063. * @param newEmitter Define the new emitter of the system
  92064. */
  92065. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  92066. this._emitter = newEmitter;
  92067. };
  92068. /**
  92069. * Get the lens flare system emitter position.
  92070. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  92071. * @returns the position
  92072. */
  92073. LensFlareSystem.prototype.getEmitterPosition = function () {
  92074. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  92075. };
  92076. /**
  92077. * @hidden
  92078. */
  92079. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  92080. var position = this.getEmitterPosition();
  92081. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  92082. this._positionX = position.x;
  92083. this._positionY = position.y;
  92084. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  92085. if (this.viewportBorder > 0) {
  92086. globalViewport.x -= this.viewportBorder;
  92087. globalViewport.y -= this.viewportBorder;
  92088. globalViewport.width += this.viewportBorder * 2;
  92089. globalViewport.height += this.viewportBorder * 2;
  92090. position.x += this.viewportBorder;
  92091. position.y += this.viewportBorder;
  92092. this._positionX += this.viewportBorder;
  92093. this._positionY += this.viewportBorder;
  92094. }
  92095. if (position.z > 0) {
  92096. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  92097. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  92098. return true;
  92099. }
  92100. return true;
  92101. }
  92102. return false;
  92103. };
  92104. /** @hidden */
  92105. LensFlareSystem.prototype._isVisible = function () {
  92106. if (!this._isEnabled || !this._scene.activeCamera) {
  92107. return false;
  92108. }
  92109. var emitterPosition = this.getEmitterPosition();
  92110. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  92111. var distance = direction.length();
  92112. direction.normalize();
  92113. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  92114. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  92115. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  92116. };
  92117. /**
  92118. * @hidden
  92119. */
  92120. LensFlareSystem.prototype.render = function () {
  92121. if (!this._effect.isReady() || !this._scene.activeCamera)
  92122. return false;
  92123. var engine = this._scene.getEngine();
  92124. var viewport = this._scene.activeCamera.viewport;
  92125. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  92126. // Position
  92127. if (!this.computeEffectivePosition(globalViewport)) {
  92128. return false;
  92129. }
  92130. // Visibility
  92131. if (!this._isVisible()) {
  92132. return false;
  92133. }
  92134. // Intensity
  92135. var awayX;
  92136. var awayY;
  92137. if (this._positionX < this.borderLimit + globalViewport.x) {
  92138. awayX = this.borderLimit + globalViewport.x - this._positionX;
  92139. }
  92140. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  92141. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  92142. }
  92143. else {
  92144. awayX = 0;
  92145. }
  92146. if (this._positionY < this.borderLimit + globalViewport.y) {
  92147. awayY = this.borderLimit + globalViewport.y - this._positionY;
  92148. }
  92149. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  92150. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  92151. }
  92152. else {
  92153. awayY = 0;
  92154. }
  92155. var away = (awayX > awayY) ? awayX : awayY;
  92156. away -= this.viewportBorder;
  92157. if (away > this.borderLimit) {
  92158. away = this.borderLimit;
  92159. }
  92160. var intensity = 1.0 - (away / this.borderLimit);
  92161. if (intensity < 0) {
  92162. return false;
  92163. }
  92164. if (intensity > 1.0) {
  92165. intensity = 1.0;
  92166. }
  92167. if (this.viewportBorder > 0) {
  92168. globalViewport.x += this.viewportBorder;
  92169. globalViewport.y += this.viewportBorder;
  92170. globalViewport.width -= this.viewportBorder * 2;
  92171. globalViewport.height -= this.viewportBorder * 2;
  92172. this._positionX -= this.viewportBorder;
  92173. this._positionY -= this.viewportBorder;
  92174. }
  92175. // Position
  92176. var centerX = globalViewport.x + globalViewport.width / 2;
  92177. var centerY = globalViewport.y + globalViewport.height / 2;
  92178. var distX = centerX - this._positionX;
  92179. var distY = centerY - this._positionY;
  92180. // Effects
  92181. engine.enableEffect(this._effect);
  92182. engine.setState(false);
  92183. engine.setDepthBuffer(false);
  92184. // VBOs
  92185. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  92186. // Flares
  92187. for (var index = 0; index < this.lensFlares.length; index++) {
  92188. var flare = this.lensFlares[index];
  92189. engine.setAlphaMode(flare.alphaMode);
  92190. var x = centerX - (distX * flare.position);
  92191. var y = centerY - (distY * flare.position);
  92192. var cw = flare.size;
  92193. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  92194. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  92195. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  92196. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  92197. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  92198. // Texture
  92199. this._effect.setTexture("textureSampler", flare.texture);
  92200. // Color
  92201. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  92202. // Draw order
  92203. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92204. }
  92205. engine.setDepthBuffer(true);
  92206. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  92207. return true;
  92208. };
  92209. /**
  92210. * Dispose and release the lens flare with its associated resources.
  92211. */
  92212. LensFlareSystem.prototype.dispose = function () {
  92213. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92214. if (vertexBuffer) {
  92215. vertexBuffer.dispose();
  92216. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92217. }
  92218. if (this._indexBuffer) {
  92219. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92220. this._indexBuffer = null;
  92221. }
  92222. while (this.lensFlares.length) {
  92223. this.lensFlares[0].dispose();
  92224. }
  92225. // Remove from scene
  92226. var index = this._scene.lensFlareSystems.indexOf(this);
  92227. this._scene.lensFlareSystems.splice(index, 1);
  92228. };
  92229. /**
  92230. * Parse a lens flare system from a JSON repressentation
  92231. * @param parsedLensFlareSystem Define the JSON to parse
  92232. * @param scene Define the scene the parsed system should be instantiated in
  92233. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  92234. * @returns the parsed system
  92235. */
  92236. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  92237. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  92238. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  92239. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  92240. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  92241. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  92242. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  92243. var parsedFlare = parsedLensFlareSystem.flares[index];
  92244. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  92245. }
  92246. return lensFlareSystem;
  92247. };
  92248. /**
  92249. * Serialize the current Lens Flare System into a JSON representation.
  92250. * @returns the serialized JSON
  92251. */
  92252. LensFlareSystem.prototype.serialize = function () {
  92253. var serializationObject = {};
  92254. serializationObject.id = this.id;
  92255. serializationObject.name = this.name;
  92256. serializationObject.emitterId = this.getEmitter().id;
  92257. serializationObject.borderLimit = this.borderLimit;
  92258. serializationObject.flares = [];
  92259. for (var index = 0; index < this.lensFlares.length; index++) {
  92260. var flare = this.lensFlares[index];
  92261. serializationObject.flares.push({
  92262. size: flare.size,
  92263. position: flare.position,
  92264. color: flare.color.asArray(),
  92265. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  92266. });
  92267. }
  92268. return serializationObject;
  92269. };
  92270. return LensFlareSystem;
  92271. }());
  92272. BABYLON.LensFlareSystem = LensFlareSystem;
  92273. })(BABYLON || (BABYLON = {}));
  92274. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  92275. var BABYLON;
  92276. (function (BABYLON) {
  92277. /**
  92278. * This is a holder class for the physics joint created by the physics plugin.
  92279. * It holds a set of functions to control the underlying joint.
  92280. */
  92281. var PhysicsJoint = /** @class */ (function () {
  92282. function PhysicsJoint(type, jointData) {
  92283. this.type = type;
  92284. this.jointData = jointData;
  92285. jointData.nativeParams = jointData.nativeParams || {};
  92286. }
  92287. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  92288. get: function () {
  92289. return this._physicsJoint;
  92290. },
  92291. set: function (newJoint) {
  92292. if (this._physicsJoint) {
  92293. //remove from the wolrd
  92294. }
  92295. this._physicsJoint = newJoint;
  92296. },
  92297. enumerable: true,
  92298. configurable: true
  92299. });
  92300. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  92301. set: function (physicsPlugin) {
  92302. this._physicsPlugin = physicsPlugin;
  92303. },
  92304. enumerable: true,
  92305. configurable: true
  92306. });
  92307. /**
  92308. * Execute a function that is physics-plugin specific.
  92309. * @param {Function} func the function that will be executed.
  92310. * It accepts two parameters: the physics world and the physics joint.
  92311. */
  92312. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  92313. func(this._physicsPlugin.world, this._physicsJoint);
  92314. };
  92315. //TODO check if the native joints are the same
  92316. //Joint Types
  92317. PhysicsJoint.DistanceJoint = 0;
  92318. PhysicsJoint.HingeJoint = 1;
  92319. PhysicsJoint.BallAndSocketJoint = 2;
  92320. PhysicsJoint.WheelJoint = 3;
  92321. PhysicsJoint.SliderJoint = 4;
  92322. //OIMO
  92323. PhysicsJoint.PrismaticJoint = 5;
  92324. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  92325. PhysicsJoint.UniversalJoint = 6;
  92326. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  92327. //Cannon
  92328. //Similar to a Ball-Joint. Different in params
  92329. PhysicsJoint.PointToPointJoint = 8;
  92330. //Cannon only at the moment
  92331. PhysicsJoint.SpringJoint = 9;
  92332. PhysicsJoint.LockJoint = 10;
  92333. return PhysicsJoint;
  92334. }());
  92335. BABYLON.PhysicsJoint = PhysicsJoint;
  92336. /**
  92337. * A class representing a physics distance joint.
  92338. */
  92339. var DistanceJoint = /** @class */ (function (_super) {
  92340. __extends(DistanceJoint, _super);
  92341. function DistanceJoint(jointData) {
  92342. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  92343. }
  92344. /**
  92345. * Update the predefined distance.
  92346. */
  92347. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  92348. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  92349. };
  92350. return DistanceJoint;
  92351. }(PhysicsJoint));
  92352. BABYLON.DistanceJoint = DistanceJoint;
  92353. var MotorEnabledJoint = /** @class */ (function (_super) {
  92354. __extends(MotorEnabledJoint, _super);
  92355. function MotorEnabledJoint(type, jointData) {
  92356. return _super.call(this, type, jointData) || this;
  92357. }
  92358. /**
  92359. * Set the motor values.
  92360. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92361. * @param {number} force the force to apply
  92362. * @param {number} maxForce max force for this motor.
  92363. */
  92364. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  92365. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  92366. };
  92367. /**
  92368. * Set the motor's limits.
  92369. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92370. */
  92371. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  92372. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  92373. };
  92374. return MotorEnabledJoint;
  92375. }(PhysicsJoint));
  92376. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  92377. /**
  92378. * This class represents a single hinge physics joint
  92379. */
  92380. var HingeJoint = /** @class */ (function (_super) {
  92381. __extends(HingeJoint, _super);
  92382. function HingeJoint(jointData) {
  92383. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  92384. }
  92385. /**
  92386. * Set the motor values.
  92387. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92388. * @param {number} force the force to apply
  92389. * @param {number} maxForce max force for this motor.
  92390. */
  92391. HingeJoint.prototype.setMotor = function (force, maxForce) {
  92392. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  92393. };
  92394. /**
  92395. * Set the motor's limits.
  92396. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92397. */
  92398. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  92399. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  92400. };
  92401. return HingeJoint;
  92402. }(MotorEnabledJoint));
  92403. BABYLON.HingeJoint = HingeJoint;
  92404. /**
  92405. * This class represents a dual hinge physics joint (same as wheel joint)
  92406. */
  92407. var Hinge2Joint = /** @class */ (function (_super) {
  92408. __extends(Hinge2Joint, _super);
  92409. function Hinge2Joint(jointData) {
  92410. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  92411. }
  92412. /**
  92413. * Set the motor values.
  92414. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92415. * @param {number} force the force to apply
  92416. * @param {number} maxForce max force for this motor.
  92417. * @param {motorIndex} the motor's index, 0 or 1.
  92418. */
  92419. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  92420. if (motorIndex === void 0) { motorIndex = 0; }
  92421. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  92422. };
  92423. /**
  92424. * Set the motor limits.
  92425. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92426. * @param {number} upperLimit the upper limit
  92427. * @param {number} lowerLimit lower limit
  92428. * @param {motorIndex} the motor's index, 0 or 1.
  92429. */
  92430. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  92431. if (motorIndex === void 0) { motorIndex = 0; }
  92432. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  92433. };
  92434. return Hinge2Joint;
  92435. }(MotorEnabledJoint));
  92436. BABYLON.Hinge2Joint = Hinge2Joint;
  92437. })(BABYLON || (BABYLON = {}));
  92438. //# sourceMappingURL=babylon.physicsJoint.js.map
  92439. var BABYLON;
  92440. (function (BABYLON) {
  92441. var PhysicsImpostor = /** @class */ (function () {
  92442. function PhysicsImpostor(object, type, _options, _scene) {
  92443. if (_options === void 0) { _options = { mass: 0 }; }
  92444. var _this = this;
  92445. this.object = object;
  92446. this.type = type;
  92447. this._options = _options;
  92448. this._scene = _scene;
  92449. this._bodyUpdateRequired = false;
  92450. this._onBeforePhysicsStepCallbacks = new Array();
  92451. this._onAfterPhysicsStepCallbacks = new Array();
  92452. this._onPhysicsCollideCallbacks = [];
  92453. this._deltaPosition = BABYLON.Vector3.Zero();
  92454. this._isDisposed = false;
  92455. //temp variables for parent rotation calculations
  92456. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  92457. this._tmpQuat = new BABYLON.Quaternion();
  92458. this._tmpQuat2 = new BABYLON.Quaternion();
  92459. /**
  92460. * this function is executed by the physics engine.
  92461. */
  92462. this.beforeStep = function () {
  92463. if (!_this._physicsEngine) {
  92464. return;
  92465. }
  92466. _this.object.translate(_this._deltaPosition, -1);
  92467. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  92468. _this.object.computeWorldMatrix(false);
  92469. if (_this.object.parent && _this.object.rotationQuaternion) {
  92470. _this.getParentsRotation();
  92471. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  92472. }
  92473. else {
  92474. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  92475. }
  92476. if (!_this._options.disableBidirectionalTransformation) {
  92477. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  92478. }
  92479. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  92480. func(_this);
  92481. });
  92482. };
  92483. /**
  92484. * this function is executed by the physics engine.
  92485. */
  92486. this.afterStep = function () {
  92487. if (!_this._physicsEngine) {
  92488. return;
  92489. }
  92490. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  92491. func(_this);
  92492. });
  92493. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  92494. // object has now its world rotation. needs to be converted to local.
  92495. if (_this.object.parent && _this.object.rotationQuaternion) {
  92496. _this.getParentsRotation();
  92497. _this._tmpQuat.conjugateInPlace();
  92498. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  92499. }
  92500. // take the position set and make it the absolute position of this object.
  92501. _this.object.setAbsolutePosition(_this.object.position);
  92502. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  92503. _this.object.translate(_this._deltaPosition, 1);
  92504. };
  92505. /**
  92506. * Legacy collision detection event support
  92507. */
  92508. this.onCollideEvent = null;
  92509. //event and body object due to cannon's event-based architecture.
  92510. this.onCollide = function (e) {
  92511. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  92512. return;
  92513. }
  92514. if (!_this._physicsEngine) {
  92515. return;
  92516. }
  92517. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  92518. if (otherImpostor) {
  92519. // Legacy collision detection event support
  92520. if (_this.onCollideEvent) {
  92521. _this.onCollideEvent(_this, otherImpostor);
  92522. }
  92523. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  92524. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  92525. }).forEach(function (obj) {
  92526. obj.callback(_this, otherImpostor);
  92527. });
  92528. }
  92529. };
  92530. //sanity check!
  92531. if (!this.object) {
  92532. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  92533. return;
  92534. }
  92535. //legacy support for old syntax.
  92536. if (!this._scene && object.getScene) {
  92537. this._scene = object.getScene();
  92538. }
  92539. if (!this._scene) {
  92540. return;
  92541. }
  92542. this._physicsEngine = this._scene.getPhysicsEngine();
  92543. if (!this._physicsEngine) {
  92544. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  92545. }
  92546. else {
  92547. //set the object's quaternion, if not set
  92548. if (!this.object.rotationQuaternion) {
  92549. if (this.object.rotation) {
  92550. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  92551. }
  92552. else {
  92553. this.object.rotationQuaternion = new BABYLON.Quaternion();
  92554. }
  92555. }
  92556. //default options params
  92557. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  92558. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  92559. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  92560. this._joints = [];
  92561. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  92562. if (!this.object.parent || this._options.ignoreParent) {
  92563. this._init();
  92564. }
  92565. else if (this.object.parent.physicsImpostor) {
  92566. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  92567. }
  92568. }
  92569. }
  92570. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  92571. get: function () {
  92572. return this._isDisposed;
  92573. },
  92574. enumerable: true,
  92575. configurable: true
  92576. });
  92577. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  92578. get: function () {
  92579. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  92580. },
  92581. set: function (value) {
  92582. this.setMass(value);
  92583. },
  92584. enumerable: true,
  92585. configurable: true
  92586. });
  92587. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  92588. get: function () {
  92589. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  92590. },
  92591. set: function (value) {
  92592. if (!this._physicsEngine) {
  92593. return;
  92594. }
  92595. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  92596. },
  92597. enumerable: true,
  92598. configurable: true
  92599. });
  92600. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  92601. get: function () {
  92602. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  92603. },
  92604. set: function (value) {
  92605. if (!this._physicsEngine) {
  92606. return;
  92607. }
  92608. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  92609. },
  92610. enumerable: true,
  92611. configurable: true
  92612. });
  92613. /**
  92614. * This function will completly initialize this impostor.
  92615. * It will create a new body - but only if this mesh has no parent.
  92616. * If it has, this impostor will not be used other than to define the impostor
  92617. * of the child mesh.
  92618. * @hidden
  92619. */
  92620. PhysicsImpostor.prototype._init = function () {
  92621. if (!this._physicsEngine) {
  92622. return;
  92623. }
  92624. this._physicsEngine.removeImpostor(this);
  92625. this.physicsBody = null;
  92626. this._parent = this._parent || this._getPhysicsParent();
  92627. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  92628. this._physicsEngine.addImpostor(this);
  92629. }
  92630. };
  92631. PhysicsImpostor.prototype._getPhysicsParent = function () {
  92632. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  92633. var parentMesh = this.object.parent;
  92634. return parentMesh.physicsImpostor;
  92635. }
  92636. return null;
  92637. };
  92638. /**
  92639. * Should a new body be generated.
  92640. */
  92641. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  92642. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  92643. };
  92644. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  92645. this.forceUpdate();
  92646. };
  92647. /**
  92648. * Force a regeneration of this or the parent's impostor's body.
  92649. * Use under cautious - This will remove all joints already implemented.
  92650. */
  92651. PhysicsImpostor.prototype.forceUpdate = function () {
  92652. this._init();
  92653. if (this.parent && !this._options.ignoreParent) {
  92654. this.parent.forceUpdate();
  92655. }
  92656. };
  92657. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  92658. /*public get mesh(): AbstractMesh {
  92659. return this._mesh;
  92660. }*/
  92661. /**
  92662. * Gets the body that holds this impostor. Either its own, or its parent.
  92663. */
  92664. get: function () {
  92665. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  92666. },
  92667. /**
  92668. * Set the physics body. Used mainly by the physics engine/plugin
  92669. */
  92670. set: function (physicsBody) {
  92671. if (this._physicsBody && this._physicsEngine) {
  92672. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  92673. }
  92674. this._physicsBody = physicsBody;
  92675. this.resetUpdateFlags();
  92676. },
  92677. enumerable: true,
  92678. configurable: true
  92679. });
  92680. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  92681. get: function () {
  92682. return !this._options.ignoreParent && this._parent ? this._parent : null;
  92683. },
  92684. set: function (value) {
  92685. this._parent = value;
  92686. },
  92687. enumerable: true,
  92688. configurable: true
  92689. });
  92690. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  92691. this._bodyUpdateRequired = false;
  92692. };
  92693. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  92694. if (this.object.getBoundingInfo) {
  92695. var q = this.object.rotationQuaternion;
  92696. //reset rotation
  92697. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  92698. //calculate the world matrix with no rotation
  92699. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  92700. var boundingInfo = this.object.getBoundingInfo();
  92701. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  92702. //bring back the rotation
  92703. this.object.rotationQuaternion = q;
  92704. //calculate the world matrix with the new rotation
  92705. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  92706. return size;
  92707. }
  92708. else {
  92709. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  92710. }
  92711. };
  92712. PhysicsImpostor.prototype.getObjectCenter = function () {
  92713. if (this.object.getBoundingInfo) {
  92714. var boundingInfo = this.object.getBoundingInfo();
  92715. return boundingInfo.boundingBox.centerWorld;
  92716. }
  92717. else {
  92718. return this.object.position;
  92719. }
  92720. };
  92721. /**
  92722. * Get a specific parametes from the options parameter.
  92723. */
  92724. PhysicsImpostor.prototype.getParam = function (paramName) {
  92725. return this._options[paramName];
  92726. };
  92727. /**
  92728. * Sets a specific parameter in the options given to the physics plugin
  92729. */
  92730. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  92731. this._options[paramName] = value;
  92732. this._bodyUpdateRequired = true;
  92733. };
  92734. /**
  92735. * Specifically change the body's mass option. Won't recreate the physics body object
  92736. */
  92737. PhysicsImpostor.prototype.setMass = function (mass) {
  92738. if (this.getParam("mass") !== mass) {
  92739. this.setParam("mass", mass);
  92740. }
  92741. if (this._physicsEngine) {
  92742. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  92743. }
  92744. };
  92745. PhysicsImpostor.prototype.getLinearVelocity = function () {
  92746. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  92747. };
  92748. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  92749. if (this._physicsEngine) {
  92750. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  92751. }
  92752. };
  92753. PhysicsImpostor.prototype.getAngularVelocity = function () {
  92754. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  92755. };
  92756. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  92757. if (this._physicsEngine) {
  92758. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  92759. }
  92760. };
  92761. /**
  92762. * Execute a function with the physics plugin native code.
  92763. * Provide a function the will have two variables - the world object and the physics body object.
  92764. */
  92765. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  92766. if (this._physicsEngine) {
  92767. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  92768. }
  92769. };
  92770. /**
  92771. * Register a function that will be executed before the physics world is stepping forward.
  92772. */
  92773. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  92774. this._onBeforePhysicsStepCallbacks.push(func);
  92775. };
  92776. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  92777. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  92778. if (index > -1) {
  92779. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  92780. }
  92781. else {
  92782. BABYLON.Tools.Warn("Function to remove was not found");
  92783. }
  92784. };
  92785. /**
  92786. * Register a function that will be executed after the physics step
  92787. */
  92788. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  92789. this._onAfterPhysicsStepCallbacks.push(func);
  92790. };
  92791. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  92792. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  92793. if (index > -1) {
  92794. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  92795. }
  92796. else {
  92797. BABYLON.Tools.Warn("Function to remove was not found");
  92798. }
  92799. };
  92800. /**
  92801. * register a function that will be executed when this impostor collides against a different body.
  92802. */
  92803. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  92804. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92805. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  92806. };
  92807. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  92808. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92809. var index = -1;
  92810. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  92811. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  92812. // chcek the arrays match
  92813. var sameList = cbDef.otherImpostors.every(function (impostor) {
  92814. return collidedAgainstList.indexOf(impostor) > -1;
  92815. });
  92816. if (sameList) {
  92817. index = idx;
  92818. }
  92819. return sameList;
  92820. }
  92821. return false;
  92822. });
  92823. if (found) {
  92824. this._onPhysicsCollideCallbacks.splice(index, 1);
  92825. }
  92826. else {
  92827. BABYLON.Tools.Warn("Function to remove was not found");
  92828. }
  92829. };
  92830. PhysicsImpostor.prototype.getParentsRotation = function () {
  92831. var parent = this.object.parent;
  92832. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  92833. while (parent) {
  92834. if (parent.rotationQuaternion) {
  92835. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  92836. }
  92837. else {
  92838. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  92839. }
  92840. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  92841. parent = parent.parent;
  92842. }
  92843. return this._tmpQuat;
  92844. };
  92845. /**
  92846. * Apply a force
  92847. */
  92848. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  92849. if (this._physicsEngine) {
  92850. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  92851. }
  92852. return this;
  92853. };
  92854. /**
  92855. * Apply an impulse
  92856. */
  92857. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  92858. if (this._physicsEngine) {
  92859. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  92860. }
  92861. return this;
  92862. };
  92863. /**
  92864. * A help function to create a joint.
  92865. */
  92866. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  92867. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  92868. this.addJoint(otherImpostor, joint);
  92869. return this;
  92870. };
  92871. /**
  92872. * Add a joint to this impostor with a different impostor.
  92873. */
  92874. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  92875. this._joints.push({
  92876. otherImpostor: otherImpostor,
  92877. joint: joint
  92878. });
  92879. if (this._physicsEngine) {
  92880. this._physicsEngine.addJoint(this, otherImpostor, joint);
  92881. }
  92882. return this;
  92883. };
  92884. /**
  92885. * Will keep this body still, in a sleep mode.
  92886. */
  92887. PhysicsImpostor.prototype.sleep = function () {
  92888. if (this._physicsEngine) {
  92889. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  92890. }
  92891. return this;
  92892. };
  92893. /**
  92894. * Wake the body up.
  92895. */
  92896. PhysicsImpostor.prototype.wakeUp = function () {
  92897. if (this._physicsEngine) {
  92898. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  92899. }
  92900. return this;
  92901. };
  92902. PhysicsImpostor.prototype.clone = function (newObject) {
  92903. if (!newObject)
  92904. return null;
  92905. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  92906. };
  92907. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  92908. var _this = this;
  92909. //no dispose if no physics engine is available.
  92910. if (!this._physicsEngine) {
  92911. return;
  92912. }
  92913. this._joints.forEach(function (j) {
  92914. if (_this._physicsEngine) {
  92915. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  92916. }
  92917. });
  92918. //dispose the physics body
  92919. this._physicsEngine.removeImpostor(this);
  92920. if (this.parent) {
  92921. this.parent.forceUpdate();
  92922. }
  92923. else {
  92924. /*this._object.getChildMeshes().forEach(function(mesh) {
  92925. if (mesh.physicsImpostor) {
  92926. if (disposeChildren) {
  92927. mesh.physicsImpostor.dispose();
  92928. mesh.physicsImpostor = null;
  92929. }
  92930. }
  92931. })*/
  92932. }
  92933. this._isDisposed = true;
  92934. };
  92935. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  92936. this._deltaPosition.copyFrom(position);
  92937. };
  92938. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  92939. if (!this._deltaRotation) {
  92940. this._deltaRotation = new BABYLON.Quaternion();
  92941. }
  92942. this._deltaRotation.copyFrom(rotation);
  92943. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  92944. };
  92945. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  92946. if (this._physicsEngine) {
  92947. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  92948. }
  92949. return this;
  92950. };
  92951. PhysicsImpostor.prototype.getRadius = function () {
  92952. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  92953. };
  92954. /**
  92955. * Sync a bone with this impostor
  92956. * @param bone The bone to sync to the impostor.
  92957. * @param boneMesh The mesh that the bone is influencing.
  92958. * @param jointPivot The pivot of the joint / bone in local space.
  92959. * @param distToJoint Optional distance from the impostor to the joint.
  92960. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  92961. */
  92962. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  92963. var tempVec = PhysicsImpostor._tmpVecs[0];
  92964. var mesh = this.object;
  92965. if (mesh.rotationQuaternion) {
  92966. if (adjustRotation) {
  92967. var tempQuat = PhysicsImpostor._tmpQuat;
  92968. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  92969. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  92970. }
  92971. else {
  92972. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  92973. }
  92974. }
  92975. tempVec.x = 0;
  92976. tempVec.y = 0;
  92977. tempVec.z = 0;
  92978. if (jointPivot) {
  92979. tempVec.x = jointPivot.x;
  92980. tempVec.y = jointPivot.y;
  92981. tempVec.z = jointPivot.z;
  92982. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  92983. if (distToJoint === undefined || distToJoint === null) {
  92984. distToJoint = jointPivot.length();
  92985. }
  92986. tempVec.x *= distToJoint;
  92987. tempVec.y *= distToJoint;
  92988. tempVec.z *= distToJoint;
  92989. }
  92990. if (bone.getParent()) {
  92991. tempVec.addInPlace(mesh.getAbsolutePosition());
  92992. bone.setAbsolutePosition(tempVec, boneMesh);
  92993. }
  92994. else {
  92995. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  92996. boneMesh.position.x -= tempVec.x;
  92997. boneMesh.position.y -= tempVec.y;
  92998. boneMesh.position.z -= tempVec.z;
  92999. }
  93000. };
  93001. /**
  93002. * Sync impostor to a bone
  93003. * @param bone The bone that the impostor will be synced to.
  93004. * @param boneMesh The mesh that the bone is influencing.
  93005. * @param jointPivot The pivot of the joint / bone in local space.
  93006. * @param distToJoint Optional distance from the impostor to the joint.
  93007. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93008. * @param boneAxis Optional vector3 axis the bone is aligned with
  93009. */
  93010. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  93011. var mesh = this.object;
  93012. if (mesh.rotationQuaternion) {
  93013. if (adjustRotation) {
  93014. var tempQuat = PhysicsImpostor._tmpQuat;
  93015. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  93016. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  93017. }
  93018. else {
  93019. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  93020. }
  93021. }
  93022. var pos = PhysicsImpostor._tmpVecs[0];
  93023. var boneDir = PhysicsImpostor._tmpVecs[1];
  93024. if (!boneAxis) {
  93025. boneAxis = PhysicsImpostor._tmpVecs[2];
  93026. boneAxis.x = 0;
  93027. boneAxis.y = 1;
  93028. boneAxis.z = 0;
  93029. }
  93030. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  93031. bone.getAbsolutePositionToRef(boneMesh, pos);
  93032. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  93033. distToJoint = jointPivot.length();
  93034. }
  93035. if (distToJoint !== undefined && distToJoint !== null) {
  93036. pos.x += boneDir.x * distToJoint;
  93037. pos.y += boneDir.y * distToJoint;
  93038. pos.z += boneDir.z * distToJoint;
  93039. }
  93040. mesh.setAbsolutePosition(pos);
  93041. };
  93042. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  93043. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  93044. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93045. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  93046. //Impostor types
  93047. PhysicsImpostor.NoImpostor = 0;
  93048. PhysicsImpostor.SphereImpostor = 1;
  93049. PhysicsImpostor.BoxImpostor = 2;
  93050. PhysicsImpostor.PlaneImpostor = 3;
  93051. PhysicsImpostor.MeshImpostor = 4;
  93052. PhysicsImpostor.CylinderImpostor = 7;
  93053. PhysicsImpostor.ParticleImpostor = 8;
  93054. PhysicsImpostor.HeightmapImpostor = 9;
  93055. return PhysicsImpostor;
  93056. }());
  93057. BABYLON.PhysicsImpostor = PhysicsImpostor;
  93058. })(BABYLON || (BABYLON = {}));
  93059. //# sourceMappingURL=babylon.physicsImpostor.js.map
  93060. var BABYLON;
  93061. (function (BABYLON) {
  93062. /**
  93063. * Class used to control physics engine
  93064. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93065. */
  93066. var PhysicsEngine = /** @class */ (function () {
  93067. /**
  93068. * Creates a new Physics Engine
  93069. * @param gravity defines the gravity vector used by the simulation
  93070. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  93071. */
  93072. function PhysicsEngine(gravity, _physicsPlugin) {
  93073. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  93074. this._physicsPlugin = _physicsPlugin;
  93075. this._impostors = [];
  93076. this._joints = [];
  93077. if (!this._physicsPlugin.isSupported()) {
  93078. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  93079. + "Please make sure it is included.");
  93080. }
  93081. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  93082. this.setGravity(gravity);
  93083. this.setTimeStep();
  93084. }
  93085. /**
  93086. * Sets the gravity vector used by the simulation
  93087. * @param gravity defines the gravity vector to use
  93088. */
  93089. PhysicsEngine.prototype.setGravity = function (gravity) {
  93090. this.gravity = gravity;
  93091. this._physicsPlugin.setGravity(this.gravity);
  93092. };
  93093. /**
  93094. * Set the time step of the physics engine.
  93095. * Default is 1/60.
  93096. * To slow it down, enter 1/600 for example.
  93097. * To speed it up, 1/30
  93098. * @param newTimeStep defines the new timestep to apply to this world.
  93099. */
  93100. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  93101. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  93102. this._physicsPlugin.setTimeStep(newTimeStep);
  93103. };
  93104. /**
  93105. * Get the time step of the physics engine.
  93106. * @returns the current time step
  93107. */
  93108. PhysicsEngine.prototype.getTimeStep = function () {
  93109. return this._physicsPlugin.getTimeStep();
  93110. };
  93111. /**
  93112. * Release all resources
  93113. */
  93114. PhysicsEngine.prototype.dispose = function () {
  93115. this._impostors.forEach(function (impostor) {
  93116. impostor.dispose();
  93117. });
  93118. this._physicsPlugin.dispose();
  93119. };
  93120. /**
  93121. * Gets the name of the current physics plugin
  93122. * @returns the name of the plugin
  93123. */
  93124. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  93125. return this._physicsPlugin.name;
  93126. };
  93127. /**
  93128. * Adding a new impostor for the impostor tracking.
  93129. * This will be done by the impostor itself.
  93130. * @param impostor the impostor to add
  93131. */
  93132. PhysicsEngine.prototype.addImpostor = function (impostor) {
  93133. impostor.uniqueId = this._impostors.push(impostor);
  93134. //if no parent, generate the body
  93135. if (!impostor.parent) {
  93136. this._physicsPlugin.generatePhysicsBody(impostor);
  93137. }
  93138. };
  93139. /**
  93140. * Remove an impostor from the engine.
  93141. * This impostor and its mesh will not longer be updated by the physics engine.
  93142. * @param impostor the impostor to remove
  93143. */
  93144. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  93145. var index = this._impostors.indexOf(impostor);
  93146. if (index > -1) {
  93147. var removed = this._impostors.splice(index, 1);
  93148. //Is it needed?
  93149. if (removed.length) {
  93150. //this will also remove it from the world.
  93151. removed[0].physicsBody = null;
  93152. }
  93153. }
  93154. };
  93155. /**
  93156. * Add a joint to the physics engine
  93157. * @param mainImpostor defines the main impostor to which the joint is added.
  93158. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  93159. * @param joint defines the joint that will connect both impostors.
  93160. */
  93161. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  93162. var impostorJoint = {
  93163. mainImpostor: mainImpostor,
  93164. connectedImpostor: connectedImpostor,
  93165. joint: joint
  93166. };
  93167. joint.physicsPlugin = this._physicsPlugin;
  93168. this._joints.push(impostorJoint);
  93169. this._physicsPlugin.generateJoint(impostorJoint);
  93170. };
  93171. /**
  93172. * Removes a joint from the simulation
  93173. * @param mainImpostor defines the impostor used with the joint
  93174. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  93175. * @param joint defines the joint to remove
  93176. */
  93177. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  93178. var matchingJoints = this._joints.filter(function (impostorJoint) {
  93179. return (impostorJoint.connectedImpostor === connectedImpostor
  93180. && impostorJoint.joint === joint
  93181. && impostorJoint.mainImpostor === mainImpostor);
  93182. });
  93183. if (matchingJoints.length) {
  93184. this._physicsPlugin.removeJoint(matchingJoints[0]);
  93185. //TODO remove it from the list as well
  93186. }
  93187. };
  93188. /**
  93189. * Called by the scene. No need to call it.
  93190. * @param delta defines the timespam between frames
  93191. */
  93192. PhysicsEngine.prototype._step = function (delta) {
  93193. var _this = this;
  93194. //check if any mesh has no body / requires an update
  93195. this._impostors.forEach(function (impostor) {
  93196. if (impostor.isBodyInitRequired()) {
  93197. _this._physicsPlugin.generatePhysicsBody(impostor);
  93198. }
  93199. });
  93200. if (delta > 0.1) {
  93201. delta = 0.1;
  93202. }
  93203. else if (delta <= 0) {
  93204. delta = 1.0 / 60.0;
  93205. }
  93206. this._physicsPlugin.executeStep(delta, this._impostors);
  93207. };
  93208. /**
  93209. * Gets the current plugin used to run the simulation
  93210. * @returns current plugin
  93211. */
  93212. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  93213. return this._physicsPlugin;
  93214. };
  93215. /**
  93216. * Gets the list of physic impostors
  93217. * @returns an array of PhysicsImpostor
  93218. */
  93219. PhysicsEngine.prototype.getImpostors = function () {
  93220. return this._impostors;
  93221. };
  93222. /**
  93223. * Gets the impostor for a physics enabled object
  93224. * @param object defines the object impersonated by the impostor
  93225. * @returns the PhysicsImpostor or null if not found
  93226. */
  93227. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  93228. for (var i = 0; i < this._impostors.length; ++i) {
  93229. if (this._impostors[i].object === object) {
  93230. return this._impostors[i];
  93231. }
  93232. }
  93233. return null;
  93234. };
  93235. /**
  93236. * Gets the impostor for a physics body object
  93237. * @param body defines physics body used by the impostor
  93238. * @returns the PhysicsImpostor or null if not found
  93239. */
  93240. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  93241. for (var i = 0; i < this._impostors.length; ++i) {
  93242. if (this._impostors[i].physicsBody === body) {
  93243. return this._impostors[i];
  93244. }
  93245. }
  93246. return null;
  93247. };
  93248. /**
  93249. * Global value used to control the smallest number supported by the simulation
  93250. */
  93251. PhysicsEngine.Epsilon = 0.001;
  93252. return PhysicsEngine;
  93253. }());
  93254. BABYLON.PhysicsEngine = PhysicsEngine;
  93255. })(BABYLON || (BABYLON = {}));
  93256. //# sourceMappingURL=babylon.physicsEngine.js.map
  93257. var BABYLON;
  93258. (function (BABYLON) {
  93259. var PhysicsHelper = /** @class */ (function () {
  93260. function PhysicsHelper(scene) {
  93261. this._scene = scene;
  93262. this._physicsEngine = this._scene.getPhysicsEngine();
  93263. if (!this._physicsEngine) {
  93264. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  93265. }
  93266. }
  93267. /**
  93268. * @param {Vector3} origin the origin of the explosion
  93269. * @param {number} radius the explosion radius
  93270. * @param {number} strength the explosion strength
  93271. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  93272. */
  93273. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  93274. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93275. if (!this._physicsEngine) {
  93276. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  93277. return null;
  93278. }
  93279. var impostors = this._physicsEngine.getImpostors();
  93280. if (impostors.length === 0) {
  93281. return null;
  93282. }
  93283. var event = new PhysicsRadialExplosionEvent(this._scene);
  93284. impostors.forEach(function (impostor) {
  93285. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  93286. if (!impostorForceAndContactPoint) {
  93287. return;
  93288. }
  93289. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93290. });
  93291. event.dispose(false);
  93292. return event;
  93293. };
  93294. /**
  93295. * @param {Vector3} origin the origin of the explosion
  93296. * @param {number} radius the explosion radius
  93297. * @param {number} strength the explosion strength
  93298. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  93299. */
  93300. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  93301. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93302. if (!this._physicsEngine) {
  93303. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93304. return null;
  93305. }
  93306. var impostors = this._physicsEngine.getImpostors();
  93307. if (impostors.length === 0) {
  93308. return null;
  93309. }
  93310. var event = new PhysicsRadialExplosionEvent(this._scene);
  93311. impostors.forEach(function (impostor) {
  93312. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  93313. if (!impostorForceAndContactPoint) {
  93314. return;
  93315. }
  93316. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93317. });
  93318. event.dispose(false);
  93319. return event;
  93320. };
  93321. /**
  93322. * @param {Vector3} origin the origin of the explosion
  93323. * @param {number} radius the explosion radius
  93324. * @param {number} strength the explosion strength
  93325. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  93326. */
  93327. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  93328. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93329. if (!this._physicsEngine) {
  93330. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93331. return null;
  93332. }
  93333. var impostors = this._physicsEngine.getImpostors();
  93334. if (impostors.length === 0) {
  93335. return null;
  93336. }
  93337. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  93338. event.dispose(false);
  93339. return event;
  93340. };
  93341. /**
  93342. * @param {Vector3} origin the origin of the updraft
  93343. * @param {number} radius the radius of the updraft
  93344. * @param {number} strength the strength of the updraft
  93345. * @param {number} height the height of the updraft
  93346. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  93347. */
  93348. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  93349. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  93350. if (!this._physicsEngine) {
  93351. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93352. return null;
  93353. }
  93354. if (this._physicsEngine.getImpostors().length === 0) {
  93355. return null;
  93356. }
  93357. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  93358. event.dispose(false);
  93359. return event;
  93360. };
  93361. /**
  93362. * @param {Vector3} origin the of the vortex
  93363. * @param {number} radius the radius of the vortex
  93364. * @param {number} strength the strength of the vortex
  93365. * @param {number} height the height of the vortex
  93366. */
  93367. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  93368. if (!this._physicsEngine) {
  93369. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93370. return null;
  93371. }
  93372. if (this._physicsEngine.getImpostors().length === 0) {
  93373. return null;
  93374. }
  93375. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  93376. event.dispose(false);
  93377. return event;
  93378. };
  93379. return PhysicsHelper;
  93380. }());
  93381. BABYLON.PhysicsHelper = PhysicsHelper;
  93382. /***** Radial explosion *****/
  93383. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  93384. function PhysicsRadialExplosionEvent(scene) {
  93385. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  93386. this._rays = [];
  93387. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  93388. this._scene = scene;
  93389. }
  93390. /**
  93391. * Returns the data related to the radial explosion event (sphere & rays).
  93392. * @returns {PhysicsRadialExplosionEventData}
  93393. */
  93394. PhysicsRadialExplosionEvent.prototype.getData = function () {
  93395. this._dataFetched = true;
  93396. return {
  93397. sphere: this._sphere,
  93398. rays: this._rays,
  93399. };
  93400. };
  93401. /**
  93402. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  93403. * @param impostor
  93404. * @param {Vector3} origin the origin of the explosion
  93405. * @param {number} radius the explosion radius
  93406. * @param {number} strength the explosion strength
  93407. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  93408. * @returns {Nullable<PhysicsForceAndContactPoint>}
  93409. */
  93410. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  93411. if (impostor.mass === 0) {
  93412. return null;
  93413. }
  93414. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  93415. return null;
  93416. }
  93417. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  93418. return null;
  93419. }
  93420. var impostorObjectCenter = impostor.getObjectCenter();
  93421. var direction = impostorObjectCenter.subtract(origin);
  93422. var ray = new BABYLON.Ray(origin, direction, radius);
  93423. this._rays.push(ray);
  93424. var hit = ray.intersectsMesh(impostor.object);
  93425. var contactPoint = hit.pickedPoint;
  93426. if (!contactPoint) {
  93427. return null;
  93428. }
  93429. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  93430. if (distanceFromOrigin > radius) {
  93431. return null;
  93432. }
  93433. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  93434. ? strength
  93435. : strength * (1 - (distanceFromOrigin / radius));
  93436. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  93437. return { force: force, contactPoint: contactPoint };
  93438. };
  93439. /**
  93440. * Disposes the sphere.
  93441. * @param {bolean} force
  93442. */
  93443. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  93444. var _this = this;
  93445. if (force === void 0) { force = true; }
  93446. if (force) {
  93447. this._sphere.dispose();
  93448. }
  93449. else {
  93450. setTimeout(function () {
  93451. if (!_this._dataFetched) {
  93452. _this._sphere.dispose();
  93453. }
  93454. }, 0);
  93455. }
  93456. };
  93457. /*** Helpers ***/
  93458. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  93459. if (!this._sphere) {
  93460. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  93461. this._sphere.isVisible = false;
  93462. }
  93463. };
  93464. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  93465. var impostorObject = impostor.object;
  93466. this._prepareSphere();
  93467. this._sphere.position = origin;
  93468. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  93469. this._sphere._updateBoundingInfo();
  93470. this._sphere.computeWorldMatrix(true);
  93471. return this._sphere.intersectsMesh(impostorObject, true);
  93472. };
  93473. return PhysicsRadialExplosionEvent;
  93474. }());
  93475. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  93476. /***** Gravitational Field *****/
  93477. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  93478. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  93479. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93480. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  93481. this._physicsHelper = physicsHelper;
  93482. this._scene = scene;
  93483. this._origin = origin;
  93484. this._radius = radius;
  93485. this._strength = strength;
  93486. this._falloff = falloff;
  93487. this._tickCallback = this._tick.bind(this);
  93488. }
  93489. /**
  93490. * Returns the data related to the gravitational field event (sphere).
  93491. * @returns {PhysicsGravitationalFieldEventData}
  93492. */
  93493. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  93494. this._dataFetched = true;
  93495. return {
  93496. sphere: this._sphere,
  93497. };
  93498. };
  93499. /**
  93500. * Enables the gravitational field.
  93501. */
  93502. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  93503. this._tickCallback.call(this);
  93504. this._scene.registerBeforeRender(this._tickCallback);
  93505. };
  93506. /**
  93507. * Disables the gravitational field.
  93508. */
  93509. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  93510. this._scene.unregisterBeforeRender(this._tickCallback);
  93511. };
  93512. /**
  93513. * Disposes the sphere.
  93514. * @param {bolean} force
  93515. */
  93516. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  93517. var _this = this;
  93518. if (force === void 0) { force = true; }
  93519. if (force) {
  93520. this._sphere.dispose();
  93521. }
  93522. else {
  93523. setTimeout(function () {
  93524. if (!_this._dataFetched) {
  93525. _this._sphere.dispose();
  93526. }
  93527. }, 0);
  93528. }
  93529. };
  93530. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  93531. // Since the params won't change, we fetch the event only once
  93532. if (this._sphere) {
  93533. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  93534. }
  93535. else {
  93536. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  93537. if (radialExplosionEvent) {
  93538. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  93539. }
  93540. }
  93541. };
  93542. return PhysicsGravitationalFieldEvent;
  93543. }());
  93544. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  93545. /***** Updraft *****/
  93546. var PhysicsUpdraftEvent = /** @class */ (function () {
  93547. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  93548. this._scene = _scene;
  93549. this._origin = _origin;
  93550. this._radius = _radius;
  93551. this._strength = _strength;
  93552. this._height = _height;
  93553. this._updraftMode = _updraftMode;
  93554. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  93555. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  93556. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  93557. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  93558. this._physicsEngine = this._scene.getPhysicsEngine();
  93559. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  93560. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  93561. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  93562. this._originDirection = this._origin.subtract(this._originTop).normalize();
  93563. }
  93564. this._tickCallback = this._tick.bind(this);
  93565. }
  93566. /**
  93567. * Returns the data related to the updraft event (cylinder).
  93568. * @returns {PhysicsUpdraftEventData}
  93569. */
  93570. PhysicsUpdraftEvent.prototype.getData = function () {
  93571. this._dataFetched = true;
  93572. return {
  93573. cylinder: this._cylinder,
  93574. };
  93575. };
  93576. /**
  93577. * Enables the updraft.
  93578. */
  93579. PhysicsUpdraftEvent.prototype.enable = function () {
  93580. this._tickCallback.call(this);
  93581. this._scene.registerBeforeRender(this._tickCallback);
  93582. };
  93583. /**
  93584. * Disables the cortex.
  93585. */
  93586. PhysicsUpdraftEvent.prototype.disable = function () {
  93587. this._scene.unregisterBeforeRender(this._tickCallback);
  93588. };
  93589. /**
  93590. * Disposes the sphere.
  93591. * @param {bolean} force
  93592. */
  93593. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  93594. var _this = this;
  93595. if (force === void 0) { force = true; }
  93596. if (force) {
  93597. this._cylinder.dispose();
  93598. }
  93599. else {
  93600. setTimeout(function () {
  93601. if (!_this._dataFetched) {
  93602. _this._cylinder.dispose();
  93603. }
  93604. }, 0);
  93605. }
  93606. };
  93607. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  93608. if (impostor.mass === 0) {
  93609. return null;
  93610. }
  93611. if (!this._intersectsWithCylinder(impostor)) {
  93612. return null;
  93613. }
  93614. var impostorObjectCenter = impostor.getObjectCenter();
  93615. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  93616. var direction = this._originDirection;
  93617. }
  93618. else {
  93619. var direction = impostorObjectCenter.subtract(this._originTop);
  93620. }
  93621. var multiplier = this._strength * -1;
  93622. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  93623. return { force: force, contactPoint: impostorObjectCenter };
  93624. };
  93625. PhysicsUpdraftEvent.prototype._tick = function () {
  93626. var _this = this;
  93627. this._physicsEngine.getImpostors().forEach(function (impostor) {
  93628. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  93629. if (!impostorForceAndContactPoint) {
  93630. return;
  93631. }
  93632. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93633. });
  93634. };
  93635. /*** Helpers ***/
  93636. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  93637. if (!this._cylinder) {
  93638. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  93639. height: this._height,
  93640. diameter: this._radius * 2,
  93641. }, this._scene);
  93642. this._cylinder.isVisible = false;
  93643. }
  93644. };
  93645. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  93646. var impostorObject = impostor.object;
  93647. this._prepareCylinder();
  93648. this._cylinder.position = this._cylinderPosition;
  93649. return this._cylinder.intersectsMesh(impostorObject, true);
  93650. };
  93651. return PhysicsUpdraftEvent;
  93652. }());
  93653. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  93654. /***** Vortex *****/
  93655. var PhysicsVortexEvent = /** @class */ (function () {
  93656. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  93657. this._scene = _scene;
  93658. this._origin = _origin;
  93659. this._radius = _radius;
  93660. this._strength = _strength;
  93661. this._height = _height;
  93662. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  93663. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  93664. this._updraftMultiplier = 0.02;
  93665. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  93666. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  93667. this._physicsEngine = this._scene.getPhysicsEngine();
  93668. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  93669. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  93670. this._tickCallback = this._tick.bind(this);
  93671. }
  93672. /**
  93673. * Returns the data related to the vortex event (cylinder).
  93674. * @returns {PhysicsVortexEventData}
  93675. */
  93676. PhysicsVortexEvent.prototype.getData = function () {
  93677. this._dataFetched = true;
  93678. return {
  93679. cylinder: this._cylinder,
  93680. };
  93681. };
  93682. /**
  93683. * Enables the vortex.
  93684. */
  93685. PhysicsVortexEvent.prototype.enable = function () {
  93686. this._tickCallback.call(this);
  93687. this._scene.registerBeforeRender(this._tickCallback);
  93688. };
  93689. /**
  93690. * Disables the cortex.
  93691. */
  93692. PhysicsVortexEvent.prototype.disable = function () {
  93693. this._scene.unregisterBeforeRender(this._tickCallback);
  93694. };
  93695. /**
  93696. * Disposes the sphere.
  93697. * @param {bolean} force
  93698. */
  93699. PhysicsVortexEvent.prototype.dispose = function (force) {
  93700. var _this = this;
  93701. if (force === void 0) { force = true; }
  93702. if (force) {
  93703. this._cylinder.dispose();
  93704. }
  93705. else {
  93706. setTimeout(function () {
  93707. if (!_this._dataFetched) {
  93708. _this._cylinder.dispose();
  93709. }
  93710. }, 0);
  93711. }
  93712. };
  93713. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  93714. if (impostor.mass === 0) {
  93715. return null;
  93716. }
  93717. if (!this._intersectsWithCylinder(impostor)) {
  93718. return null;
  93719. }
  93720. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  93721. return null;
  93722. }
  93723. var impostorObjectCenter = impostor.getObjectCenter();
  93724. 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)
  93725. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  93726. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  93727. var hit = ray.intersectsMesh(impostor.object);
  93728. var contactPoint = hit.pickedPoint;
  93729. if (!contactPoint) {
  93730. return null;
  93731. }
  93732. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  93733. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  93734. var directionToOrigin = contactPoint.normalize();
  93735. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  93736. directionToOrigin = directionToOrigin.negate();
  93737. }
  93738. // TODO: find a more physically based solution
  93739. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  93740. var forceX = directionToOrigin.x * this._strength / 8;
  93741. var forceY = directionToOrigin.y * this._updraftMultiplier;
  93742. var forceZ = directionToOrigin.z * this._strength / 8;
  93743. }
  93744. else {
  93745. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  93746. var forceY = this._originTop.y * this._updraftMultiplier;
  93747. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  93748. }
  93749. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  93750. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  93751. return { force: force, contactPoint: impostorObjectCenter };
  93752. };
  93753. PhysicsVortexEvent.prototype._tick = function () {
  93754. var _this = this;
  93755. this._physicsEngine.getImpostors().forEach(function (impostor) {
  93756. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  93757. if (!impostorForceAndContactPoint) {
  93758. return;
  93759. }
  93760. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93761. });
  93762. };
  93763. /*** Helpers ***/
  93764. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  93765. if (!this._cylinder) {
  93766. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  93767. height: this._height,
  93768. diameter: this._radius * 2,
  93769. }, this._scene);
  93770. this._cylinder.isVisible = false;
  93771. }
  93772. };
  93773. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  93774. var impostorObject = impostor.object;
  93775. this._prepareCylinder();
  93776. this._cylinder.position = this._cylinderPosition;
  93777. return this._cylinder.intersectsMesh(impostorObject, true);
  93778. };
  93779. return PhysicsVortexEvent;
  93780. }());
  93781. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  93782. /***** Enums *****/
  93783. /**
  93784. * The strenght of the force in correspondence to the distance of the affected object
  93785. */
  93786. var PhysicsRadialImpulseFalloff;
  93787. (function (PhysicsRadialImpulseFalloff) {
  93788. /** Defines that impulse is constant in strength across it's whole radius */
  93789. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  93790. /** DEfines that impulse gets weaker if it's further from the origin */
  93791. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  93792. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  93793. /**
  93794. * The strenght of the force in correspondence to the distance of the affected object
  93795. */
  93796. var PhysicsUpdraftMode;
  93797. (function (PhysicsUpdraftMode) {
  93798. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  93799. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  93800. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  93801. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  93802. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  93803. })(BABYLON || (BABYLON = {}));
  93804. //# sourceMappingURL=babylon.physicsHelper.js.map
  93805. var BABYLON;
  93806. (function (BABYLON) {
  93807. /** @hidden */
  93808. var CannonJSPlugin = /** @class */ (function () {
  93809. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  93810. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  93811. if (iterations === void 0) { iterations = 10; }
  93812. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  93813. this.name = "CannonJSPlugin";
  93814. this._physicsMaterials = new Array();
  93815. this._fixedTimeStep = 1 / 60;
  93816. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  93817. this.BJSCANNON = CANNON;
  93818. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  93819. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  93820. this._tmpPosition = BABYLON.Vector3.Zero();
  93821. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  93822. this._tmpUnityRotation = new BABYLON.Quaternion();
  93823. if (!this.isSupported()) {
  93824. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  93825. return;
  93826. }
  93827. this._extendNamespace();
  93828. this.world = new this.BJSCANNON.World();
  93829. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  93830. this.world.solver.iterations = iterations;
  93831. }
  93832. CannonJSPlugin.prototype.setGravity = function (gravity) {
  93833. this.world.gravity.copy(gravity);
  93834. };
  93835. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  93836. this._fixedTimeStep = timeStep;
  93837. };
  93838. CannonJSPlugin.prototype.getTimeStep = function () {
  93839. return this._fixedTimeStep;
  93840. };
  93841. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  93842. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  93843. };
  93844. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93845. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93846. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93847. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  93848. };
  93849. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93850. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93851. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93852. impostor.physicsBody.applyForce(impulse, worldPoint);
  93853. };
  93854. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93855. //parent-child relationship. Does this impostor has a parent impostor?
  93856. if (impostor.parent) {
  93857. if (impostor.physicsBody) {
  93858. this.removePhysicsBody(impostor);
  93859. //TODO is that needed?
  93860. impostor.forceUpdate();
  93861. }
  93862. return;
  93863. }
  93864. //should a new body be created for this impostor?
  93865. if (impostor.isBodyInitRequired()) {
  93866. var shape = this._createShape(impostor);
  93867. //unregister events, if body is being changed
  93868. var oldBody = impostor.physicsBody;
  93869. if (oldBody) {
  93870. this.removePhysicsBody(impostor);
  93871. }
  93872. //create the body and material
  93873. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  93874. var bodyCreationObject = {
  93875. mass: impostor.getParam("mass"),
  93876. material: material
  93877. };
  93878. // A simple extend, in case native options were used.
  93879. var nativeOptions = impostor.getParam("nativeOptions");
  93880. for (var key in nativeOptions) {
  93881. if (nativeOptions.hasOwnProperty(key)) {
  93882. bodyCreationObject[key] = nativeOptions[key];
  93883. }
  93884. }
  93885. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  93886. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  93887. this.world.addEventListener("preStep", impostor.beforeStep);
  93888. this.world.addEventListener("postStep", impostor.afterStep);
  93889. impostor.physicsBody.addShape(shape);
  93890. this.world.add(impostor.physicsBody);
  93891. //try to keep the body moving in the right direction by taking old properties.
  93892. //Should be tested!
  93893. if (oldBody) {
  93894. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  93895. impostor.physicsBody[param].copy(oldBody[param]);
  93896. });
  93897. }
  93898. this._processChildMeshes(impostor);
  93899. }
  93900. //now update the body's transformation
  93901. this._updatePhysicsBodyTransformation(impostor);
  93902. };
  93903. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  93904. var _this = this;
  93905. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  93906. var currentRotation = mainImpostor.object.rotationQuaternion;
  93907. if (meshChildren.length) {
  93908. var processMesh = function (localPosition, mesh) {
  93909. if (!currentRotation || !mesh.rotationQuaternion) {
  93910. return;
  93911. }
  93912. var childImpostor = mesh.getPhysicsImpostor();
  93913. if (childImpostor) {
  93914. var parent = childImpostor.parent;
  93915. if (parent !== mainImpostor) {
  93916. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  93917. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  93918. if (childImpostor.physicsBody) {
  93919. _this.removePhysicsBody(childImpostor);
  93920. childImpostor.physicsBody = null;
  93921. }
  93922. childImpostor.parent = mainImpostor;
  93923. childImpostor.resetUpdateFlags();
  93924. 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));
  93925. //Add the mass of the children.
  93926. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  93927. }
  93928. }
  93929. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  93930. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  93931. };
  93932. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  93933. }
  93934. };
  93935. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93936. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  93937. this.world.removeEventListener("preStep", impostor.beforeStep);
  93938. this.world.removeEventListener("postStep", impostor.afterStep);
  93939. this.world.remove(impostor.physicsBody);
  93940. };
  93941. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93942. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93943. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93944. if (!mainBody || !connectedBody) {
  93945. return;
  93946. }
  93947. var constraint;
  93948. var jointData = impostorJoint.joint.jointData;
  93949. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  93950. var constraintData = {
  93951. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  93952. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  93953. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  93954. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  93955. maxForce: jointData.nativeParams.maxForce,
  93956. collideConnected: !!jointData.collision
  93957. };
  93958. switch (impostorJoint.joint.type) {
  93959. case BABYLON.PhysicsJoint.HingeJoint:
  93960. case BABYLON.PhysicsJoint.Hinge2Joint:
  93961. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  93962. break;
  93963. case BABYLON.PhysicsJoint.DistanceJoint:
  93964. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  93965. break;
  93966. case BABYLON.PhysicsJoint.SpringJoint:
  93967. var springData = jointData;
  93968. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  93969. restLength: springData.length,
  93970. stiffness: springData.stiffness,
  93971. damping: springData.damping,
  93972. localAnchorA: constraintData.pivotA,
  93973. localAnchorB: constraintData.pivotB
  93974. });
  93975. break;
  93976. case BABYLON.PhysicsJoint.LockJoint:
  93977. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  93978. break;
  93979. case BABYLON.PhysicsJoint.PointToPointJoint:
  93980. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93981. default:
  93982. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  93983. break;
  93984. }
  93985. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  93986. constraint.collideConnected = !!jointData.collision;
  93987. impostorJoint.joint.physicsJoint = constraint;
  93988. //don't add spring as constraint, as it is not one.
  93989. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  93990. this.world.addConstraint(constraint);
  93991. }
  93992. else {
  93993. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  93994. constraint.applyForce();
  93995. };
  93996. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  93997. }
  93998. };
  93999. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94000. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94001. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  94002. }
  94003. else {
  94004. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94005. }
  94006. };
  94007. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  94008. var index;
  94009. var mat;
  94010. for (index = 0; index < this._physicsMaterials.length; index++) {
  94011. mat = this._physicsMaterials[index];
  94012. if (mat.friction === friction && mat.restitution === restitution) {
  94013. return mat;
  94014. }
  94015. }
  94016. var currentMat = new this.BJSCANNON.Material(name);
  94017. currentMat.friction = friction;
  94018. currentMat.restitution = restitution;
  94019. this._physicsMaterials.push(currentMat);
  94020. return currentMat;
  94021. };
  94022. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  94023. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  94024. };
  94025. CannonJSPlugin.prototype._createShape = function (impostor) {
  94026. var object = impostor.object;
  94027. var returnValue;
  94028. var extendSize = impostor.getObjectExtendSize();
  94029. switch (impostor.type) {
  94030. case BABYLON.PhysicsImpostor.SphereImpostor:
  94031. var radiusX = extendSize.x;
  94032. var radiusY = extendSize.y;
  94033. var radiusZ = extendSize.z;
  94034. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  94035. break;
  94036. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  94037. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94038. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  94039. break;
  94040. case BABYLON.PhysicsImpostor.BoxImpostor:
  94041. var box = extendSize.scale(0.5);
  94042. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  94043. break;
  94044. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94045. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  94046. returnValue = new this.BJSCANNON.Plane();
  94047. break;
  94048. case BABYLON.PhysicsImpostor.MeshImpostor:
  94049. // should transform the vertex data to world coordinates!!
  94050. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  94051. var rawFaces = object.getIndices ? object.getIndices() : [];
  94052. if (!rawVerts)
  94053. return;
  94054. // get only scale! so the object could transform correctly.
  94055. var oldPosition = object.position.clone();
  94056. var oldRotation = object.rotation && object.rotation.clone();
  94057. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  94058. object.position.copyFromFloats(0, 0, 0);
  94059. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94060. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94061. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94062. var transform = object.computeWorldMatrix(true);
  94063. // convert rawVerts to object space
  94064. var temp = new Array();
  94065. var index;
  94066. for (index = 0; index < rawVerts.length; index += 3) {
  94067. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  94068. }
  94069. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  94070. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  94071. //now set back the transformation!
  94072. object.position.copyFrom(oldPosition);
  94073. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  94074. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  94075. break;
  94076. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  94077. var oldPosition2 = object.position.clone();
  94078. var oldRotation2 = object.rotation && object.rotation.clone();
  94079. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  94080. object.position.copyFromFloats(0, 0, 0);
  94081. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94082. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94083. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94084. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  94085. returnValue = this._createHeightmap(object);
  94086. object.position.copyFrom(oldPosition2);
  94087. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  94088. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  94089. object.computeWorldMatrix(true);
  94090. break;
  94091. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94092. returnValue = new this.BJSCANNON.Particle();
  94093. break;
  94094. }
  94095. return returnValue;
  94096. };
  94097. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  94098. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94099. var transform = object.computeWorldMatrix(true);
  94100. // convert rawVerts to object space
  94101. var temp = new Array();
  94102. var index;
  94103. for (index = 0; index < pos.length; index += 3) {
  94104. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  94105. }
  94106. pos = temp;
  94107. var matrix = new Array();
  94108. //For now pointDepth will not be used and will be automatically calculated.
  94109. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  94110. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  94111. var boundingInfo = object.getBoundingInfo();
  94112. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  94113. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  94114. var elementSize = dim * 2 / arraySize;
  94115. for (var i = 0; i < pos.length; i = i + 3) {
  94116. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  94117. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  94118. var y = -pos[i + 2] + minY;
  94119. if (!matrix[x]) {
  94120. matrix[x] = [];
  94121. }
  94122. if (!matrix[x][z]) {
  94123. matrix[x][z] = y;
  94124. }
  94125. matrix[x][z] = Math.max(y, matrix[x][z]);
  94126. }
  94127. for (var x = 0; x <= arraySize; ++x) {
  94128. if (!matrix[x]) {
  94129. var loc = 1;
  94130. while (!matrix[(x + loc) % arraySize]) {
  94131. loc++;
  94132. }
  94133. matrix[x] = matrix[(x + loc) % arraySize].slice();
  94134. //console.log("missing x", x);
  94135. }
  94136. for (var z = 0; z <= arraySize; ++z) {
  94137. if (!matrix[x][z]) {
  94138. var loc = 1;
  94139. var newValue;
  94140. while (newValue === undefined) {
  94141. newValue = matrix[x][(z + loc++) % arraySize];
  94142. }
  94143. matrix[x][z] = newValue;
  94144. }
  94145. }
  94146. }
  94147. var shape = new this.BJSCANNON.Heightfield(matrix, {
  94148. elementSize: elementSize
  94149. });
  94150. //For future reference, needed for body transformation
  94151. shape.minY = minY;
  94152. return shape;
  94153. };
  94154. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  94155. var object = impostor.object;
  94156. //make sure it is updated...
  94157. object.computeWorldMatrix && object.computeWorldMatrix(true);
  94158. // The delta between the mesh position and the mesh bounding box center
  94159. var bInfo = object.getBoundingInfo();
  94160. if (!bInfo)
  94161. return;
  94162. var center = impostor.getObjectCenter();
  94163. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  94164. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  94165. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  94166. this._tmpPosition.copyFrom(center);
  94167. var quaternion = object.rotationQuaternion;
  94168. if (!quaternion) {
  94169. return;
  94170. }
  94171. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  94172. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  94173. //-90 DEG in X, precalculated
  94174. quaternion = quaternion.multiply(this._minus90X);
  94175. //Invert! (Precalculated, 90 deg in X)
  94176. //No need to clone. this will never change.
  94177. impostor.setDeltaRotation(this._plus90X);
  94178. }
  94179. //If it is a heightfield, if should be centered.
  94180. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  94181. var mesh = object;
  94182. var boundingInfo = mesh.getBoundingInfo();
  94183. //calculate the correct body position:
  94184. var rotationQuaternion = mesh.rotationQuaternion;
  94185. mesh.rotationQuaternion = this._tmpUnityRotation;
  94186. mesh.computeWorldMatrix(true);
  94187. //get original center with no rotation
  94188. var c = center.clone();
  94189. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  94190. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  94191. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  94192. mesh.setPreTransformMatrix(p);
  94193. mesh.computeWorldMatrix(true);
  94194. //calculate the translation
  94195. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  94196. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  94197. //add it inverted to the delta
  94198. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  94199. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  94200. //rotation is back
  94201. mesh.rotationQuaternion = rotationQuaternion;
  94202. mesh.setPreTransformMatrix(oldPivot);
  94203. mesh.computeWorldMatrix(true);
  94204. }
  94205. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  94206. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  94207. //this._tmpPosition.copyFrom(object.position);
  94208. }
  94209. impostor.setDeltaPosition(this._tmpDeltaPosition);
  94210. //Now update the impostor object
  94211. impostor.physicsBody.position.copy(this._tmpPosition);
  94212. impostor.physicsBody.quaternion.copy(quaternion);
  94213. };
  94214. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  94215. impostor.object.position.copyFrom(impostor.physicsBody.position);
  94216. if (impostor.object.rotationQuaternion) {
  94217. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  94218. }
  94219. };
  94220. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  94221. impostor.physicsBody.position.copy(newPosition);
  94222. impostor.physicsBody.quaternion.copy(newRotation);
  94223. };
  94224. CannonJSPlugin.prototype.isSupported = function () {
  94225. return this.BJSCANNON !== undefined;
  94226. };
  94227. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  94228. impostor.physicsBody.velocity.copy(velocity);
  94229. };
  94230. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  94231. impostor.physicsBody.angularVelocity.copy(velocity);
  94232. };
  94233. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  94234. var v = impostor.physicsBody.velocity;
  94235. if (!v) {
  94236. return null;
  94237. }
  94238. return new BABYLON.Vector3(v.x, v.y, v.z);
  94239. };
  94240. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  94241. var v = impostor.physicsBody.angularVelocity;
  94242. if (!v) {
  94243. return null;
  94244. }
  94245. return new BABYLON.Vector3(v.x, v.y, v.z);
  94246. };
  94247. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  94248. impostor.physicsBody.mass = mass;
  94249. impostor.physicsBody.updateMassProperties();
  94250. };
  94251. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  94252. return impostor.physicsBody.mass;
  94253. };
  94254. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  94255. return impostor.physicsBody.material.friction;
  94256. };
  94257. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  94258. impostor.physicsBody.material.friction = friction;
  94259. };
  94260. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  94261. return impostor.physicsBody.material.restitution;
  94262. };
  94263. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  94264. impostor.physicsBody.material.restitution = restitution;
  94265. };
  94266. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  94267. impostor.physicsBody.sleep();
  94268. };
  94269. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  94270. impostor.physicsBody.wakeUp();
  94271. };
  94272. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  94273. joint.physicsJoint.distance = maxDistance;
  94274. };
  94275. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  94276. // if (!motorIndex) {
  94277. // joint.physicsJoint.enableMotor();
  94278. // }
  94279. // }
  94280. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  94281. // if (!motorIndex) {
  94282. // joint.physicsJoint.disableMotor();
  94283. // }
  94284. // }
  94285. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  94286. if (!motorIndex) {
  94287. joint.physicsJoint.enableMotor();
  94288. joint.physicsJoint.setMotorSpeed(speed);
  94289. if (maxForce) {
  94290. this.setLimit(joint, maxForce);
  94291. }
  94292. }
  94293. };
  94294. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  94295. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  94296. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  94297. };
  94298. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  94299. var body = impostor.physicsBody;
  94300. mesh.position.x = body.position.x;
  94301. mesh.position.y = body.position.y;
  94302. mesh.position.z = body.position.z;
  94303. if (mesh.rotationQuaternion) {
  94304. mesh.rotationQuaternion.x = body.quaternion.x;
  94305. mesh.rotationQuaternion.y = body.quaternion.y;
  94306. mesh.rotationQuaternion.z = body.quaternion.z;
  94307. mesh.rotationQuaternion.w = body.quaternion.w;
  94308. }
  94309. };
  94310. CannonJSPlugin.prototype.getRadius = function (impostor) {
  94311. var shape = impostor.physicsBody.shapes[0];
  94312. return shape.boundingSphereRadius;
  94313. };
  94314. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  94315. var shape = impostor.physicsBody.shapes[0];
  94316. result.x = shape.halfExtents.x * 2;
  94317. result.y = shape.halfExtents.y * 2;
  94318. result.z = shape.halfExtents.z * 2;
  94319. };
  94320. CannonJSPlugin.prototype.dispose = function () {
  94321. };
  94322. CannonJSPlugin.prototype._extendNamespace = function () {
  94323. //this will force cannon to execute at least one step when using interpolation
  94324. var step_tmp1 = new this.BJSCANNON.Vec3();
  94325. var Engine = this.BJSCANNON;
  94326. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  94327. maxSubSteps = maxSubSteps || 10;
  94328. timeSinceLastCalled = timeSinceLastCalled || 0;
  94329. if (timeSinceLastCalled === 0) {
  94330. this.internalStep(dt);
  94331. this.time += dt;
  94332. }
  94333. else {
  94334. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  94335. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  94336. var t0 = performance.now();
  94337. for (var i = 0; i !== internalSteps; i++) {
  94338. this.internalStep(dt);
  94339. if (performance.now() - t0 > dt * 1000) {
  94340. break;
  94341. }
  94342. }
  94343. this.time += timeSinceLastCalled;
  94344. var h = this.time % dt;
  94345. var h_div_dt = h / dt;
  94346. var interpvelo = step_tmp1;
  94347. var bodies = this.bodies;
  94348. for (var j = 0; j !== bodies.length; j++) {
  94349. var b = bodies[j];
  94350. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  94351. b.position.vsub(b.previousPosition, interpvelo);
  94352. interpvelo.scale(h_div_dt, interpvelo);
  94353. b.position.vadd(interpvelo, b.interpolatedPosition);
  94354. }
  94355. else {
  94356. b.interpolatedPosition.copy(b.position);
  94357. b.interpolatedQuaternion.copy(b.quaternion);
  94358. }
  94359. }
  94360. }
  94361. };
  94362. };
  94363. return CannonJSPlugin;
  94364. }());
  94365. BABYLON.CannonJSPlugin = CannonJSPlugin;
  94366. })(BABYLON || (BABYLON = {}));
  94367. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  94368. var BABYLON;
  94369. (function (BABYLON) {
  94370. /** @hidden */
  94371. var OimoJSPlugin = /** @class */ (function () {
  94372. function OimoJSPlugin(iterations) {
  94373. this.name = "OimoJSPlugin";
  94374. this._tmpImpostorsArray = [];
  94375. this._tmpPositionVector = BABYLON.Vector3.Zero();
  94376. this.BJSOIMO = OIMO;
  94377. this.world = new this.BJSOIMO.World({
  94378. iterations: iterations
  94379. });
  94380. this.world.clear();
  94381. }
  94382. OimoJSPlugin.prototype.setGravity = function (gravity) {
  94383. this.world.gravity.copy(gravity);
  94384. };
  94385. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  94386. this.world.timeStep = timeStep;
  94387. };
  94388. OimoJSPlugin.prototype.getTimeStep = function () {
  94389. return this.world.timeStep;
  94390. };
  94391. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  94392. var _this = this;
  94393. impostors.forEach(function (impostor) {
  94394. impostor.beforeStep();
  94395. });
  94396. this.world.step();
  94397. impostors.forEach(function (impostor) {
  94398. impostor.afterStep();
  94399. //update the ordered impostors array
  94400. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  94401. });
  94402. //check for collisions
  94403. var contact = this.world.contacts;
  94404. while (contact !== null) {
  94405. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  94406. contact = contact.next;
  94407. continue;
  94408. }
  94409. //is this body colliding with any other? get the impostor
  94410. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  94411. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  94412. if (!mainImpostor || !collidingImpostor) {
  94413. contact = contact.next;
  94414. continue;
  94415. }
  94416. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  94417. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  94418. contact = contact.next;
  94419. }
  94420. };
  94421. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  94422. var mass = impostor.physicsBody.mass;
  94423. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  94424. };
  94425. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  94426. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  94427. this.applyImpulse(impostor, force, contactPoint);
  94428. };
  94429. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  94430. var _this = this;
  94431. //parent-child relationship. Does this impostor has a parent impostor?
  94432. if (impostor.parent) {
  94433. if (impostor.physicsBody) {
  94434. this.removePhysicsBody(impostor);
  94435. //TODO is that needed?
  94436. impostor.forceUpdate();
  94437. }
  94438. return;
  94439. }
  94440. if (impostor.isBodyInitRequired()) {
  94441. var bodyConfig = {
  94442. name: impostor.uniqueId,
  94443. //Oimo must have mass, also for static objects.
  94444. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  94445. size: [],
  94446. type: [],
  94447. pos: [],
  94448. posShape: [],
  94449. rot: [],
  94450. rotShape: [],
  94451. move: impostor.getParam("mass") !== 0,
  94452. density: impostor.getParam("mass"),
  94453. friction: impostor.getParam("friction"),
  94454. restitution: impostor.getParam("restitution"),
  94455. //Supporting older versions of Oimo
  94456. world: this.world
  94457. };
  94458. var impostors = [impostor];
  94459. var addToArray = function (parent) {
  94460. if (!parent.getChildMeshes)
  94461. return;
  94462. parent.getChildMeshes().forEach(function (m) {
  94463. if (m.physicsImpostor) {
  94464. impostors.push(m.physicsImpostor);
  94465. //m.physicsImpostor._init();
  94466. }
  94467. });
  94468. };
  94469. addToArray(impostor.object);
  94470. var checkWithEpsilon_1 = function (value) {
  94471. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  94472. };
  94473. var globalQuaternion_1 = new BABYLON.Quaternion();
  94474. impostors.forEach(function (i) {
  94475. if (!i.object.rotationQuaternion) {
  94476. return;
  94477. }
  94478. //get the correct bounding box
  94479. var oldQuaternion = i.object.rotationQuaternion;
  94480. globalQuaternion_1 = oldQuaternion.clone();
  94481. var rot = oldQuaternion.toEulerAngles();
  94482. var extendSize = i.getObjectExtendSize();
  94483. var radToDeg = 57.295779513082320876;
  94484. if (i === impostor) {
  94485. var center = impostor.getObjectCenter();
  94486. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  94487. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  94488. //Can also use Array.prototype.push.apply
  94489. bodyConfig.pos.push(center.x);
  94490. bodyConfig.pos.push(center.y);
  94491. bodyConfig.pos.push(center.z);
  94492. bodyConfig.posShape.push(0, 0, 0);
  94493. //tmp solution
  94494. bodyConfig.rot.push(0);
  94495. bodyConfig.rot.push(0);
  94496. bodyConfig.rot.push(0);
  94497. bodyConfig.rotShape.push(0, 0, 0);
  94498. }
  94499. else {
  94500. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  94501. bodyConfig.posShape.push(localPosition.x);
  94502. bodyConfig.posShape.push(localPosition.y);
  94503. bodyConfig.posShape.push(localPosition.z);
  94504. bodyConfig.pos.push(0, 0, 0);
  94505. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  94506. bodyConfig.rot.push(0);
  94507. bodyConfig.rot.push(0);
  94508. bodyConfig.rot.push(0);
  94509. bodyConfig.rotShape.push(rot.x * radToDeg);
  94510. bodyConfig.rotShape.push(rot.y * radToDeg);
  94511. bodyConfig.rotShape.push(rot.z * radToDeg);
  94512. }
  94513. // register mesh
  94514. switch (i.type) {
  94515. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94516. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  94517. case BABYLON.PhysicsImpostor.SphereImpostor:
  94518. var radiusX = extendSize.x;
  94519. var radiusY = extendSize.y;
  94520. var radiusZ = extendSize.z;
  94521. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  94522. bodyConfig.type.push('sphere');
  94523. //due to the way oimo works with compounds, add 3 times
  94524. bodyConfig.size.push(size);
  94525. bodyConfig.size.push(size);
  94526. bodyConfig.size.push(size);
  94527. break;
  94528. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94529. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  94530. var sizeY = checkWithEpsilon_1(extendSize.y);
  94531. bodyConfig.type.push('cylinder');
  94532. bodyConfig.size.push(sizeX);
  94533. bodyConfig.size.push(sizeY);
  94534. //due to the way oimo works with compounds, add one more value.
  94535. bodyConfig.size.push(sizeY);
  94536. break;
  94537. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94538. case BABYLON.PhysicsImpostor.BoxImpostor:
  94539. default:
  94540. var sizeX = checkWithEpsilon_1(extendSize.x);
  94541. var sizeY = checkWithEpsilon_1(extendSize.y);
  94542. var sizeZ = checkWithEpsilon_1(extendSize.z);
  94543. bodyConfig.type.push('box');
  94544. //if (i === impostor) {
  94545. bodyConfig.size.push(sizeX);
  94546. bodyConfig.size.push(sizeY);
  94547. bodyConfig.size.push(sizeZ);
  94548. //} else {
  94549. // bodyConfig.size.push(0,0,0);
  94550. //}
  94551. break;
  94552. }
  94553. //actually not needed, but hey...
  94554. i.object.rotationQuaternion = oldQuaternion;
  94555. });
  94556. impostor.physicsBody = this.world.add(bodyConfig);
  94557. // set the quaternion, ignoring the previously defined (euler) rotation
  94558. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  94559. // update with delta 0, so the body will reveive the new rotation.
  94560. impostor.physicsBody.updatePosition(0);
  94561. }
  94562. else {
  94563. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  94564. }
  94565. impostor.setDeltaPosition(this._tmpPositionVector);
  94566. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  94567. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  94568. };
  94569. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  94570. //impostor.physicsBody.dispose();
  94571. //Same as : (older oimo versions)
  94572. this.world.removeRigidBody(impostor.physicsBody);
  94573. };
  94574. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  94575. var mainBody = impostorJoint.mainImpostor.physicsBody;
  94576. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  94577. if (!mainBody || !connectedBody) {
  94578. return;
  94579. }
  94580. var jointData = impostorJoint.joint.jointData;
  94581. var options = jointData.nativeParams || {};
  94582. var type;
  94583. var nativeJointData = {
  94584. body1: mainBody,
  94585. body2: connectedBody,
  94586. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  94587. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  94588. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  94589. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  94590. min: options.min,
  94591. max: options.max,
  94592. collision: options.collision || jointData.collision,
  94593. spring: options.spring,
  94594. //supporting older version of Oimo
  94595. world: this.world
  94596. };
  94597. switch (impostorJoint.joint.type) {
  94598. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  94599. type = "jointBall";
  94600. break;
  94601. case BABYLON.PhysicsJoint.SpringJoint:
  94602. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  94603. var springData = jointData;
  94604. nativeJointData.min = springData.length || nativeJointData.min;
  94605. //Max should also be set, just make sure it is at least min
  94606. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  94607. case BABYLON.PhysicsJoint.DistanceJoint:
  94608. type = "jointDistance";
  94609. nativeJointData.max = jointData.maxDistance;
  94610. break;
  94611. case BABYLON.PhysicsJoint.PrismaticJoint:
  94612. type = "jointPrisme";
  94613. break;
  94614. case BABYLON.PhysicsJoint.SliderJoint:
  94615. type = "jointSlide";
  94616. break;
  94617. case BABYLON.PhysicsJoint.WheelJoint:
  94618. type = "jointWheel";
  94619. break;
  94620. case BABYLON.PhysicsJoint.HingeJoint:
  94621. default:
  94622. type = "jointHinge";
  94623. break;
  94624. }
  94625. nativeJointData.type = type;
  94626. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  94627. };
  94628. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94629. //Bug in Oimo prevents us from disposing a joint in the playground
  94630. //joint.joint.physicsJoint.dispose();
  94631. //So we will bruteforce it!
  94632. try {
  94633. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  94634. }
  94635. catch (e) {
  94636. BABYLON.Tools.Warn(e);
  94637. }
  94638. };
  94639. OimoJSPlugin.prototype.isSupported = function () {
  94640. return this.BJSOIMO !== undefined;
  94641. };
  94642. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  94643. if (!impostor.physicsBody.sleeping) {
  94644. //TODO check that
  94645. /*if (impostor.physicsBody.shapes.next) {
  94646. var parentShape = this._getLastShape(impostor.physicsBody);
  94647. impostor.object.position.copyFrom(parentShape.position);
  94648. console.log(parentShape.position);
  94649. } else {*/
  94650. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  94651. //}
  94652. if (impostor.object.rotationQuaternion) {
  94653. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  94654. }
  94655. }
  94656. };
  94657. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  94658. var body = impostor.physicsBody;
  94659. body.position.copy(newPosition);
  94660. body.orientation.copy(newRotation);
  94661. body.syncShapes();
  94662. body.awake();
  94663. };
  94664. /*private _getLastShape(body: any): any {
  94665. var lastShape = body.shapes;
  94666. while (lastShape.next) {
  94667. lastShape = lastShape.next;
  94668. }
  94669. return lastShape;
  94670. }*/
  94671. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  94672. impostor.physicsBody.linearVelocity.copy(velocity);
  94673. };
  94674. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  94675. impostor.physicsBody.angularVelocity.copy(velocity);
  94676. };
  94677. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  94678. var v = impostor.physicsBody.linearVelocity;
  94679. if (!v) {
  94680. return null;
  94681. }
  94682. return new BABYLON.Vector3(v.x, v.y, v.z);
  94683. };
  94684. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  94685. var v = impostor.physicsBody.angularVelocity;
  94686. if (!v) {
  94687. return null;
  94688. }
  94689. return new BABYLON.Vector3(v.x, v.y, v.z);
  94690. };
  94691. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  94692. var staticBody = mass === 0;
  94693. //this will actually set the body's density and not its mass.
  94694. //But this is how oimo treats the mass variable.
  94695. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  94696. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  94697. };
  94698. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  94699. return impostor.physicsBody.shapes.density;
  94700. };
  94701. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  94702. return impostor.physicsBody.shapes.friction;
  94703. };
  94704. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  94705. impostor.physicsBody.shapes.friction = friction;
  94706. };
  94707. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  94708. return impostor.physicsBody.shapes.restitution;
  94709. };
  94710. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  94711. impostor.physicsBody.shapes.restitution = restitution;
  94712. };
  94713. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  94714. impostor.physicsBody.sleep();
  94715. };
  94716. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  94717. impostor.physicsBody.awake();
  94718. };
  94719. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  94720. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  94721. if (minDistance !== void 0) {
  94722. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  94723. }
  94724. };
  94725. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  94726. //TODO separate rotational and transational motors.
  94727. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  94728. if (motor) {
  94729. motor.setMotor(speed, maxForce);
  94730. }
  94731. };
  94732. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  94733. //TODO separate rotational and transational motors.
  94734. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  94735. if (motor) {
  94736. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  94737. }
  94738. };
  94739. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  94740. var body = impostor.physicsBody;
  94741. mesh.position.x = body.position.x;
  94742. mesh.position.y = body.position.y;
  94743. mesh.position.z = body.position.z;
  94744. if (mesh.rotationQuaternion) {
  94745. mesh.rotationQuaternion.x = body.orientation.x;
  94746. mesh.rotationQuaternion.y = body.orientation.y;
  94747. mesh.rotationQuaternion.z = body.orientation.z;
  94748. mesh.rotationQuaternion.w = body.orientation.s;
  94749. }
  94750. };
  94751. OimoJSPlugin.prototype.getRadius = function (impostor) {
  94752. return impostor.physicsBody.shapes.radius;
  94753. };
  94754. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  94755. var shape = impostor.physicsBody.shapes;
  94756. result.x = shape.halfWidth * 2;
  94757. result.y = shape.halfHeight * 2;
  94758. result.z = shape.halfDepth * 2;
  94759. };
  94760. OimoJSPlugin.prototype.dispose = function () {
  94761. this.world.clear();
  94762. };
  94763. return OimoJSPlugin;
  94764. }());
  94765. BABYLON.OimoJSPlugin = OimoJSPlugin;
  94766. })(BABYLON || (BABYLON = {}));
  94767. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  94768. var BABYLON;
  94769. (function (BABYLON) {
  94770. /**
  94771. * Gets the current physics engine
  94772. * @returns a IPhysicsEngine or null if none attached
  94773. */
  94774. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  94775. return this._physicsEngine;
  94776. };
  94777. /**
  94778. * Enables physics to the current scene
  94779. * @param gravity defines the scene's gravity for the physics engine
  94780. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  94781. * @return a boolean indicating if the physics engine was initialized
  94782. */
  94783. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  94784. if (gravity === void 0) { gravity = null; }
  94785. if (this._physicsEngine) {
  94786. return true;
  94787. }
  94788. // Register the component to the scene
  94789. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  94790. if (!component) {
  94791. component = new PhysicsEngineSceneComponent(this);
  94792. this._addComponent(component);
  94793. }
  94794. try {
  94795. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  94796. return true;
  94797. }
  94798. catch (e) {
  94799. BABYLON.Tools.Error(e.message);
  94800. return false;
  94801. }
  94802. };
  94803. /**
  94804. * Disables and disposes the physics engine associated with the scene
  94805. */
  94806. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  94807. if (!this._physicsEngine) {
  94808. return;
  94809. }
  94810. this._physicsEngine.dispose();
  94811. this._physicsEngine = null;
  94812. };
  94813. /**
  94814. * Gets a boolean indicating if there is an active physics engine
  94815. * @returns a boolean indicating if there is an active physics engine
  94816. */
  94817. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  94818. return this._physicsEngine !== undefined;
  94819. };
  94820. /**
  94821. * Deletes a physics compound impostor
  94822. * @param compound defines the compound to delete
  94823. */
  94824. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  94825. var mesh = compound.parts[0].mesh;
  94826. if (mesh.physicsImpostor) {
  94827. mesh.physicsImpostor.dispose( /*true*/);
  94828. mesh.physicsImpostor = null;
  94829. }
  94830. };
  94831. /** @hidden */
  94832. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  94833. if (this._physicsEngine) {
  94834. this.onBeforePhysicsObservable.notifyObservers(this);
  94835. this._physicsEngine._step(step / 1000);
  94836. this.onAfterPhysicsObservable.notifyObservers(this);
  94837. }
  94838. };
  94839. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  94840. get: function () {
  94841. return this._physicsImpostor;
  94842. },
  94843. set: function (value) {
  94844. var _this = this;
  94845. if (this._physicsImpostor === value) {
  94846. return;
  94847. }
  94848. if (this._disposePhysicsObserver) {
  94849. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  94850. }
  94851. this._physicsImpostor = value;
  94852. if (value) {
  94853. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  94854. // Physics
  94855. if (_this.physicsImpostor) {
  94856. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  94857. _this.physicsImpostor = null;
  94858. }
  94859. });
  94860. }
  94861. },
  94862. enumerable: true,
  94863. configurable: true
  94864. });
  94865. /**
  94866. * Gets the current physics impostor
  94867. * @see http://doc.babylonjs.com/features/physics_engine
  94868. * @returns a physics impostor or null
  94869. */
  94870. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  94871. return this.physicsImpostor;
  94872. };
  94873. /**
  94874. * Apply a physic impulse to the mesh
  94875. * @param force defines the force to apply
  94876. * @param contactPoint defines where to apply the force
  94877. * @returns the current mesh
  94878. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  94879. */
  94880. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  94881. if (!this.physicsImpostor) {
  94882. return this;
  94883. }
  94884. this.physicsImpostor.applyImpulse(force, contactPoint);
  94885. return this;
  94886. };
  94887. /**
  94888. * Creates a physic joint between two meshes
  94889. * @param otherMesh defines the other mesh to use
  94890. * @param pivot1 defines the pivot to use on this mesh
  94891. * @param pivot2 defines the pivot to use on the other mesh
  94892. * @param options defines additional options (can be plugin dependent)
  94893. * @returns the current mesh
  94894. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  94895. */
  94896. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  94897. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  94898. return this;
  94899. }
  94900. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  94901. mainPivot: pivot1,
  94902. connectedPivot: pivot2,
  94903. nativeParams: options
  94904. });
  94905. return this;
  94906. };
  94907. /**
  94908. * Defines the physics engine scene component responsible to manage a physics engine
  94909. */
  94910. var PhysicsEngineSceneComponent = /** @class */ (function () {
  94911. /**
  94912. * Creates a new instance of the component for the given scene
  94913. * @param scene Defines the scene to register the component in
  94914. */
  94915. function PhysicsEngineSceneComponent(scene) {
  94916. var _this = this;
  94917. /**
  94918. * The component name helpful to identify the component in the list of scene components.
  94919. */
  94920. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  94921. this.scene = scene;
  94922. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  94923. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  94924. // Replace the function used to get the deterministic frame time
  94925. this.scene.getDeterministicFrameTime = function () {
  94926. if (_this.scene._physicsEngine) {
  94927. return _this.scene._physicsEngine.getTimeStep() * 1000;
  94928. }
  94929. return 1000.0 / 60.0;
  94930. };
  94931. }
  94932. /**
  94933. * Registers the component in a given scene
  94934. */
  94935. PhysicsEngineSceneComponent.prototype.register = function () {
  94936. };
  94937. /**
  94938. * Rebuilds the elements related to this component in case of
  94939. * context lost for instance.
  94940. */
  94941. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  94942. // Nothing to do for this component
  94943. };
  94944. /**
  94945. * Disposes the component and the associated ressources
  94946. */
  94947. PhysicsEngineSceneComponent.prototype.dispose = function () {
  94948. this.scene.onBeforePhysicsObservable.clear();
  94949. this.scene.onAfterPhysicsObservable.clear();
  94950. if (this.scene._physicsEngine) {
  94951. this.scene.disablePhysicsEngine();
  94952. }
  94953. };
  94954. return PhysicsEngineSceneComponent;
  94955. }());
  94956. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  94957. })(BABYLON || (BABYLON = {}));
  94958. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  94959. var BABYLON;
  94960. (function (BABYLON) {
  94961. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  94962. // All values and structures referenced from:
  94963. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  94964. var DDS_MAGIC = 0x20534444;
  94965. var
  94966. //DDSD_CAPS = 0x1,
  94967. //DDSD_HEIGHT = 0x2,
  94968. //DDSD_WIDTH = 0x4,
  94969. //DDSD_PITCH = 0x8,
  94970. //DDSD_PIXELFORMAT = 0x1000,
  94971. DDSD_MIPMAPCOUNT = 0x20000;
  94972. //DDSD_LINEARSIZE = 0x80000,
  94973. //DDSD_DEPTH = 0x800000;
  94974. // var DDSCAPS_COMPLEX = 0x8,
  94975. // DDSCAPS_MIPMAP = 0x400000,
  94976. // DDSCAPS_TEXTURE = 0x1000;
  94977. var DDSCAPS2_CUBEMAP = 0x200;
  94978. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  94979. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  94980. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  94981. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  94982. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  94983. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  94984. // DDSCAPS2_VOLUME = 0x200000;
  94985. var
  94986. //DDPF_ALPHAPIXELS = 0x1,
  94987. //DDPF_ALPHA = 0x2,
  94988. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  94989. //DDPF_YUV = 0x200,
  94990. DDPF_LUMINANCE = 0x20000;
  94991. function FourCCToInt32(value) {
  94992. return value.charCodeAt(0) +
  94993. (value.charCodeAt(1) << 8) +
  94994. (value.charCodeAt(2) << 16) +
  94995. (value.charCodeAt(3) << 24);
  94996. }
  94997. function Int32ToFourCC(value) {
  94998. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  94999. }
  95000. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  95001. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  95002. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  95003. var FOURCC_DX10 = FourCCToInt32("DX10");
  95004. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  95005. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  95006. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  95007. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  95008. var headerLengthInt = 31; // The header length in 32 bit ints
  95009. // Offsets into the header array
  95010. var off_magic = 0;
  95011. var off_size = 1;
  95012. var off_flags = 2;
  95013. var off_height = 3;
  95014. var off_width = 4;
  95015. var off_mipmapCount = 7;
  95016. var off_pfFlags = 20;
  95017. var off_pfFourCC = 21;
  95018. var off_RGBbpp = 22;
  95019. var off_RMask = 23;
  95020. var off_GMask = 24;
  95021. var off_BMask = 25;
  95022. var off_AMask = 26;
  95023. // var off_caps1 = 27;
  95024. var off_caps2 = 28;
  95025. // var off_caps3 = 29;
  95026. // var off_caps4 = 30;
  95027. var off_dxgiFormat = 32;
  95028. ;
  95029. /**
  95030. * Class used to provide DDS decompression tools
  95031. */
  95032. var DDSTools = /** @class */ (function () {
  95033. function DDSTools() {
  95034. }
  95035. /**
  95036. * Gets DDS information from an array buffer
  95037. * @param arrayBuffer defines the array buffer to read data from
  95038. * @returns the DDS information
  95039. */
  95040. DDSTools.GetDDSInfo = function (arrayBuffer) {
  95041. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95042. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  95043. var mipmapCount = 1;
  95044. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  95045. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95046. }
  95047. var fourCC = header[off_pfFourCC];
  95048. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  95049. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95050. switch (fourCC) {
  95051. case FOURCC_D3DFMT_R16G16B16A16F:
  95052. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95053. break;
  95054. case FOURCC_D3DFMT_R32G32B32A32F:
  95055. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95056. break;
  95057. case FOURCC_DX10:
  95058. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  95059. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95060. break;
  95061. }
  95062. }
  95063. return {
  95064. width: header[off_width],
  95065. height: header[off_height],
  95066. mipmapCount: mipmapCount,
  95067. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  95068. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  95069. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  95070. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  95071. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  95072. dxgiFormat: dxgiFormat,
  95073. textureType: textureType
  95074. };
  95075. };
  95076. DDSTools._ToHalfFloat = function (value) {
  95077. if (!DDSTools._FloatView) {
  95078. DDSTools._FloatView = new Float32Array(1);
  95079. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  95080. }
  95081. DDSTools._FloatView[0] = value;
  95082. var x = DDSTools._Int32View[0];
  95083. var bits = (x >> 16) & 0x8000; /* Get the sign */
  95084. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  95085. var e = (x >> 23) & 0xff; /* Using int is faster here */
  95086. /* If zero, or denormal, or exponent underflows too much for a denormal
  95087. * half, return signed zero. */
  95088. if (e < 103) {
  95089. return bits;
  95090. }
  95091. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  95092. if (e > 142) {
  95093. bits |= 0x7c00;
  95094. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  95095. * not Inf, so make sure we set one mantissa bit too. */
  95096. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  95097. return bits;
  95098. }
  95099. /* If exponent underflows but not too much, return a denormal */
  95100. if (e < 113) {
  95101. m |= 0x0800;
  95102. /* Extra rounding may overflow and set mantissa to 0 and exponent
  95103. * to 1, which is OK. */
  95104. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  95105. return bits;
  95106. }
  95107. bits |= ((e - 112) << 10) | (m >> 1);
  95108. bits += m & 1;
  95109. return bits;
  95110. };
  95111. DDSTools._FromHalfFloat = function (value) {
  95112. var s = (value & 0x8000) >> 15;
  95113. var e = (value & 0x7C00) >> 10;
  95114. var f = value & 0x03FF;
  95115. if (e === 0) {
  95116. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  95117. }
  95118. else if (e == 0x1F) {
  95119. return f ? NaN : ((s ? -1 : 1) * Infinity);
  95120. }
  95121. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  95122. };
  95123. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95124. var destArray = new Float32Array(dataLength);
  95125. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95126. var index = 0;
  95127. for (var y = 0; y < height; y++) {
  95128. for (var x = 0; x < width; x++) {
  95129. var srcPos = (x + y * width) * 4;
  95130. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  95131. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  95132. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  95133. if (DDSTools.StoreLODInAlphaChannel) {
  95134. destArray[index + 3] = lod;
  95135. }
  95136. else {
  95137. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  95138. }
  95139. index += 4;
  95140. }
  95141. }
  95142. return destArray;
  95143. };
  95144. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95145. if (DDSTools.StoreLODInAlphaChannel) {
  95146. var destArray = new Uint16Array(dataLength);
  95147. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95148. var index = 0;
  95149. for (var y = 0; y < height; y++) {
  95150. for (var x = 0; x < width; x++) {
  95151. var srcPos = (x + y * width) * 4;
  95152. destArray[index] = srcData[srcPos];
  95153. destArray[index + 1] = srcData[srcPos + 1];
  95154. destArray[index + 2] = srcData[srcPos + 2];
  95155. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  95156. index += 4;
  95157. }
  95158. }
  95159. return destArray;
  95160. }
  95161. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  95162. };
  95163. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95164. if (DDSTools.StoreLODInAlphaChannel) {
  95165. var destArray = new Float32Array(dataLength);
  95166. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95167. var index = 0;
  95168. for (var y = 0; y < height; y++) {
  95169. for (var x = 0; x < width; x++) {
  95170. var srcPos = (x + y * width) * 4;
  95171. destArray[index] = srcData[srcPos];
  95172. destArray[index + 1] = srcData[srcPos + 1];
  95173. destArray[index + 2] = srcData[srcPos + 2];
  95174. destArray[index + 3] = lod;
  95175. index += 4;
  95176. }
  95177. }
  95178. return destArray;
  95179. }
  95180. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  95181. };
  95182. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95183. var destArray = new Uint8Array(dataLength);
  95184. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95185. var index = 0;
  95186. for (var y = 0; y < height; y++) {
  95187. for (var x = 0; x < width; x++) {
  95188. var srcPos = (x + y * width) * 4;
  95189. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  95190. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  95191. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  95192. if (DDSTools.StoreLODInAlphaChannel) {
  95193. destArray[index + 3] = lod;
  95194. }
  95195. else {
  95196. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  95197. }
  95198. index += 4;
  95199. }
  95200. }
  95201. return destArray;
  95202. };
  95203. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95204. var destArray = new Uint8Array(dataLength);
  95205. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95206. var index = 0;
  95207. for (var y = 0; y < height; y++) {
  95208. for (var x = 0; x < width; x++) {
  95209. var srcPos = (x + y * width) * 4;
  95210. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  95211. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  95212. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  95213. if (DDSTools.StoreLODInAlphaChannel) {
  95214. destArray[index + 3] = lod;
  95215. }
  95216. else {
  95217. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  95218. }
  95219. index += 4;
  95220. }
  95221. }
  95222. return destArray;
  95223. };
  95224. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  95225. var byteArray = new Uint8Array(dataLength);
  95226. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  95227. var index = 0;
  95228. for (var y = 0; y < height; y++) {
  95229. for (var x = 0; x < width; x++) {
  95230. var srcPos = (x + y * width) * 4;
  95231. byteArray[index] = srcData[srcPos + rOffset];
  95232. byteArray[index + 1] = srcData[srcPos + gOffset];
  95233. byteArray[index + 2] = srcData[srcPos + bOffset];
  95234. byteArray[index + 3] = srcData[srcPos + aOffset];
  95235. index += 4;
  95236. }
  95237. }
  95238. return byteArray;
  95239. };
  95240. DDSTools._ExtractLongWordOrder = function (value) {
  95241. if (value === 0 || value === 255 || value === -16777216) {
  95242. return 0;
  95243. }
  95244. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  95245. };
  95246. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  95247. var byteArray = new Uint8Array(dataLength);
  95248. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  95249. var index = 0;
  95250. for (var y = 0; y < height; y++) {
  95251. for (var x = 0; x < width; x++) {
  95252. var srcPos = (x + y * width) * 3;
  95253. byteArray[index] = srcData[srcPos + rOffset];
  95254. byteArray[index + 1] = srcData[srcPos + gOffset];
  95255. byteArray[index + 2] = srcData[srcPos + bOffset];
  95256. index += 3;
  95257. }
  95258. }
  95259. return byteArray;
  95260. };
  95261. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  95262. var byteArray = new Uint8Array(dataLength);
  95263. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  95264. var index = 0;
  95265. for (var y = 0; y < height; y++) {
  95266. for (var x = 0; x < width; x++) {
  95267. var srcPos = (x + y * width);
  95268. byteArray[index] = srcData[srcPos];
  95269. index++;
  95270. }
  95271. }
  95272. return byteArray;
  95273. };
  95274. /**
  95275. * Uploads DDS Levels to a Babylon Texture
  95276. * @hidden
  95277. */
  95278. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  95279. if (lodIndex === void 0) { lodIndex = -1; }
  95280. var sphericalPolynomialFaces = null;
  95281. if (info.sphericalPolynomial) {
  95282. sphericalPolynomialFaces = new Array();
  95283. }
  95284. var ext = engine.getCaps().s3tc;
  95285. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95286. var fourCC, width, height, dataLength = 0, dataOffset;
  95287. var byteArray, mipmapCount, mip;
  95288. var internalCompressedFormat = 0;
  95289. var blockBytes = 1;
  95290. if (header[off_magic] !== DDS_MAGIC) {
  95291. BABYLON.Tools.Error("Invalid magic number in DDS header");
  95292. return;
  95293. }
  95294. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  95295. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  95296. return;
  95297. }
  95298. if (info.isCompressed && !ext) {
  95299. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  95300. return;
  95301. }
  95302. var bpp = header[off_RGBbpp];
  95303. dataOffset = header[off_size] + 4;
  95304. var computeFormats = false;
  95305. if (info.isFourCC) {
  95306. fourCC = header[off_pfFourCC];
  95307. switch (fourCC) {
  95308. case FOURCC_DXT1:
  95309. blockBytes = 8;
  95310. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  95311. break;
  95312. case FOURCC_DXT3:
  95313. blockBytes = 16;
  95314. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  95315. break;
  95316. case FOURCC_DXT5:
  95317. blockBytes = 16;
  95318. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  95319. break;
  95320. case FOURCC_D3DFMT_R16G16B16A16F:
  95321. computeFormats = true;
  95322. break;
  95323. case FOURCC_D3DFMT_R32G32B32A32F:
  95324. computeFormats = true;
  95325. break;
  95326. case FOURCC_DX10:
  95327. // There is an additionnal header so dataOffset need to be changed
  95328. dataOffset += 5 * 4; // 5 uints
  95329. var supported = false;
  95330. switch (info.dxgiFormat) {
  95331. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  95332. computeFormats = true;
  95333. supported = true;
  95334. break;
  95335. case DXGI_FORMAT_B8G8R8X8_UNORM:
  95336. info.isRGB = true;
  95337. info.isFourCC = false;
  95338. bpp = 32;
  95339. supported = true;
  95340. break;
  95341. }
  95342. if (supported) {
  95343. break;
  95344. }
  95345. default:
  95346. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  95347. return;
  95348. }
  95349. }
  95350. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  95351. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  95352. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  95353. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  95354. if (computeFormats) {
  95355. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  95356. }
  95357. mipmapCount = 1;
  95358. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  95359. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95360. }
  95361. for (var face = 0; face < faces; face++) {
  95362. width = header[off_width];
  95363. height = header[off_height];
  95364. for (mip = 0; mip < mipmapCount; ++mip) {
  95365. if (lodIndex === -1 || lodIndex === mip) {
  95366. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  95367. var i = (lodIndex === -1) ? mip : 0;
  95368. if (!info.isCompressed && info.isFourCC) {
  95369. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95370. dataLength = width * height * 4;
  95371. var floatArray = null;
  95372. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  95373. if (bpp === 128) {
  95374. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95375. if (sphericalPolynomialFaces && i == 0) {
  95376. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  95377. }
  95378. }
  95379. else if (bpp === 64) {
  95380. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95381. if (sphericalPolynomialFaces && i == 0) {
  95382. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  95383. }
  95384. }
  95385. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95386. }
  95387. else {
  95388. if (bpp === 128) {
  95389. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95390. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95391. if (sphericalPolynomialFaces && i == 0) {
  95392. sphericalPolynomialFaces.push(floatArray);
  95393. }
  95394. }
  95395. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  95396. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95397. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95398. if (sphericalPolynomialFaces && i == 0) {
  95399. sphericalPolynomialFaces.push(floatArray);
  95400. }
  95401. }
  95402. else { // 64
  95403. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95404. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95405. if (sphericalPolynomialFaces && i == 0) {
  95406. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  95407. }
  95408. }
  95409. }
  95410. if (floatArray) {
  95411. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  95412. }
  95413. }
  95414. else if (info.isRGB) {
  95415. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95416. if (bpp === 24) {
  95417. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  95418. dataLength = width * height * 3;
  95419. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  95420. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  95421. }
  95422. else { // 32
  95423. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95424. dataLength = width * height * 4;
  95425. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  95426. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  95427. }
  95428. }
  95429. else if (info.isLuminance) {
  95430. var unpackAlignment = engine._getUnpackAlignement();
  95431. var unpaddedRowSize = width;
  95432. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  95433. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  95434. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  95435. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  95436. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95437. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  95438. }
  95439. else {
  95440. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  95441. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  95442. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95443. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  95444. }
  95445. }
  95446. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  95447. width *= 0.5;
  95448. height *= 0.5;
  95449. width = Math.max(1.0, width);
  95450. height = Math.max(1.0, height);
  95451. }
  95452. if (currentFace !== undefined) {
  95453. // Loading a single face
  95454. break;
  95455. }
  95456. }
  95457. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  95458. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  95459. size: header[off_width],
  95460. right: sphericalPolynomialFaces[0],
  95461. left: sphericalPolynomialFaces[1],
  95462. up: sphericalPolynomialFaces[2],
  95463. down: sphericalPolynomialFaces[3],
  95464. front: sphericalPolynomialFaces[4],
  95465. back: sphericalPolynomialFaces[5],
  95466. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  95467. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  95468. gammaSpace: false,
  95469. });
  95470. }
  95471. else {
  95472. info.sphericalPolynomial = undefined;
  95473. }
  95474. };
  95475. /**
  95476. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  95477. */
  95478. DDSTools.StoreLODInAlphaChannel = false;
  95479. return DDSTools;
  95480. }());
  95481. BABYLON.DDSTools = DDSTools;
  95482. })(BABYLON || (BABYLON = {}));
  95483. //# sourceMappingURL=babylon.dds.js.map
  95484. var BABYLON;
  95485. (function (BABYLON) {
  95486. /**
  95487. * Implementation of the DDS Texture Loader.
  95488. */
  95489. var DDSTextureLoader = /** @class */ (function () {
  95490. function DDSTextureLoader() {
  95491. /**
  95492. * Defines wether the loader supports cascade loading the different faces.
  95493. */
  95494. this.supportCascades = true;
  95495. }
  95496. /**
  95497. * This returns if the loader support the current file information.
  95498. * @param extension defines the file extension of the file being loaded
  95499. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95500. * @param fallback defines the fallback internal texture if any
  95501. * @param isBase64 defines whether the texture is encoded as a base64
  95502. * @param isBuffer defines whether the texture data are stored as a buffer
  95503. * @returns true if the loader can load the specified file
  95504. */
  95505. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95506. return extension.indexOf(".dds") === 0;
  95507. };
  95508. /**
  95509. * Transform the url before loading if required.
  95510. * @param rootUrl the url of the texture
  95511. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95512. * @returns the transformed texture
  95513. */
  95514. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95515. return rootUrl;
  95516. };
  95517. /**
  95518. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95519. * @param rootUrl the url of the texture
  95520. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95521. * @returns the fallback texture
  95522. */
  95523. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95524. return null;
  95525. };
  95526. /**
  95527. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95528. * @param data contains the texture data
  95529. * @param texture defines the BabylonJS internal texture
  95530. * @param createPolynomials will be true if polynomials have been requested
  95531. * @param onLoad defines the callback to trigger once the texture is ready
  95532. * @param onError defines the callback to trigger in case of error
  95533. */
  95534. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  95535. var engine = texture.getEngine();
  95536. var info;
  95537. var loadMipmap = false;
  95538. if (Array.isArray(imgs)) {
  95539. for (var index = 0; index < imgs.length; index++) {
  95540. var data_1 = imgs[index];
  95541. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  95542. texture.width = info.width;
  95543. texture.height = info.height;
  95544. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  95545. engine._unpackFlipY(info.isCompressed);
  95546. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  95547. if (!info.isFourCC && info.mipmapCount === 1) {
  95548. engine.generateMipMapsForCubemap(texture);
  95549. }
  95550. }
  95551. }
  95552. else {
  95553. var data = imgs;
  95554. info = BABYLON.DDSTools.GetDDSInfo(data);
  95555. texture.width = info.width;
  95556. texture.height = info.height;
  95557. if (createPolynomials) {
  95558. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  95559. }
  95560. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  95561. engine._unpackFlipY(info.isCompressed);
  95562. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  95563. if (!info.isFourCC && info.mipmapCount === 1) {
  95564. engine.generateMipMapsForCubemap(texture);
  95565. }
  95566. }
  95567. engine._setCubeMapTextureParams(loadMipmap);
  95568. texture.isReady = true;
  95569. if (onLoad) {
  95570. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  95571. }
  95572. };
  95573. /**
  95574. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95575. * @param data contains the texture data
  95576. * @param texture defines the BabylonJS internal texture
  95577. * @param callback defines the method to call once ready to upload
  95578. */
  95579. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  95580. var info = BABYLON.DDSTools.GetDDSInfo(data);
  95581. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  95582. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  95583. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  95584. });
  95585. };
  95586. return DDSTextureLoader;
  95587. }());
  95588. // Register the loader.
  95589. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  95590. })(BABYLON || (BABYLON = {}));
  95591. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  95592. var BABYLON;
  95593. (function (BABYLON) {
  95594. /**
  95595. * Based on jsTGALoader - Javascript loader for TGA file
  95596. * By Vincent Thibault
  95597. * @see http://blog.robrowser.com/javascript-tga-loader.html
  95598. */
  95599. var TGATools = /** @class */ (function () {
  95600. function TGATools() {
  95601. }
  95602. /**
  95603. * Gets the header of a TGA file
  95604. * @param data defines the TGA data
  95605. * @returns the header
  95606. */
  95607. TGATools.GetTGAHeader = function (data) {
  95608. var offset = 0;
  95609. var header = {
  95610. id_length: data[offset++],
  95611. colormap_type: data[offset++],
  95612. image_type: data[offset++],
  95613. colormap_index: data[offset++] | data[offset++] << 8,
  95614. colormap_length: data[offset++] | data[offset++] << 8,
  95615. colormap_size: data[offset++],
  95616. origin: [
  95617. data[offset++] | data[offset++] << 8,
  95618. data[offset++] | data[offset++] << 8
  95619. ],
  95620. width: data[offset++] | data[offset++] << 8,
  95621. height: data[offset++] | data[offset++] << 8,
  95622. pixel_size: data[offset++],
  95623. flags: data[offset++]
  95624. };
  95625. return header;
  95626. };
  95627. /**
  95628. * Uploads TGA content to a Babylon Texture
  95629. * @hidden
  95630. */
  95631. TGATools.UploadContent = function (texture, data) {
  95632. // Not enough data to contain header ?
  95633. if (data.length < 19) {
  95634. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  95635. return;
  95636. }
  95637. // Read Header
  95638. var offset = 18;
  95639. var header = TGATools.GetTGAHeader(data);
  95640. // Assume it's a valid Targa file.
  95641. if (header.id_length + offset > data.length) {
  95642. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  95643. return;
  95644. }
  95645. // Skip not needed data
  95646. offset += header.id_length;
  95647. var use_rle = false;
  95648. var use_pal = false;
  95649. var use_grey = false;
  95650. // Get some informations.
  95651. switch (header.image_type) {
  95652. case TGATools._TYPE_RLE_INDEXED:
  95653. use_rle = true;
  95654. case TGATools._TYPE_INDEXED:
  95655. use_pal = true;
  95656. break;
  95657. case TGATools._TYPE_RLE_RGB:
  95658. use_rle = true;
  95659. case TGATools._TYPE_RGB:
  95660. // use_rgb = true;
  95661. break;
  95662. case TGATools._TYPE_RLE_GREY:
  95663. use_rle = true;
  95664. case TGATools._TYPE_GREY:
  95665. use_grey = true;
  95666. break;
  95667. }
  95668. var pixel_data;
  95669. // var numAlphaBits = header.flags & 0xf;
  95670. var pixel_size = header.pixel_size >> 3;
  95671. var pixel_total = header.width * header.height * pixel_size;
  95672. // Read palettes
  95673. var palettes;
  95674. if (use_pal) {
  95675. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  95676. }
  95677. // Read LRE
  95678. if (use_rle) {
  95679. pixel_data = new Uint8Array(pixel_total);
  95680. var c, count, i;
  95681. var localOffset = 0;
  95682. var pixels = new Uint8Array(pixel_size);
  95683. while (offset < pixel_total && localOffset < pixel_total) {
  95684. c = data[offset++];
  95685. count = (c & 0x7f) + 1;
  95686. // RLE pixels
  95687. if (c & 0x80) {
  95688. // Bind pixel tmp array
  95689. for (i = 0; i < pixel_size; ++i) {
  95690. pixels[i] = data[offset++];
  95691. }
  95692. // Copy pixel array
  95693. for (i = 0; i < count; ++i) {
  95694. pixel_data.set(pixels, localOffset + i * pixel_size);
  95695. }
  95696. localOffset += pixel_size * count;
  95697. }
  95698. // Raw pixels
  95699. else {
  95700. count *= pixel_size;
  95701. for (i = 0; i < count; ++i) {
  95702. pixel_data[localOffset + i] = data[offset++];
  95703. }
  95704. localOffset += count;
  95705. }
  95706. }
  95707. }
  95708. // RAW Pixels
  95709. else {
  95710. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  95711. }
  95712. // Load to texture
  95713. var x_start, y_start, x_step, y_step, y_end, x_end;
  95714. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  95715. default:
  95716. case TGATools._ORIGIN_UL:
  95717. x_start = 0;
  95718. x_step = 1;
  95719. x_end = header.width;
  95720. y_start = 0;
  95721. y_step = 1;
  95722. y_end = header.height;
  95723. break;
  95724. case TGATools._ORIGIN_BL:
  95725. x_start = 0;
  95726. x_step = 1;
  95727. x_end = header.width;
  95728. y_start = header.height - 1;
  95729. y_step = -1;
  95730. y_end = -1;
  95731. break;
  95732. case TGATools._ORIGIN_UR:
  95733. x_start = header.width - 1;
  95734. x_step = -1;
  95735. x_end = -1;
  95736. y_start = 0;
  95737. y_step = 1;
  95738. y_end = header.height;
  95739. break;
  95740. case TGATools._ORIGIN_BR:
  95741. x_start = header.width - 1;
  95742. x_step = -1;
  95743. x_end = -1;
  95744. y_start = header.height - 1;
  95745. y_step = -1;
  95746. y_end = -1;
  95747. break;
  95748. }
  95749. // Load the specify method
  95750. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  95751. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  95752. var engine = texture.getEngine();
  95753. engine._uploadDataToTextureDirectly(texture, imageData);
  95754. };
  95755. /** @hidden */
  95756. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95757. var image = pixel_data, colormap = palettes;
  95758. var width = header.width, height = header.height;
  95759. var color, i = 0, x, y;
  95760. var imageData = new Uint8Array(width * height * 4);
  95761. for (y = y_start; y !== y_end; y += y_step) {
  95762. for (x = x_start; x !== x_end; x += x_step, i++) {
  95763. color = image[i];
  95764. imageData[(x + width * y) * 4 + 3] = 255;
  95765. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  95766. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  95767. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  95768. }
  95769. }
  95770. return imageData;
  95771. };
  95772. /** @hidden */
  95773. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95774. var image = pixel_data;
  95775. var width = header.width, height = header.height;
  95776. var color, i = 0, x, y;
  95777. var imageData = new Uint8Array(width * height * 4);
  95778. for (y = y_start; y !== y_end; y += y_step) {
  95779. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  95780. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  95781. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  95782. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  95783. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  95784. imageData[(x + width * y) * 4 + 0] = r;
  95785. imageData[(x + width * y) * 4 + 1] = g;
  95786. imageData[(x + width * y) * 4 + 2] = b;
  95787. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  95788. }
  95789. }
  95790. return imageData;
  95791. };
  95792. /** @hidden */
  95793. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95794. var image = pixel_data;
  95795. var width = header.width, height = header.height;
  95796. var i = 0, x, y;
  95797. var imageData = new Uint8Array(width * height * 4);
  95798. for (y = y_start; y !== y_end; y += y_step) {
  95799. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  95800. imageData[(x + width * y) * 4 + 3] = 255;
  95801. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95802. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95803. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95804. }
  95805. }
  95806. return imageData;
  95807. };
  95808. /** @hidden */
  95809. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95810. var image = pixel_data;
  95811. var width = header.width, height = header.height;
  95812. var i = 0, x, y;
  95813. var imageData = new Uint8Array(width * height * 4);
  95814. for (y = y_start; y !== y_end; y += y_step) {
  95815. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  95816. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95817. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95818. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95819. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  95820. }
  95821. }
  95822. return imageData;
  95823. };
  95824. /** @hidden */
  95825. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95826. var image = pixel_data;
  95827. var width = header.width, height = header.height;
  95828. var color, i = 0, x, y;
  95829. var imageData = new Uint8Array(width * height * 4);
  95830. for (y = y_start; y !== y_end; y += y_step) {
  95831. for (x = x_start; x !== x_end; x += x_step, i++) {
  95832. color = image[i];
  95833. imageData[(x + width * y) * 4 + 0] = color;
  95834. imageData[(x + width * y) * 4 + 1] = color;
  95835. imageData[(x + width * y) * 4 + 2] = color;
  95836. imageData[(x + width * y) * 4 + 3] = 255;
  95837. }
  95838. }
  95839. return imageData;
  95840. };
  95841. /** @hidden */
  95842. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95843. var image = pixel_data;
  95844. var width = header.width, height = header.height;
  95845. var i = 0, x, y;
  95846. var imageData = new Uint8Array(width * height * 4);
  95847. for (y = y_start; y !== y_end; y += y_step) {
  95848. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  95849. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  95850. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  95851. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95852. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  95853. }
  95854. }
  95855. return imageData;
  95856. };
  95857. //private static _TYPE_NO_DATA = 0;
  95858. TGATools._TYPE_INDEXED = 1;
  95859. TGATools._TYPE_RGB = 2;
  95860. TGATools._TYPE_GREY = 3;
  95861. TGATools._TYPE_RLE_INDEXED = 9;
  95862. TGATools._TYPE_RLE_RGB = 10;
  95863. TGATools._TYPE_RLE_GREY = 11;
  95864. TGATools._ORIGIN_MASK = 0x30;
  95865. TGATools._ORIGIN_SHIFT = 0x04;
  95866. TGATools._ORIGIN_BL = 0x00;
  95867. TGATools._ORIGIN_BR = 0x01;
  95868. TGATools._ORIGIN_UL = 0x02;
  95869. TGATools._ORIGIN_UR = 0x03;
  95870. return TGATools;
  95871. }());
  95872. BABYLON.TGATools = TGATools;
  95873. })(BABYLON || (BABYLON = {}));
  95874. //# sourceMappingURL=babylon.tga.js.map
  95875. var BABYLON;
  95876. (function (BABYLON) {
  95877. /**
  95878. * Implementation of the TGA Texture Loader.
  95879. */
  95880. var TGATextureLoader = /** @class */ (function () {
  95881. function TGATextureLoader() {
  95882. /**
  95883. * Defines wether the loader supports cascade loading the different faces.
  95884. */
  95885. this.supportCascades = false;
  95886. }
  95887. /**
  95888. * This returns if the loader support the current file information.
  95889. * @param extension defines the file extension of the file being loaded
  95890. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95891. * @param fallback defines the fallback internal texture if any
  95892. * @param isBase64 defines whether the texture is encoded as a base64
  95893. * @param isBuffer defines whether the texture data are stored as a buffer
  95894. * @returns true if the loader can load the specified file
  95895. */
  95896. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95897. return extension.indexOf(".tga") === 0;
  95898. };
  95899. /**
  95900. * Transform the url before loading if required.
  95901. * @param rootUrl the url of the texture
  95902. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95903. * @returns the transformed texture
  95904. */
  95905. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95906. return rootUrl;
  95907. };
  95908. /**
  95909. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95910. * @param rootUrl the url of the texture
  95911. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95912. * @returns the fallback texture
  95913. */
  95914. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95915. return null;
  95916. };
  95917. /**
  95918. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95919. * @param data contains the texture data
  95920. * @param texture defines the BabylonJS internal texture
  95921. * @param createPolynomials will be true if polynomials have been requested
  95922. * @param onLoad defines the callback to trigger once the texture is ready
  95923. * @param onError defines the callback to trigger in case of error
  95924. */
  95925. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95926. throw ".env not supported in Cube.";
  95927. };
  95928. /**
  95929. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95930. * @param data contains the texture data
  95931. * @param texture defines the BabylonJS internal texture
  95932. * @param callback defines the method to call once ready to upload
  95933. */
  95934. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  95935. var uintData = new Uint8Array(data);
  95936. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  95937. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  95938. BABYLON.TGATools.UploadContent(texture, uintData);
  95939. });
  95940. };
  95941. return TGATextureLoader;
  95942. }());
  95943. // Register the loader.
  95944. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  95945. })(BABYLON || (BABYLON = {}));
  95946. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  95947. var BABYLON;
  95948. (function (BABYLON) {
  95949. /**
  95950. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  95951. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  95952. */
  95953. var KhronosTextureContainer = /** @class */ (function () {
  95954. /**
  95955. * Creates a new KhronosTextureContainer
  95956. * @param arrayBuffer contents of the KTX container file
  95957. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  95958. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  95959. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  95960. */
  95961. function KhronosTextureContainer(
  95962. /** contents of the KTX container file */
  95963. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  95964. this.arrayBuffer = arrayBuffer;
  95965. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  95966. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  95967. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  95968. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  95969. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  95970. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  95971. BABYLON.Tools.Error("texture missing KTX identifier");
  95972. return;
  95973. }
  95974. // load the reset of the header in native 32 bit int
  95975. var header = new Int32Array(this.arrayBuffer, 12, 13);
  95976. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  95977. var oppositeEndianess = header[0] === 0x01020304;
  95978. // read all the header elements in order they exist in the file, without modification (sans endainness)
  95979. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  95980. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  95981. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  95982. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  95983. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  95984. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  95985. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  95986. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  95987. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  95988. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  95989. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  95990. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  95991. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  95992. if (this.glType !== 0) {
  95993. BABYLON.Tools.Error("only compressed formats currently supported");
  95994. return;
  95995. }
  95996. else {
  95997. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  95998. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  95999. }
  96000. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  96001. BABYLON.Tools.Error("only 2D textures currently supported");
  96002. return;
  96003. }
  96004. if (this.numberOfArrayElements !== 0) {
  96005. BABYLON.Tools.Error("texture arrays not currently supported");
  96006. return;
  96007. }
  96008. if (this.numberOfFaces !== facesExpected) {
  96009. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  96010. return;
  96011. }
  96012. // we now have a completely validated file, so could use existence of loadType as success
  96013. // would need to make this more elaborate & adjust checks above to support more than one load type
  96014. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  96015. }
  96016. //
  96017. /**
  96018. * Revert the endianness of a value.
  96019. * Not as fast hardware based, but will probably never need to use
  96020. * @param val defines the value to convert
  96021. * @returns the new value
  96022. */
  96023. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  96024. return ((val & 0xFF) << 24)
  96025. | ((val & 0xFF00) << 8)
  96026. | ((val >> 8) & 0xFF00)
  96027. | ((val >> 24) & 0xFF);
  96028. };
  96029. /**
  96030. * Uploads KTX content to a Babylon Texture.
  96031. * It is assumed that the texture has already been created & is currently bound
  96032. * @hidden
  96033. */
  96034. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  96035. switch (this.loadType) {
  96036. case KhronosTextureContainer.COMPRESSED_2D:
  96037. this._upload2DCompressedLevels(texture, loadMipmaps);
  96038. break;
  96039. case KhronosTextureContainer.TEX_2D:
  96040. case KhronosTextureContainer.COMPRESSED_3D:
  96041. case KhronosTextureContainer.TEX_3D:
  96042. }
  96043. };
  96044. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  96045. // initialize width & height for level 1
  96046. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  96047. var width = this.pixelWidth;
  96048. var height = this.pixelHeight;
  96049. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  96050. for (var level = 0; level < mipmapCount; level++) {
  96051. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  96052. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  96053. for (var face = 0; face < this.numberOfFaces; face++) {
  96054. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  96055. var engine = texture.getEngine();
  96056. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  96057. dataOffset += imageSize; // add size of the image for the next face/mipmap
  96058. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  96059. }
  96060. width = Math.max(1.0, width * 0.5);
  96061. height = Math.max(1.0, height * 0.5);
  96062. }
  96063. };
  96064. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  96065. // load types
  96066. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  96067. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  96068. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  96069. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  96070. return KhronosTextureContainer;
  96071. }());
  96072. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  96073. })(BABYLON || (BABYLON = {}));
  96074. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  96075. var BABYLON;
  96076. (function (BABYLON) {
  96077. /**
  96078. * Implementation of the KTX Texture Loader.
  96079. */
  96080. var KTXTextureLoader = /** @class */ (function () {
  96081. function KTXTextureLoader() {
  96082. /**
  96083. * Defines wether the loader supports cascade loading the different faces.
  96084. */
  96085. this.supportCascades = false;
  96086. }
  96087. /**
  96088. * This returns if the loader support the current file information.
  96089. * @param extension defines the file extension of the file being loaded
  96090. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96091. * @param fallback defines the fallback internal texture if any
  96092. * @param isBase64 defines whether the texture is encoded as a base64
  96093. * @param isBuffer defines whether the texture data are stored as a buffer
  96094. * @returns true if the loader can load the specified file
  96095. */
  96096. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96097. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  96098. return true;
  96099. }
  96100. return false;
  96101. };
  96102. /**
  96103. * Transform the url before loading if required.
  96104. * @param rootUrl the url of the texture
  96105. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96106. * @returns the transformed texture
  96107. */
  96108. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96109. var lastDot = rootUrl.lastIndexOf('.');
  96110. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  96111. };
  96112. /**
  96113. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96114. * @param rootUrl the url of the texture
  96115. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96116. * @returns the fallback texture
  96117. */
  96118. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96119. // remove the format appended to the rootUrl in the original createCubeTexture call.
  96120. var exp = new RegExp("" + textureFormatInUse + "$");
  96121. return rootUrl.replace(exp, "");
  96122. };
  96123. /**
  96124. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96125. * @param data contains the texture data
  96126. * @param texture defines the BabylonJS internal texture
  96127. * @param createPolynomials will be true if polynomials have been requested
  96128. * @param onLoad defines the callback to trigger once the texture is ready
  96129. * @param onError defines the callback to trigger in case of error
  96130. */
  96131. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96132. if (Array.isArray(data)) {
  96133. return;
  96134. }
  96135. var engine = texture.getEngine();
  96136. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  96137. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  96138. engine._unpackFlipY(true);
  96139. ktx.uploadLevels(texture, texture.generateMipMaps);
  96140. texture.width = ktx.pixelWidth;
  96141. texture.height = ktx.pixelHeight;
  96142. engine._setCubeMapTextureParams(loadMipmap);
  96143. texture.isReady = true;
  96144. };
  96145. /**
  96146. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96147. * @param data contains the texture data
  96148. * @param texture defines the BabylonJS internal texture
  96149. * @param callback defines the method to call once ready to upload
  96150. */
  96151. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  96152. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  96153. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  96154. ktx.uploadLevels(texture, texture.generateMipMaps);
  96155. });
  96156. };
  96157. return KTXTextureLoader;
  96158. }());
  96159. // Register the loader.
  96160. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  96161. })(BABYLON || (BABYLON = {}));
  96162. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  96163. var BABYLON;
  96164. (function (BABYLON) {
  96165. /**
  96166. * Sets of helpers addressing the serialization and deserialization of environment texture
  96167. * stored in a BabylonJS env file.
  96168. * Those files are usually stored as .env files.
  96169. */
  96170. var EnvironmentTextureTools = /** @class */ (function () {
  96171. function EnvironmentTextureTools() {
  96172. }
  96173. /**
  96174. * Gets the environment info from an env file.
  96175. * @param data The array buffer containing the .env bytes.
  96176. * @returns the environment file info (the json header) if successfully parsed.
  96177. */
  96178. EnvironmentTextureTools.GetEnvInfo = function (data) {
  96179. var dataView = new DataView(data);
  96180. var pos = 0;
  96181. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  96182. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  96183. BABYLON.Tools.Error('Not a babylon environment map');
  96184. return null;
  96185. }
  96186. }
  96187. // Read json manifest - collect characters up to null terminator
  96188. var manifestString = '';
  96189. var charCode = 0x00;
  96190. while ((charCode = dataView.getUint8(pos++))) {
  96191. manifestString += String.fromCharCode(charCode);
  96192. }
  96193. var manifest = JSON.parse(manifestString);
  96194. if (manifest.specular) {
  96195. // Extend the header with the position of the payload.
  96196. manifest.specular.specularDataPosition = pos;
  96197. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  96198. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  96199. }
  96200. return manifest;
  96201. };
  96202. /**
  96203. * Creates an environment texture from a loaded cube texture.
  96204. * @param texture defines the cube texture to convert in env file
  96205. * @return a promise containing the environment data if succesfull.
  96206. */
  96207. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  96208. var _this = this;
  96209. var internalTexture = texture.getInternalTexture();
  96210. if (!internalTexture) {
  96211. return Promise.reject("The cube texture is invalid.");
  96212. }
  96213. if (!texture._prefiltered) {
  96214. return Promise.reject("The cube texture is invalid (not prefiltered).");
  96215. }
  96216. var engine = internalTexture.getEngine();
  96217. if (engine && engine.premultipliedAlpha) {
  96218. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  96219. }
  96220. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  96221. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  96222. }
  96223. var canvas = engine.getRenderingCanvas();
  96224. if (!canvas) {
  96225. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  96226. }
  96227. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96228. if (!engine.getCaps().textureFloatRender) {
  96229. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96230. if (!engine.getCaps().textureHalfFloatRender) {
  96231. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  96232. }
  96233. }
  96234. var cubeWidth = internalTexture.width;
  96235. var hostingScene = new BABYLON.Scene(engine);
  96236. var specularTextures = {};
  96237. var promises = [];
  96238. // Read and collect all mipmaps data from the cube.
  96239. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  96240. mipmapsCount = Math.round(mipmapsCount);
  96241. var _loop_1 = function (i) {
  96242. var faceWidth = Math.pow(2, mipmapsCount - i);
  96243. var _loop_2 = function (face) {
  96244. var data = texture.readPixels(face, i);
  96245. // Creates a temp texture with the face data.
  96246. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  96247. // And rgbdEncode them.
  96248. var promise = new Promise(function (resolve, reject) {
  96249. 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);
  96250. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  96251. rgbdPostProcess.onApply = function (effect) {
  96252. effect._bindTexture("textureSampler", tempTexture);
  96253. };
  96254. // As the process needs to happen on the main canvas, keep track of the current size
  96255. var currentW = engine.getRenderWidth();
  96256. var currentH = engine.getRenderHeight();
  96257. // Set the desired size for the texture
  96258. engine.setSize(faceWidth, faceWidth);
  96259. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  96260. // Reading datas from WebGL
  96261. BABYLON.Tools.ToBlob(canvas, function (blob) {
  96262. var fileReader = new FileReader();
  96263. fileReader.onload = function (event) {
  96264. var arrayBuffer = event.target.result;
  96265. specularTextures[i * 6 + face] = arrayBuffer;
  96266. resolve();
  96267. };
  96268. fileReader.readAsArrayBuffer(blob);
  96269. });
  96270. // Reapply the previous canvas size
  96271. engine.setSize(currentW, currentH);
  96272. });
  96273. });
  96274. promises.push(promise);
  96275. };
  96276. // All faces of the cube.
  96277. for (var face = 0; face < 6; face++) {
  96278. _loop_2(face);
  96279. }
  96280. };
  96281. for (var i = 0; i <= mipmapsCount; i++) {
  96282. _loop_1(i);
  96283. }
  96284. // Once all the textures haves been collected as RGBD stored in PNGs
  96285. return Promise.all(promises).then(function () {
  96286. // We can delete the hosting scene keeping track of all the creation objects
  96287. hostingScene.dispose();
  96288. // Creates the json header for the env texture
  96289. var info = {
  96290. version: 1,
  96291. width: cubeWidth,
  96292. irradiance: _this._CreateEnvTextureIrradiance(texture),
  96293. specular: {
  96294. mipmaps: [],
  96295. lodGenerationScale: texture.lodGenerationScale
  96296. }
  96297. };
  96298. // Sets the specular image data information
  96299. var position = 0;
  96300. for (var i = 0; i <= mipmapsCount; i++) {
  96301. for (var face = 0; face < 6; face++) {
  96302. var byteLength = specularTextures[i * 6 + face].byteLength;
  96303. info.specular.mipmaps.push({
  96304. length: byteLength,
  96305. position: position
  96306. });
  96307. position += byteLength;
  96308. }
  96309. }
  96310. // Encode the JSON as an array buffer
  96311. var infoString = JSON.stringify(info);
  96312. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  96313. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  96314. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  96315. infoView[i] = infoString.charCodeAt(i);
  96316. }
  96317. // Ends up with a null terminator for easier parsing
  96318. infoView[infoString.length] = 0x00;
  96319. // Computes the final required size and creates the storage
  96320. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  96321. var finalBuffer = new ArrayBuffer(totalSize);
  96322. var finalBufferView = new Uint8Array(finalBuffer);
  96323. var dataView = new DataView(finalBuffer);
  96324. // Copy the magic bytes identifying the file in
  96325. var pos = 0;
  96326. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  96327. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  96328. }
  96329. // Add the json info
  96330. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  96331. pos += infoBuffer.byteLength;
  96332. // Finally inserts the texture data
  96333. for (var i = 0; i <= mipmapsCount; i++) {
  96334. for (var face = 0; face < 6; face++) {
  96335. var dataBuffer = specularTextures[i * 6 + face];
  96336. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  96337. pos += dataBuffer.byteLength;
  96338. }
  96339. }
  96340. // Voila
  96341. return finalBuffer;
  96342. });
  96343. };
  96344. /**
  96345. * Creates a JSON representation of the spherical data.
  96346. * @param texture defines the texture containing the polynomials
  96347. * @return the JSON representation of the spherical info
  96348. */
  96349. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  96350. var polynmials = texture.sphericalPolynomial;
  96351. if (polynmials == null) {
  96352. return null;
  96353. }
  96354. return {
  96355. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  96356. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  96357. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  96358. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  96359. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  96360. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  96361. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  96362. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  96363. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  96364. };
  96365. };
  96366. /**
  96367. * Uploads the texture info contained in the env file to the GPU.
  96368. * @param texture defines the internal texture to upload to
  96369. * @param arrayBuffer defines the buffer cotaining the data to load
  96370. * @param info defines the texture info retrieved through the GetEnvInfo method
  96371. * @returns a promise
  96372. */
  96373. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  96374. if (info.version !== 1) {
  96375. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  96376. }
  96377. var specularInfo = info.specular;
  96378. if (!specularInfo) {
  96379. // Nothing else parsed so far
  96380. return Promise.resolve();
  96381. }
  96382. // Double checks the enclosed info
  96383. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  96384. mipmapsCount = Math.round(mipmapsCount) + 1;
  96385. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  96386. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  96387. }
  96388. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  96389. var imageData = new Array(mipmapsCount);
  96390. for (var i = 0; i < mipmapsCount; i++) {
  96391. imageData[i] = new Array(6);
  96392. for (var face = 0; face < 6; face++) {
  96393. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  96394. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  96395. }
  96396. }
  96397. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  96398. };
  96399. /**
  96400. * Uploads the levels of image data to the GPU.
  96401. * @param texture defines the internal texture to upload to
  96402. * @param imageData defines the array buffer views of image data [mipmap][face]
  96403. * @returns a promise
  96404. */
  96405. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  96406. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  96407. throw new Error("Texture size must be a power of two");
  96408. }
  96409. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  96410. // Gets everything ready.
  96411. var engine = texture.getEngine();
  96412. var expandTexture = false;
  96413. var generateNonLODTextures = false;
  96414. var rgbdPostProcess = null;
  96415. var cubeRtt = null;
  96416. var lodTextures = null;
  96417. var caps = engine.getCaps();
  96418. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96419. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96420. texture.generateMipMaps = true;
  96421. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  96422. // Add extra process if texture lod is not supported
  96423. if (!caps.textureLOD) {
  96424. expandTexture = false;
  96425. generateNonLODTextures = true;
  96426. lodTextures = {};
  96427. }
  96428. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  96429. else if (engine.webGLVersion < 2) {
  96430. expandTexture = false;
  96431. }
  96432. // If half float available we can uncompress the texture
  96433. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  96434. expandTexture = true;
  96435. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96436. }
  96437. // If full float available we can uncompress the texture
  96438. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  96439. expandTexture = true;
  96440. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96441. }
  96442. // Expand the texture if possible
  96443. if (expandTexture) {
  96444. // Simply run through the decode PP
  96445. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  96446. texture._isRGBD = false;
  96447. texture.invertY = false;
  96448. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  96449. generateDepthBuffer: false,
  96450. generateMipMaps: true,
  96451. generateStencilBuffer: false,
  96452. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  96453. type: texture.type,
  96454. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  96455. });
  96456. }
  96457. else {
  96458. texture._isRGBD = true;
  96459. texture.invertY = true;
  96460. // In case of missing support, applies the same patch than DDS files.
  96461. if (generateNonLODTextures) {
  96462. var mipSlices = 3;
  96463. var scale = texture._lodGenerationScale;
  96464. var offset = texture._lodGenerationOffset;
  96465. for (var i = 0; i < mipSlices; i++) {
  96466. //compute LOD from even spacing in smoothness (matching shader calculation)
  96467. var smoothness = i / (mipSlices - 1);
  96468. var roughness = 1 - smoothness;
  96469. var minLODIndex = offset; // roughness = 0
  96470. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  96471. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  96472. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  96473. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  96474. glTextureFromLod.isCube = true;
  96475. glTextureFromLod.invertY = true;
  96476. glTextureFromLod.generateMipMaps = false;
  96477. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  96478. // Wrap in a base texture for easy binding.
  96479. var lodTexture = new BABYLON.BaseTexture(null);
  96480. lodTexture.isCube = true;
  96481. lodTexture._texture = glTextureFromLod;
  96482. lodTextures[mipmapIndex] = lodTexture;
  96483. switch (i) {
  96484. case 0:
  96485. texture._lodTextureLow = lodTexture;
  96486. break;
  96487. case 1:
  96488. texture._lodTextureMid = lodTexture;
  96489. break;
  96490. case 2:
  96491. texture._lodTextureHigh = lodTexture;
  96492. break;
  96493. }
  96494. }
  96495. }
  96496. }
  96497. var promises = [];
  96498. var _loop_3 = function (i) {
  96499. var _loop_4 = function (face) {
  96500. // Constructs an image element from image data
  96501. var bytes = imageData[i][face];
  96502. var blob = new Blob([bytes], { type: 'image/png' });
  96503. var url = URL.createObjectURL(blob);
  96504. var image = new Image();
  96505. image.src = url;
  96506. // Enqueue promise to upload to the texture.
  96507. var promise = new Promise(function (resolve, reject) {
  96508. image.onload = function () {
  96509. if (expandTexture) {
  96510. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  96511. reject(message);
  96512. }, image);
  96513. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  96514. // Uncompress the data to a RTT
  96515. rgbdPostProcess.onApply = function (effect) {
  96516. effect._bindTexture("textureSampler", tempTexture_1);
  96517. effect.setFloat2("scale", 1, 1);
  96518. };
  96519. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  96520. // Cleanup
  96521. engine.restoreDefaultFramebuffer();
  96522. tempTexture_1.dispose();
  96523. window.URL.revokeObjectURL(url);
  96524. resolve();
  96525. });
  96526. }
  96527. else {
  96528. engine._uploadImageToTexture(texture, image, face, i);
  96529. // Upload the face to the non lod texture support
  96530. if (generateNonLODTextures) {
  96531. var lodTexture = lodTextures[i];
  96532. if (lodTexture) {
  96533. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  96534. }
  96535. }
  96536. resolve();
  96537. }
  96538. };
  96539. image.onerror = function (error) {
  96540. reject(error);
  96541. };
  96542. });
  96543. promises.push(promise);
  96544. };
  96545. // All faces
  96546. for (var face = 0; face < 6; face++) {
  96547. _loop_4(face);
  96548. }
  96549. };
  96550. // All mipmaps up to provided number of images
  96551. for (var i = 0; i < imageData.length; i++) {
  96552. _loop_3(i);
  96553. }
  96554. // Fill remaining mipmaps with black textures.
  96555. if (imageData.length < mipmapsCount) {
  96556. var data = void 0;
  96557. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  96558. var dataLength = size * size * 4;
  96559. switch (texture.type) {
  96560. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  96561. data = new Uint8Array(dataLength);
  96562. break;
  96563. }
  96564. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  96565. data = new Uint16Array(dataLength);
  96566. break;
  96567. }
  96568. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  96569. data = new Float32Array(dataLength);
  96570. break;
  96571. }
  96572. }
  96573. for (var i = imageData.length; i < mipmapsCount; i++) {
  96574. for (var face = 0; face < 6; face++) {
  96575. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  96576. }
  96577. }
  96578. }
  96579. // Once all done, finishes the cleanup and return
  96580. return Promise.all(promises).then(function () {
  96581. // Release temp RTT.
  96582. if (cubeRtt) {
  96583. engine._releaseFramebufferObjects(cubeRtt);
  96584. cubeRtt._swapAndDie(texture);
  96585. }
  96586. // Release temp Post Process.
  96587. if (rgbdPostProcess) {
  96588. rgbdPostProcess.dispose();
  96589. }
  96590. // Flag internal texture as ready in case they are in use.
  96591. if (generateNonLODTextures) {
  96592. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  96593. texture._lodTextureHigh._texture.isReady = true;
  96594. }
  96595. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  96596. texture._lodTextureMid._texture.isReady = true;
  96597. }
  96598. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  96599. texture._lodTextureLow._texture.isReady = true;
  96600. }
  96601. }
  96602. });
  96603. };
  96604. /**
  96605. * Uploads spherical polynomials information to the texture.
  96606. * @param texture defines the texture we are trying to upload the information to
  96607. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  96608. */
  96609. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  96610. if (info.version !== 1) {
  96611. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  96612. }
  96613. var irradianceInfo = info.irradiance;
  96614. if (!irradianceInfo) {
  96615. return;
  96616. }
  96617. var sp = new BABYLON.SphericalPolynomial();
  96618. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  96619. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  96620. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  96621. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  96622. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  96623. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  96624. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  96625. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  96626. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  96627. texture._sphericalPolynomial = sp;
  96628. };
  96629. /**
  96630. * Magic number identifying the env file.
  96631. */
  96632. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  96633. return EnvironmentTextureTools;
  96634. }());
  96635. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  96636. })(BABYLON || (BABYLON = {}));
  96637. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  96638. var BABYLON;
  96639. (function (BABYLON) {
  96640. /**
  96641. * Implementation of the ENV Texture Loader.
  96642. */
  96643. var ENVTextureLoader = /** @class */ (function () {
  96644. function ENVTextureLoader() {
  96645. /**
  96646. * Defines wether the loader supports cascade loading the different faces.
  96647. */
  96648. this.supportCascades = false;
  96649. }
  96650. /**
  96651. * This returns if the loader support the current file information.
  96652. * @param extension defines the file extension of the file being loaded
  96653. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96654. * @param fallback defines the fallback internal texture if any
  96655. * @param isBase64 defines whether the texture is encoded as a base64
  96656. * @param isBuffer defines whether the texture data are stored as a buffer
  96657. * @returns true if the loader can load the specified file
  96658. */
  96659. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96660. return extension.indexOf(".env") === 0;
  96661. };
  96662. /**
  96663. * Transform the url before loading if required.
  96664. * @param rootUrl the url of the texture
  96665. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96666. * @returns the transformed texture
  96667. */
  96668. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96669. return rootUrl;
  96670. };
  96671. /**
  96672. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96673. * @param rootUrl the url of the texture
  96674. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96675. * @returns the fallback texture
  96676. */
  96677. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96678. return null;
  96679. };
  96680. /**
  96681. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96682. * @param data contains the texture data
  96683. * @param texture defines the BabylonJS internal texture
  96684. * @param createPolynomials will be true if polynomials have been requested
  96685. * @param onLoad defines the callback to trigger once the texture is ready
  96686. * @param onError defines the callback to trigger in case of error
  96687. */
  96688. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96689. if (Array.isArray(data)) {
  96690. return;
  96691. }
  96692. data = data;
  96693. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  96694. if (info) {
  96695. texture.width = info.width;
  96696. texture.height = info.width;
  96697. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  96698. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  96699. texture.isReady = true;
  96700. if (onLoad) {
  96701. onLoad();
  96702. }
  96703. });
  96704. }
  96705. else if (onError) {
  96706. onError("Can not parse the environment file", null);
  96707. }
  96708. };
  96709. /**
  96710. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96711. * @param data contains the texture data
  96712. * @param texture defines the BabylonJS internal texture
  96713. * @param callback defines the method to call once ready to upload
  96714. */
  96715. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  96716. throw ".env not supported in 2d.";
  96717. };
  96718. return ENVTextureLoader;
  96719. }());
  96720. // Register the loader.
  96721. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  96722. })(BABYLON || (BABYLON = {}));
  96723. //# sourceMappingURL=babylon.envTextureLoader.js.map
  96724. var BABYLON;
  96725. (function (BABYLON) {
  96726. /**
  96727. * Renders a layer on top of an existing scene
  96728. */
  96729. var UtilityLayerRenderer = /** @class */ (function () {
  96730. /**
  96731. * Instantiates a UtilityLayerRenderer
  96732. * @param originalScene the original scene that will be rendered on top of
  96733. */
  96734. function UtilityLayerRenderer(
  96735. /** the original scene that will be rendered on top of */
  96736. originalScene) {
  96737. var _this = this;
  96738. this.originalScene = originalScene;
  96739. this._pointerCaptures = {};
  96740. this._lastPointerEvents = {};
  96741. /**
  96742. * If the utility layer should automatically be rendered on top of existing scene
  96743. */
  96744. this.shouldRender = true;
  96745. /**
  96746. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  96747. */
  96748. this.onlyCheckPointerDownEvents = true;
  96749. /**
  96750. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  96751. */
  96752. this.processAllEvents = false;
  96753. /**
  96754. * Observable raised when the pointer move from the utility layer scene to the main scene
  96755. */
  96756. this.onPointerOutObservable = new BABYLON.Observable();
  96757. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  96758. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  96759. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  96760. this.utilityLayerScene._allowPostProcessClearColor = false;
  96761. originalScene.getEngine().scenes.pop();
  96762. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  96763. this.utilityLayerScene.detachControl();
  96764. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  96765. if (!_this.processAllEvents) {
  96766. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  96767. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  96768. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  96769. return;
  96770. }
  96771. }
  96772. var pointerEvent = (prePointerInfo.event);
  96773. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  96774. _this._pointerCaptures[pointerEvent.pointerId] = false;
  96775. return;
  96776. }
  96777. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  96778. if (!prePointerInfo.ray && utilityScenePick) {
  96779. prePointerInfo.ray = utilityScenePick.ray;
  96780. }
  96781. // always fire the prepointer oversvable
  96782. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  96783. // allow every non pointer down event to flow to the utility layer
  96784. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  96785. if (!prePointerInfo.skipOnPointerObservable) {
  96786. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  96787. }
  96788. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  96789. _this._pointerCaptures[pointerEvent.pointerId] = false;
  96790. }
  96791. return;
  96792. }
  96793. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  96794. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  96795. if (utilityScenePick && utilityScenePick.hit) {
  96796. if (!prePointerInfo.skipOnPointerObservable) {
  96797. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  96798. }
  96799. prePointerInfo.skipOnPointerObservable = true;
  96800. }
  96801. }
  96802. else {
  96803. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  96804. var pointerEvent_1 = (prePointerInfo.event);
  96805. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  96806. if (originalScenePick && utilityScenePick) {
  96807. // No pick in utility scene
  96808. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  96809. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96810. // We touched an utility mesh present in the main scene
  96811. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96812. prePointerInfo.skipOnPointerObservable = true;
  96813. }
  96814. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96815. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  96816. }
  96817. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96818. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96819. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96820. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96821. }
  96822. }
  96823. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  96824. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  96825. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  96826. // If a previous utility layer set this, do not unset this
  96827. if (!prePointerInfo.skipOnPointerObservable) {
  96828. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  96829. }
  96830. }
  96831. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  96832. // We have a pick in both scenes but main is closer than utility
  96833. // We touched an utility mesh present in the main scene
  96834. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96835. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96836. prePointerInfo.skipOnPointerObservable = true;
  96837. }
  96838. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96839. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96840. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96841. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96842. }
  96843. }
  96844. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  96845. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  96846. }
  96847. }
  96848. }
  96849. });
  96850. // Render directly on top of existing scene without clearing
  96851. this.utilityLayerScene.autoClear = false;
  96852. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  96853. if (_this.shouldRender) {
  96854. _this.render();
  96855. }
  96856. });
  96857. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  96858. _this.dispose();
  96859. });
  96860. this._updateCamera();
  96861. }
  96862. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  96863. /**
  96864. * 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)
  96865. */
  96866. get: function () {
  96867. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  96868. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96869. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96870. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96871. });
  96872. }
  96873. return UtilityLayerRenderer._DefaultUtilityLayer;
  96874. },
  96875. enumerable: true,
  96876. configurable: true
  96877. });
  96878. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  96879. /**
  96880. * 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)
  96881. */
  96882. get: function () {
  96883. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  96884. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96885. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  96886. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96887. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96888. });
  96889. }
  96890. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  96891. },
  96892. enumerable: true,
  96893. configurable: true
  96894. });
  96895. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  96896. if (!prePointerInfo.skipOnPointerObservable) {
  96897. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  96898. this._lastPointerEvents[pointerEvent.pointerId] = true;
  96899. }
  96900. };
  96901. /**
  96902. * Renders the utility layers scene on top of the original scene
  96903. */
  96904. UtilityLayerRenderer.prototype.render = function () {
  96905. this._updateCamera();
  96906. if (this.utilityLayerScene.activeCamera) {
  96907. // Set the camera's scene to utility layers scene
  96908. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  96909. var camera = this.utilityLayerScene.activeCamera;
  96910. camera._scene = this.utilityLayerScene;
  96911. if (camera.leftCamera) {
  96912. camera.leftCamera._scene = this.utilityLayerScene;
  96913. }
  96914. if (camera.rightCamera) {
  96915. camera.rightCamera._scene = this.utilityLayerScene;
  96916. }
  96917. this.utilityLayerScene.render(false);
  96918. // Reset camera's scene back to original
  96919. camera._scene = oldScene;
  96920. if (camera.leftCamera) {
  96921. camera.leftCamera._scene = oldScene;
  96922. }
  96923. if (camera.rightCamera) {
  96924. camera.rightCamera._scene = oldScene;
  96925. }
  96926. }
  96927. };
  96928. /**
  96929. * Disposes of the renderer
  96930. */
  96931. UtilityLayerRenderer.prototype.dispose = function () {
  96932. this.onPointerOutObservable.clear();
  96933. if (this._afterRenderObserver) {
  96934. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  96935. }
  96936. if (this._sceneDisposeObserver) {
  96937. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96938. }
  96939. if (this._originalPointerObserver) {
  96940. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  96941. }
  96942. this.utilityLayerScene.dispose();
  96943. };
  96944. UtilityLayerRenderer.prototype._updateCamera = function () {
  96945. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  96946. };
  96947. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96948. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96949. return UtilityLayerRenderer;
  96950. }());
  96951. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  96952. })(BABYLON || (BABYLON = {}));
  96953. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  96954. //# sourceMappingURL=babylon.behavior.js.map
  96955. var BABYLON;
  96956. (function (BABYLON) {
  96957. /**
  96958. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  96959. */
  96960. var PointerDragBehavior = /** @class */ (function () {
  96961. /**
  96962. * Creates a pointer drag behavior that can be attached to a mesh
  96963. * @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)
  96964. */
  96965. function PointerDragBehavior(options) {
  96966. /**
  96967. * 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)
  96968. */
  96969. this.maxDragAngle = 0;
  96970. /**
  96971. * @hidden
  96972. */
  96973. this._useAlternatePickedPointAboveMaxDragAngle = false;
  96974. /**
  96975. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96976. */
  96977. this.currentDraggingPointerID = -1;
  96978. /**
  96979. * If the behavior is currently in a dragging state
  96980. */
  96981. this.dragging = false;
  96982. /**
  96983. * 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)
  96984. */
  96985. this.dragDeltaRatio = 0.2;
  96986. /**
  96987. * If the drag plane orientation should be updated during the dragging (Default: true)
  96988. */
  96989. this.updateDragPlane = true;
  96990. // Debug mode will display drag planes to help visualize behavior
  96991. this._debugMode = false;
  96992. this._moving = false;
  96993. /**
  96994. * Fires each time the attached mesh is dragged with the pointer
  96995. * * delta between last drag position and current drag position in world space
  96996. * * dragDistance along the drag axis
  96997. * * dragPlaneNormal normal of the current drag plane used during the drag
  96998. * * dragPlanePoint in world space where the drag intersects the drag plane
  96999. */
  97000. this.onDragObservable = new BABYLON.Observable();
  97001. /**
  97002. * Fires each time a drag begins (eg. mouse down on mesh)
  97003. */
  97004. this.onDragStartObservable = new BABYLON.Observable();
  97005. /**
  97006. * Fires each time a drag ends (eg. mouse release after drag)
  97007. */
  97008. this.onDragEndObservable = new BABYLON.Observable();
  97009. /**
  97010. * If the attached mesh should be moved when dragged
  97011. */
  97012. this.moveAttached = true;
  97013. /**
  97014. * If the drag behavior will react to drag events (Default: true)
  97015. */
  97016. this.enabled = true;
  97017. /**
  97018. * If camera controls should be detached during the drag
  97019. */
  97020. this.detachCameraControls = true;
  97021. /**
  97022. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  97023. */
  97024. this.useObjectOrienationForDragging = true;
  97025. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97026. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  97027. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  97028. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97029. this._attachedElement = null;
  97030. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97031. this._lastPointerRay = {};
  97032. this._dragDelta = new BABYLON.Vector3();
  97033. // Variables to avoid instantiation in the below method
  97034. this._pointA = new BABYLON.Vector3(0, 0, 0);
  97035. this._pointB = new BABYLON.Vector3(0, 0, 0);
  97036. this._pointC = new BABYLON.Vector3(0, 0, 0);
  97037. this._lineA = new BABYLON.Vector3(0, 0, 0);
  97038. this._lineB = new BABYLON.Vector3(0, 0, 0);
  97039. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  97040. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  97041. this._options = options ? options : {};
  97042. var optionCount = 0;
  97043. if (this._options.dragAxis) {
  97044. optionCount++;
  97045. }
  97046. if (this._options.dragPlaneNormal) {
  97047. optionCount++;
  97048. }
  97049. if (optionCount > 1) {
  97050. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  97051. }
  97052. }
  97053. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  97054. /**
  97055. * The name of the behavior
  97056. */
  97057. get: function () {
  97058. return "PointerDrag";
  97059. },
  97060. enumerable: true,
  97061. configurable: true
  97062. });
  97063. /**
  97064. * Initializes the behavior
  97065. */
  97066. PointerDragBehavior.prototype.init = function () { };
  97067. /**
  97068. * Attaches the drag behavior the passed in mesh
  97069. * @param ownerNode The mesh that will be dragged around once attached
  97070. */
  97071. PointerDragBehavior.prototype.attach = function (ownerNode) {
  97072. var _this = this;
  97073. this._scene = ownerNode.getScene();
  97074. this._attachedNode = ownerNode;
  97075. // Initialize drag plane to not interfere with existing scene
  97076. if (!PointerDragBehavior._planeScene) {
  97077. if (this._debugMode) {
  97078. PointerDragBehavior._planeScene = this._scene;
  97079. }
  97080. else {
  97081. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  97082. PointerDragBehavior._planeScene.detachControl();
  97083. this._scene.getEngine().scenes.pop();
  97084. this._scene.onDisposeObservable.addOnce(function () {
  97085. PointerDragBehavior._planeScene.dispose();
  97086. PointerDragBehavior._planeScene = null;
  97087. });
  97088. }
  97089. }
  97090. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  97091. // State of the drag
  97092. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  97093. var pickPredicate = function (m) {
  97094. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  97095. };
  97096. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97097. if (!_this.enabled) {
  97098. return;
  97099. }
  97100. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97101. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97102. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  97103. }
  97104. }
  97105. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97106. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97107. _this.releaseDrag();
  97108. }
  97109. }
  97110. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97111. var pointerId = pointerInfo.event.pointerId;
  97112. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  97113. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  97114. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  97115. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  97116. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  97117. }
  97118. _this.currentDraggingPointerID = pointerId;
  97119. }
  97120. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  97121. if (!_this._lastPointerRay[pointerId]) {
  97122. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97123. }
  97124. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  97125. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  97126. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  97127. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  97128. _this._moveDrag(pointerInfo.pickInfo.ray);
  97129. }
  97130. }
  97131. }
  97132. });
  97133. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97134. if (_this._moving && _this.moveAttached) {
  97135. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  97136. // Slowly move mesh to avoid jitter
  97137. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  97138. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  97139. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  97140. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  97141. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  97142. }
  97143. });
  97144. };
  97145. /**
  97146. * Force relase the drag action by code.
  97147. */
  97148. PointerDragBehavior.prototype.releaseDrag = function () {
  97149. this.dragging = false;
  97150. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  97151. this.currentDraggingPointerID = -1;
  97152. this._moving = false;
  97153. // Reattach camera controls
  97154. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97155. this._scene.activeCamera.attachControl(this._attachedElement, true);
  97156. }
  97157. };
  97158. /**
  97159. * Simulates the start of a pointer drag event on the behavior
  97160. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  97161. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  97162. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  97163. */
  97164. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  97165. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  97166. this._startDrag(pointerId, fromRay, startPickedPoint);
  97167. var lastRay = this._lastPointerRay[pointerId];
  97168. if (pointerId === PointerDragBehavior._AnyMouseID) {
  97169. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  97170. }
  97171. if (lastRay) {
  97172. // if there was a last pointer ray drag the object there
  97173. this._moveDrag(lastRay);
  97174. }
  97175. };
  97176. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  97177. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  97178. return;
  97179. }
  97180. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  97181. // Create start ray from the camera to the object
  97182. if (fromRay) {
  97183. this._startDragRay.direction.copyFrom(fromRay.direction);
  97184. this._startDragRay.origin.copyFrom(fromRay.origin);
  97185. }
  97186. else {
  97187. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  97188. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  97189. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  97190. }
  97191. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  97192. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  97193. if (pickedPoint) {
  97194. this.dragging = true;
  97195. this.currentDraggingPointerID = pointerId;
  97196. this.lastDragPosition.copyFrom(pickedPoint);
  97197. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  97198. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  97199. // Detatch camera controls
  97200. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97201. if (this._scene.activeCamera.inputs.attachedElement) {
  97202. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  97203. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  97204. }
  97205. else {
  97206. this._attachedElement = null;
  97207. }
  97208. }
  97209. }
  97210. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  97211. };
  97212. PointerDragBehavior.prototype._moveDrag = function (ray) {
  97213. this._moving = true;
  97214. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  97215. if (pickedPoint) {
  97216. if (this.updateDragPlane) {
  97217. this._updateDragPlanePosition(ray, pickedPoint);
  97218. }
  97219. var dragLength = 0;
  97220. // depending on the drag mode option drag accordingly
  97221. if (this._options.dragAxis) {
  97222. // Convert local drag axis to world
  97223. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  97224. // Project delta drag from the drag plane onto the drag axis
  97225. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  97226. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  97227. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  97228. }
  97229. else {
  97230. dragLength = this._dragDelta.length();
  97231. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  97232. }
  97233. this._targetPosition.addInPlace(this._dragDelta);
  97234. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  97235. this.lastDragPosition.copyFrom(pickedPoint);
  97236. }
  97237. };
  97238. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  97239. var _this = this;
  97240. if (!ray) {
  97241. return null;
  97242. }
  97243. // Calculate angle between plane normal and ray
  97244. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  97245. // Correct if ray is casted from oposite side
  97246. if (angle > Math.PI / 2) {
  97247. angle = Math.PI - angle;
  97248. }
  97249. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  97250. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  97251. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  97252. // Invert ray direction along the towards object axis
  97253. this._tmpVector.copyFrom(ray.direction);
  97254. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  97255. this._alternatePickedPoint.normalize();
  97256. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  97257. this._tmpVector.addInPlace(this._alternatePickedPoint);
  97258. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  97259. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  97260. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  97261. this._alternatePickedPoint.addInPlace(this._tmpVector);
  97262. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  97263. return this._alternatePickedPoint;
  97264. }
  97265. else {
  97266. return null;
  97267. }
  97268. }
  97269. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  97270. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  97271. return pickResult.pickedPoint;
  97272. }
  97273. else {
  97274. return null;
  97275. }
  97276. };
  97277. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  97278. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  97279. this._pointA.copyFrom(dragPlanePosition);
  97280. if (this._options.dragAxis) {
  97281. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  97282. // Calculate plane normal in direction of camera but perpendicular to drag axis
  97283. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  97284. ray.origin.subtractToRef(this._pointA, this._pointC);
  97285. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  97286. // Get perpendicular line from direction to camera and drag axis
  97287. this._pointB.subtractToRef(this._pointA, this._lineA);
  97288. this._pointC.subtractToRef(this._pointA, this._lineB);
  97289. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  97290. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  97291. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  97292. this._lookAt.normalize();
  97293. this._dragPlane.position.copyFrom(this._pointA);
  97294. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  97295. this._dragPlane.lookAt(this._lookAt);
  97296. }
  97297. else if (this._options.dragPlaneNormal) {
  97298. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  97299. this._dragPlane.position.copyFrom(this._pointA);
  97300. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  97301. this._dragPlane.lookAt(this._lookAt);
  97302. }
  97303. else {
  97304. this._dragPlane.position.copyFrom(this._pointA);
  97305. this._dragPlane.lookAt(ray.origin);
  97306. }
  97307. this._dragPlane.computeWorldMatrix(true);
  97308. };
  97309. /**
  97310. * Detaches the behavior from the mesh
  97311. */
  97312. PointerDragBehavior.prototype.detach = function () {
  97313. if (this._pointerObserver) {
  97314. this._scene.onPointerObservable.remove(this._pointerObserver);
  97315. }
  97316. if (this._beforeRenderObserver) {
  97317. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  97318. }
  97319. };
  97320. PointerDragBehavior._AnyMouseID = -2;
  97321. return PointerDragBehavior;
  97322. }());
  97323. BABYLON.PointerDragBehavior = PointerDragBehavior;
  97324. })(BABYLON || (BABYLON = {}));
  97325. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  97326. var BABYLON;
  97327. (function (BABYLON) {
  97328. /**
  97329. * A behavior that when attached to a mesh will allow the mesh to be scaled
  97330. */
  97331. var MultiPointerScaleBehavior = /** @class */ (function () {
  97332. /**
  97333. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  97334. */
  97335. function MultiPointerScaleBehavior() {
  97336. this._startDistance = 0;
  97337. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  97338. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  97339. this._sceneRenderObserver = null;
  97340. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  97341. this._dragBehaviorA.moveAttached = false;
  97342. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  97343. this._dragBehaviorB.moveAttached = false;
  97344. }
  97345. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  97346. /**
  97347. * The name of the behavior
  97348. */
  97349. get: function () {
  97350. return "MultiPointerScale";
  97351. },
  97352. enumerable: true,
  97353. configurable: true
  97354. });
  97355. /**
  97356. * Initializes the behavior
  97357. */
  97358. MultiPointerScaleBehavior.prototype.init = function () { };
  97359. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  97360. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  97361. };
  97362. /**
  97363. * Attaches the scale behavior the passed in mesh
  97364. * @param ownerNode The mesh that will be scaled around once attached
  97365. */
  97366. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  97367. var _this = this;
  97368. this._ownerNode = ownerNode;
  97369. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  97370. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  97371. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97372. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  97373. _this._dragBehaviorA.releaseDrag();
  97374. }
  97375. else {
  97376. _this._initialScale.copyFrom(ownerNode.scaling);
  97377. _this._startDistance = _this._getCurrentDistance();
  97378. }
  97379. }
  97380. });
  97381. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  97382. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97383. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  97384. _this._dragBehaviorB.releaseDrag();
  97385. }
  97386. else {
  97387. _this._initialScale.copyFrom(ownerNode.scaling);
  97388. _this._startDistance = _this._getCurrentDistance();
  97389. }
  97390. }
  97391. });
  97392. // Once both drag behaviors are active scale based on the distance between the two pointers
  97393. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  97394. behavior.onDragObservable.add(function () {
  97395. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97396. var ratio = _this._getCurrentDistance() / _this._startDistance;
  97397. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  97398. }
  97399. });
  97400. });
  97401. ownerNode.addBehavior(this._dragBehaviorA);
  97402. ownerNode.addBehavior(this._dragBehaviorB);
  97403. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  97404. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  97405. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97406. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  97407. if (change.length() > 0.01) {
  97408. ownerNode.scaling.addInPlace(change);
  97409. }
  97410. }
  97411. });
  97412. };
  97413. /**
  97414. * Detaches the behavior from the mesh
  97415. */
  97416. MultiPointerScaleBehavior.prototype.detach = function () {
  97417. var _this = this;
  97418. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  97419. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  97420. behavior.onDragStartObservable.clear();
  97421. behavior.onDragObservable.clear();
  97422. _this._ownerNode.removeBehavior(behavior);
  97423. });
  97424. };
  97425. return MultiPointerScaleBehavior;
  97426. }());
  97427. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  97428. })(BABYLON || (BABYLON = {}));
  97429. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  97430. var BABYLON;
  97431. (function (BABYLON) {
  97432. /**
  97433. * 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
  97434. */
  97435. var SixDofDragBehavior = /** @class */ (function () {
  97436. /**
  97437. * 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
  97438. */
  97439. function SixDofDragBehavior() {
  97440. this._sceneRenderObserver = null;
  97441. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97442. this._moving = false;
  97443. this._startingOrientation = new BABYLON.Quaternion();
  97444. /**
  97445. * 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)
  97446. */
  97447. this.zDragFactor = 3;
  97448. /**
  97449. * If the behavior is currently in a dragging state
  97450. */
  97451. this.dragging = false;
  97452. /**
  97453. * 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)
  97454. */
  97455. this.dragDeltaRatio = 0.2;
  97456. /**
  97457. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  97458. */
  97459. this.currentDraggingPointerID = -1;
  97460. /**
  97461. * If camera controls should be detached during the drag
  97462. */
  97463. this.detachCameraControls = true;
  97464. /**
  97465. * Fires each time a drag starts
  97466. */
  97467. this.onDragStartObservable = new BABYLON.Observable();
  97468. /**
  97469. * Fires each time a drag ends (eg. mouse release after drag)
  97470. */
  97471. this.onDragEndObservable = new BABYLON.Observable();
  97472. }
  97473. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  97474. /**
  97475. * The name of the behavior
  97476. */
  97477. get: function () {
  97478. return "SixDofDrag";
  97479. },
  97480. enumerable: true,
  97481. configurable: true
  97482. });
  97483. /**
  97484. * Initializes the behavior
  97485. */
  97486. SixDofDragBehavior.prototype.init = function () { };
  97487. /**
  97488. * Attaches the scale behavior the passed in mesh
  97489. * @param ownerNode The mesh that will be scaled around once attached
  97490. */
  97491. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  97492. var _this = this;
  97493. this._ownerNode = ownerNode;
  97494. this._scene = this._ownerNode.getScene();
  97495. if (!SixDofDragBehavior._virtualScene) {
  97496. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  97497. this._scene.getEngine().scenes.pop();
  97498. }
  97499. var pickedMesh = null;
  97500. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  97501. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  97502. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  97503. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  97504. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  97505. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  97506. var pickPredicate = function (m) {
  97507. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  97508. };
  97509. var attachedElement = null;
  97510. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97511. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97512. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97513. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  97514. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  97515. }
  97516. pickedMesh = _this._ownerNode;
  97517. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  97518. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  97519. // Set position and orientation of the controller
  97520. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  97521. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  97522. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  97523. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  97524. pickedMesh.computeWorldMatrix();
  97525. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  97526. if (!pickedMesh.rotationQuaternion) {
  97527. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  97528. }
  97529. var oldParent = pickedMesh.parent;
  97530. pickedMesh.setParent(null);
  97531. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  97532. pickedMesh.setParent(oldParent);
  97533. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  97534. // Update state
  97535. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  97536. _this.dragging = true;
  97537. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  97538. // Detatch camera controls
  97539. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  97540. if (_this._scene.activeCamera.inputs.attachedElement) {
  97541. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  97542. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  97543. }
  97544. else {
  97545. attachedElement = null;
  97546. }
  97547. }
  97548. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  97549. _this.onDragStartObservable.notifyObservers({});
  97550. }
  97551. }
  97552. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97553. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97554. _this.dragging = false;
  97555. _this._moving = false;
  97556. _this.currentDraggingPointerID = -1;
  97557. pickedMesh = null;
  97558. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  97559. // Reattach camera controls
  97560. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  97561. _this._scene.activeCamera.attachControl(attachedElement, true);
  97562. }
  97563. _this.onDragEndObservable.notifyObservers({});
  97564. }
  97565. }
  97566. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97567. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  97568. var zDragFactor = _this.zDragFactor;
  97569. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  97570. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  97571. zDragFactor = 0;
  97572. }
  97573. // Calculate controller drag distance in controller space
  97574. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  97575. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  97576. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  97577. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  97578. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  97579. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  97580. if (_this._virtualDragMesh.position.z < 0) {
  97581. _this._virtualDragMesh.position.z = 0;
  97582. }
  97583. // Update the controller position
  97584. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  97585. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  97586. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  97587. // Move the virtualObjectsPosition into the picked mesh's space if needed
  97588. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  97589. if (pickedMesh.parent) {
  97590. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  97591. }
  97592. if (!_this._moving) {
  97593. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  97594. }
  97595. _this._moving = true;
  97596. }
  97597. }
  97598. });
  97599. var tmpQuaternion = new BABYLON.Quaternion();
  97600. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  97601. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  97602. if (_this.dragging && _this._moving && pickedMesh) {
  97603. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  97604. // Slowly move mesh to avoid jitter
  97605. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  97606. // Get change in rotation
  97607. tmpQuaternion.copyFrom(_this._startingOrientation);
  97608. tmpQuaternion.x = -tmpQuaternion.x;
  97609. tmpQuaternion.y = -tmpQuaternion.y;
  97610. tmpQuaternion.z = -tmpQuaternion.z;
  97611. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  97612. // Convert change in rotation to only y axis rotation
  97613. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  97614. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  97615. // Slowly move mesh to avoid jitter
  97616. var oldParent = pickedMesh.parent;
  97617. pickedMesh.setParent(null);
  97618. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  97619. pickedMesh.setParent(oldParent);
  97620. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  97621. }
  97622. });
  97623. };
  97624. /**
  97625. * Detaches the behavior from the mesh
  97626. */
  97627. SixDofDragBehavior.prototype.detach = function () {
  97628. if (this._scene) {
  97629. this._scene.onPointerObservable.remove(this._pointerObserver);
  97630. }
  97631. if (this._ownerNode) {
  97632. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  97633. }
  97634. if (this._virtualOriginMesh) {
  97635. this._virtualOriginMesh.dispose();
  97636. }
  97637. if (this._virtualDragMesh) {
  97638. this._virtualDragMesh.dispose();
  97639. }
  97640. this.onDragEndObservable.clear();
  97641. this.onDragStartObservable.clear();
  97642. };
  97643. return SixDofDragBehavior;
  97644. }());
  97645. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  97646. })(BABYLON || (BABYLON = {}));
  97647. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  97648. var BABYLON;
  97649. (function (BABYLON) {
  97650. /**
  97651. * @hidden
  97652. */
  97653. var FaceDirectionInfo = /** @class */ (function () {
  97654. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  97655. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  97656. if (diff === void 0) { diff = 0; }
  97657. if (ignore === void 0) { ignore = false; }
  97658. this.direction = direction;
  97659. this.rotatedDirection = rotatedDirection;
  97660. this.diff = diff;
  97661. this.ignore = ignore;
  97662. }
  97663. return FaceDirectionInfo;
  97664. }());
  97665. /**
  97666. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  97667. */
  97668. var AttachToBoxBehavior = /** @class */ (function () {
  97669. /**
  97670. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  97671. * @param ui The transform node that should be attched to the mesh
  97672. */
  97673. function AttachToBoxBehavior(ui) {
  97674. this.ui = ui;
  97675. /**
  97676. * The name of the behavior
  97677. */
  97678. this.name = "AttachToBoxBehavior";
  97679. /**
  97680. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  97681. */
  97682. this.distanceAwayFromFace = 0.15;
  97683. /**
  97684. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  97685. */
  97686. this.distanceAwayFromBottomOfFace = 0.15;
  97687. 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))];
  97688. this._tmpMatrix = new BABYLON.Matrix();
  97689. this._tmpVector = new BABYLON.Vector3();
  97690. this._zeroVector = BABYLON.Vector3.Zero();
  97691. this._lookAtTmpMatrix = new BABYLON.Matrix();
  97692. /* Does nothing */
  97693. }
  97694. /**
  97695. * Initializes the behavior
  97696. */
  97697. AttachToBoxBehavior.prototype.init = function () {
  97698. /* Does nothing */
  97699. };
  97700. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  97701. var _this = this;
  97702. // Go over each face and calculate the angle between the face's normal and targetDirection
  97703. this._faceVectors.forEach(function (v) {
  97704. if (!_this._target.rotationQuaternion) {
  97705. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  97706. }
  97707. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  97708. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  97709. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  97710. });
  97711. // Return the face information of the one with the normal closeset to target direction
  97712. return this._faceVectors.reduce(function (min, p) {
  97713. if (min.ignore) {
  97714. return p;
  97715. }
  97716. else if (p.ignore) {
  97717. return min;
  97718. }
  97719. else {
  97720. return min.diff < p.diff ? min : p;
  97721. }
  97722. }, this._faceVectors[0]);
  97723. };
  97724. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  97725. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  97726. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  97727. this._lookAtTmpMatrix.invert();
  97728. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  97729. };
  97730. /**
  97731. * Attaches the AttachToBoxBehavior to the passed in mesh
  97732. * @param target The mesh that the specified node will be attached to
  97733. */
  97734. AttachToBoxBehavior.prototype.attach = function (target) {
  97735. var _this = this;
  97736. this._target = target;
  97737. this._scene = this._target.getScene();
  97738. // Every frame, update the app bars position
  97739. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97740. if (!_this._scene.activeCamera) {
  97741. return;
  97742. }
  97743. // Find the face closest to the cameras position
  97744. var cameraPos = _this._scene.activeCamera.position;
  97745. if (_this._scene.activeCamera.devicePosition) {
  97746. cameraPos = _this._scene.activeCamera.devicePosition;
  97747. }
  97748. var facing = _this._closestFace(cameraPos.subtract(target.position));
  97749. if (_this._scene.activeCamera.leftCamera) {
  97750. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  97751. }
  97752. else {
  97753. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  97754. }
  97755. // Get camera up direction
  97756. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  97757. // Ignore faces to not select a parrelel face for the up vector of the UI
  97758. _this._faceVectors.forEach(function (v) {
  97759. if (facing.direction.x && v.direction.x) {
  97760. v.ignore = true;
  97761. }
  97762. if (facing.direction.y && v.direction.y) {
  97763. v.ignore = true;
  97764. }
  97765. if (facing.direction.z && v.direction.z) {
  97766. v.ignore = true;
  97767. }
  97768. });
  97769. var facingUp = _this._closestFace(_this._tmpVector);
  97770. // Unignore faces
  97771. _this._faceVectors.forEach(function (v) {
  97772. v.ignore = false;
  97773. });
  97774. // Position the app bar on that face
  97775. _this.ui.position.copyFrom(target.position);
  97776. if (facing.direction.x) {
  97777. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97778. _this.ui.position.addInPlace(_this._tmpVector);
  97779. }
  97780. if (facing.direction.y) {
  97781. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97782. _this.ui.position.addInPlace(_this._tmpVector);
  97783. }
  97784. if (facing.direction.z) {
  97785. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97786. _this.ui.position.addInPlace(_this._tmpVector);
  97787. }
  97788. // Rotate to be oriented properly to the camera
  97789. if (!_this.ui.rotationQuaternion) {
  97790. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  97791. }
  97792. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  97793. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  97794. // Place ui the correct distance from the bottom of the mesh
  97795. if (facingUp.direction.x) {
  97796. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  97797. }
  97798. if (facingUp.direction.y) {
  97799. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  97800. }
  97801. if (facingUp.direction.z) {
  97802. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  97803. }
  97804. _this.ui.position.addInPlace(_this._tmpVector);
  97805. });
  97806. };
  97807. /**
  97808. * Detaches the behavior from the mesh
  97809. */
  97810. AttachToBoxBehavior.prototype.detach = function () {
  97811. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  97812. };
  97813. return AttachToBoxBehavior;
  97814. }());
  97815. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  97816. })(BABYLON || (BABYLON = {}));
  97817. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  97818. var BABYLON;
  97819. (function (BABYLON) {
  97820. /**
  97821. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  97822. */
  97823. var FadeInOutBehavior = /** @class */ (function () {
  97824. /**
  97825. * Instatiates the FadeInOutBehavior
  97826. */
  97827. function FadeInOutBehavior() {
  97828. var _this = this;
  97829. /**
  97830. * Time in milliseconds to delay before fading in (Default: 0)
  97831. */
  97832. this.delay = 0;
  97833. /**
  97834. * Time in milliseconds for the mesh to fade in (Default: 300)
  97835. */
  97836. this.fadeInTime = 300;
  97837. this._millisecondsPerFrame = 1000 / 60;
  97838. this._hovered = false;
  97839. this._hoverValue = 0;
  97840. this._ownerNode = null;
  97841. this._update = function () {
  97842. if (_this._ownerNode) {
  97843. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  97844. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  97845. if (_this._ownerNode.visibility > 1) {
  97846. _this._setAllVisibility(_this._ownerNode, 1);
  97847. _this._hoverValue = _this.fadeInTime + _this.delay;
  97848. return;
  97849. }
  97850. else if (_this._ownerNode.visibility < 0) {
  97851. _this._setAllVisibility(_this._ownerNode, 0);
  97852. if (_this._hoverValue < 0) {
  97853. _this._hoverValue = 0;
  97854. return;
  97855. }
  97856. }
  97857. setTimeout(_this._update, _this._millisecondsPerFrame);
  97858. }
  97859. };
  97860. }
  97861. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  97862. /**
  97863. * The name of the behavior
  97864. */
  97865. get: function () {
  97866. return "FadeInOut";
  97867. },
  97868. enumerable: true,
  97869. configurable: true
  97870. });
  97871. /**
  97872. * Initializes the behavior
  97873. */
  97874. FadeInOutBehavior.prototype.init = function () {
  97875. };
  97876. /**
  97877. * Attaches the fade behavior on the passed in mesh
  97878. * @param ownerNode The mesh that will be faded in/out once attached
  97879. */
  97880. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  97881. this._ownerNode = ownerNode;
  97882. this._setAllVisibility(this._ownerNode, 0);
  97883. };
  97884. /**
  97885. * Detaches the behavior from the mesh
  97886. */
  97887. FadeInOutBehavior.prototype.detach = function () {
  97888. this._ownerNode = null;
  97889. };
  97890. /**
  97891. * Triggers the mesh to begin fading in or out
  97892. * @param value if the object should fade in or out (true to fade in)
  97893. */
  97894. FadeInOutBehavior.prototype.fadeIn = function (value) {
  97895. this._hovered = value;
  97896. this._update();
  97897. };
  97898. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  97899. var _this = this;
  97900. mesh.visibility = value;
  97901. mesh.getChildMeshes().forEach(function (c) {
  97902. _this._setAllVisibility(c, value);
  97903. });
  97904. };
  97905. return FadeInOutBehavior;
  97906. }());
  97907. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  97908. })(BABYLON || (BABYLON = {}));
  97909. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  97910. var BABYLON;
  97911. (function (BABYLON) {
  97912. /**
  97913. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  97914. */
  97915. var Gizmo = /** @class */ (function () {
  97916. /**
  97917. * Creates a gizmo
  97918. * @param gizmoLayer The utility layer the gizmo will be added to
  97919. */
  97920. function Gizmo(
  97921. /** The utility layer the gizmo will be added to */
  97922. gizmoLayer) {
  97923. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97924. var _this = this;
  97925. this.gizmoLayer = gizmoLayer;
  97926. /**
  97927. * Ratio for the scale of the gizmo (Default: 1)
  97928. */
  97929. this.scaleRatio = 1;
  97930. this._tmpMatrix = new BABYLON.Matrix();
  97931. /**
  97932. * If a custom mesh has been set (Default: false)
  97933. */
  97934. this._customMeshSet = false;
  97935. /**
  97936. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  97937. */
  97938. this.updateGizmoRotationToMatchAttachedMesh = true;
  97939. /**
  97940. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  97941. */
  97942. this.updateGizmoPositionToMatchAttachedMesh = true;
  97943. /**
  97944. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  97945. */
  97946. this._updateScale = true;
  97947. this._interactionsEnabled = true;
  97948. this._tempVector = new BABYLON.Vector3();
  97949. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  97950. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  97951. _this._update();
  97952. });
  97953. this.attachedMesh = null;
  97954. }
  97955. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  97956. /**
  97957. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  97958. * * When set, interactions will be enabled
  97959. */
  97960. get: function () {
  97961. return this._attachedMesh;
  97962. },
  97963. set: function (value) {
  97964. this._attachedMesh = value;
  97965. this._rootMesh.setEnabled(value ? true : false);
  97966. this._attachedMeshChanged(value);
  97967. },
  97968. enumerable: true,
  97969. configurable: true
  97970. });
  97971. /**
  97972. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  97973. * @param mesh The mesh to replace the default mesh of the gizmo
  97974. */
  97975. Gizmo.prototype.setCustomMesh = function (mesh) {
  97976. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  97977. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  97978. }
  97979. this._rootMesh.getChildMeshes().forEach(function (c) {
  97980. c.dispose();
  97981. });
  97982. mesh.parent = this._rootMesh;
  97983. this._customMeshSet = true;
  97984. };
  97985. Gizmo.prototype._attachedMeshChanged = function (value) {
  97986. };
  97987. /**
  97988. * @hidden
  97989. * Updates the gizmo to match the attached mesh's position/rotation
  97990. */
  97991. Gizmo.prototype._update = function () {
  97992. if (this.attachedMesh) {
  97993. if (this.updateGizmoRotationToMatchAttachedMesh) {
  97994. if (!this._rootMesh.rotationQuaternion) {
  97995. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  97996. }
  97997. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  97998. this._tempVector.copyFrom(this.attachedMesh.scaling);
  97999. if (this.attachedMesh.scaling.x < 0) {
  98000. this.attachedMesh.scaling.x *= -1;
  98001. }
  98002. if (this.attachedMesh.scaling.y < 0) {
  98003. this.attachedMesh.scaling.y *= -1;
  98004. }
  98005. if (this.attachedMesh.scaling.z < 0) {
  98006. this.attachedMesh.scaling.z *= -1;
  98007. }
  98008. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  98009. this.attachedMesh.scaling.copyFrom(this._tempVector);
  98010. this.attachedMesh.computeWorldMatrix();
  98011. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  98012. }
  98013. else if (this._rootMesh.rotationQuaternion) {
  98014. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  98015. }
  98016. if (this.updateGizmoPositionToMatchAttachedMesh) {
  98017. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  98018. }
  98019. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  98020. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  98021. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  98022. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  98023. }
  98024. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  98025. var dist = this._tempVector.length() * this.scaleRatio;
  98026. this._rootMesh.scaling.set(dist, dist, dist);
  98027. }
  98028. }
  98029. };
  98030. /**
  98031. * Disposes of the gizmo
  98032. */
  98033. Gizmo.prototype.dispose = function () {
  98034. this._rootMesh.dispose();
  98035. if (this._beforeRenderObserver) {
  98036. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98037. }
  98038. };
  98039. return Gizmo;
  98040. }());
  98041. BABYLON.Gizmo = Gizmo;
  98042. })(BABYLON || (BABYLON = {}));
  98043. //# sourceMappingURL=babylon.gizmo.js.map
  98044. var BABYLON;
  98045. (function (BABYLON) {
  98046. /**
  98047. * Single axis drag gizmo
  98048. */
  98049. var AxisDragGizmo = /** @class */ (function (_super) {
  98050. __extends(AxisDragGizmo, _super);
  98051. /**
  98052. * Creates an AxisDragGizmo
  98053. * @param gizmoLayer The utility layer the gizmo will be added to
  98054. * @param dragAxis The axis which the gizmo will be able to drag on
  98055. * @param color The color of the gizmo
  98056. */
  98057. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  98058. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98059. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98060. var _this = _super.call(this, gizmoLayer) || this;
  98061. _this._pointerObserver = null;
  98062. /**
  98063. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98064. */
  98065. _this.snapDistance = 0;
  98066. /**
  98067. * Event that fires each time the gizmo snaps to a new location.
  98068. * * snapDistance is the the change in distance
  98069. */
  98070. _this.onSnapObservable = new BABYLON.Observable();
  98071. // Create Material
  98072. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98073. coloredMaterial.disableLighting = true;
  98074. coloredMaterial.emissiveColor = color;
  98075. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98076. hoverMaterial.disableLighting = true;
  98077. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98078. // Build mesh on root node
  98079. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98080. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  98081. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98082. arrowTail.color = coloredMaterial.emissiveColor;
  98083. arrow.addChild(arrowMesh);
  98084. arrow.addChild(arrowTail);
  98085. // Position arrow pointing in its drag axis
  98086. arrowMesh.scaling.scaleInPlace(0.05);
  98087. arrowMesh.material = coloredMaterial;
  98088. arrowMesh.rotation.x = Math.PI / 2;
  98089. arrowMesh.position.z += 0.3;
  98090. arrowTail.scaling.scaleInPlace(0.26);
  98091. arrowTail.rotation.x = Math.PI / 2;
  98092. arrowTail.material = coloredMaterial;
  98093. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98094. arrow.scaling.scaleInPlace(1 / 3);
  98095. _this._rootMesh.addChild(arrow);
  98096. var currentSnapDragDistance = 0;
  98097. var tmpVector = new BABYLON.Vector3();
  98098. var tmpSnapEvent = { snapDistance: 0 };
  98099. // Add drag behavior to handle events when the gizmo is dragged
  98100. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98101. _this.dragBehavior.moveAttached = false;
  98102. _this._rootMesh.addBehavior(_this.dragBehavior);
  98103. var localDelta = new BABYLON.Vector3();
  98104. var tmpMatrix = new BABYLON.Matrix();
  98105. _this.dragBehavior.onDragObservable.add(function (event) {
  98106. if (_this.attachedMesh) {
  98107. // Convert delta to local translation if it has a parent
  98108. if (_this.attachedMesh.parent) {
  98109. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98110. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  98111. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  98112. }
  98113. else {
  98114. localDelta.copyFrom(event.delta);
  98115. }
  98116. // Snapping logic
  98117. if (_this.snapDistance == 0) {
  98118. _this.attachedMesh.position.addInPlace(localDelta);
  98119. }
  98120. else {
  98121. currentSnapDragDistance += event.dragDistance;
  98122. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98123. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  98124. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98125. localDelta.normalizeToRef(tmpVector);
  98126. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  98127. _this.attachedMesh.position.addInPlace(tmpVector);
  98128. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98129. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98130. }
  98131. }
  98132. }
  98133. });
  98134. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98135. if (_this._customMeshSet) {
  98136. return;
  98137. }
  98138. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98139. var material = isHovered ? hoverMaterial : coloredMaterial;
  98140. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98141. m.material = material;
  98142. if (m.color) {
  98143. m.color = material.emissiveColor;
  98144. }
  98145. });
  98146. });
  98147. return _this;
  98148. }
  98149. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  98150. if (this.dragBehavior) {
  98151. this.dragBehavior.enabled = value ? true : false;
  98152. }
  98153. };
  98154. /**
  98155. * Disposes of the gizmo
  98156. */
  98157. AxisDragGizmo.prototype.dispose = function () {
  98158. this.onSnapObservable.clear();
  98159. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98160. this.dragBehavior.detach();
  98161. _super.prototype.dispose.call(this);
  98162. };
  98163. return AxisDragGizmo;
  98164. }(BABYLON.Gizmo));
  98165. BABYLON.AxisDragGizmo = AxisDragGizmo;
  98166. })(BABYLON || (BABYLON = {}));
  98167. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  98168. var BABYLON;
  98169. (function (BABYLON) {
  98170. /**
  98171. * Single axis scale gizmo
  98172. */
  98173. var AxisScaleGizmo = /** @class */ (function (_super) {
  98174. __extends(AxisScaleGizmo, _super);
  98175. /**
  98176. * Creates an AxisScaleGizmo
  98177. * @param gizmoLayer The utility layer the gizmo will be added to
  98178. * @param dragAxis The axis which the gizmo will be able to scale on
  98179. * @param color The color of the gizmo
  98180. */
  98181. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  98182. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98183. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98184. var _this = _super.call(this, gizmoLayer) || this;
  98185. _this._pointerObserver = null;
  98186. /**
  98187. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98188. */
  98189. _this.snapDistance = 0;
  98190. /**
  98191. * Event that fires each time the gizmo snaps to a new location.
  98192. * * snapDistance is the the change in distance
  98193. */
  98194. _this.onSnapObservable = new BABYLON.Observable();
  98195. /**
  98196. * If the scaling operation should be done on all axis (default: false)
  98197. */
  98198. _this.uniformScaling = false;
  98199. // Create Material
  98200. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98201. _this._coloredMaterial.disableLighting = true;
  98202. _this._coloredMaterial.emissiveColor = color;
  98203. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98204. hoverMaterial.disableLighting = true;
  98205. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98206. // Build mesh on root node
  98207. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98208. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  98209. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98210. arrowTail.color = _this._coloredMaterial.emissiveColor;
  98211. arrow.addChild(arrowMesh);
  98212. arrow.addChild(arrowTail);
  98213. // Position arrow pointing in its drag axis
  98214. arrowMesh.scaling.scaleInPlace(0.1);
  98215. arrowMesh.material = _this._coloredMaterial;
  98216. arrowMesh.rotation.x = Math.PI / 2;
  98217. arrowMesh.position.z += 0.3;
  98218. arrowTail.scaling.scaleInPlace(0.26);
  98219. arrowTail.rotation.x = Math.PI / 2;
  98220. arrowTail.material = _this._coloredMaterial;
  98221. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98222. _this._rootMesh.addChild(arrow);
  98223. arrow.scaling.scaleInPlace(1 / 3);
  98224. // Add drag behavior to handle events when the gizmo is dragged
  98225. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98226. _this.dragBehavior.moveAttached = false;
  98227. _this._rootMesh.addBehavior(_this.dragBehavior);
  98228. var currentSnapDragDistance = 0;
  98229. var tmpVector = new BABYLON.Vector3();
  98230. var tmpSnapEvent = { snapDistance: 0 };
  98231. _this.dragBehavior.onDragObservable.add(function (event) {
  98232. if (_this.attachedMesh) {
  98233. // Snapping logic
  98234. var snapped = false;
  98235. var dragSteps = 0;
  98236. if (_this.uniformScaling) {
  98237. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  98238. if (tmpVector.y < 0) {
  98239. tmpVector.scaleInPlace(-1);
  98240. }
  98241. }
  98242. else {
  98243. tmpVector.copyFrom(dragAxis);
  98244. }
  98245. if (_this.snapDistance == 0) {
  98246. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  98247. }
  98248. else {
  98249. currentSnapDragDistance += event.dragDistance;
  98250. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98251. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  98252. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98253. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  98254. snapped = true;
  98255. }
  98256. else {
  98257. tmpVector.scaleInPlace(0);
  98258. }
  98259. }
  98260. _this.attachedMesh.scaling.addInPlace(tmpVector);
  98261. if (snapped) {
  98262. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98263. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98264. }
  98265. }
  98266. });
  98267. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98268. if (_this._customMeshSet) {
  98269. return;
  98270. }
  98271. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98272. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  98273. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98274. m.material = material;
  98275. if (m.color) {
  98276. m.color = material.emissiveColor;
  98277. }
  98278. });
  98279. });
  98280. return _this;
  98281. }
  98282. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  98283. if (this.dragBehavior) {
  98284. this.dragBehavior.enabled = value ? true : false;
  98285. }
  98286. };
  98287. /**
  98288. * Disposes of the gizmo
  98289. */
  98290. AxisScaleGizmo.prototype.dispose = function () {
  98291. this.onSnapObservable.clear();
  98292. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98293. this.dragBehavior.detach();
  98294. _super.prototype.dispose.call(this);
  98295. };
  98296. /**
  98297. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  98298. * @param mesh The mesh to replace the default mesh of the gizmo
  98299. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  98300. */
  98301. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  98302. var _this = this;
  98303. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  98304. _super.prototype.setCustomMesh.call(this, mesh);
  98305. if (useGizmoMaterial) {
  98306. this._rootMesh.getChildMeshes().forEach(function (m) {
  98307. m.material = _this._coloredMaterial;
  98308. if (m.color) {
  98309. m.color = _this._coloredMaterial.emissiveColor;
  98310. }
  98311. });
  98312. this._customMeshSet = false;
  98313. }
  98314. };
  98315. return AxisScaleGizmo;
  98316. }(BABYLON.Gizmo));
  98317. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  98318. })(BABYLON || (BABYLON = {}));
  98319. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  98320. var BABYLON;
  98321. (function (BABYLON) {
  98322. /**
  98323. * Single plane rotation gizmo
  98324. */
  98325. var PlaneRotationGizmo = /** @class */ (function (_super) {
  98326. __extends(PlaneRotationGizmo, _super);
  98327. /**
  98328. * Creates a PlaneRotationGizmo
  98329. * @param gizmoLayer The utility layer the gizmo will be added to
  98330. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  98331. * @param color The color of the gizmo
  98332. */
  98333. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  98334. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98335. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98336. var _this = _super.call(this, gizmoLayer) || this;
  98337. _this._pointerObserver = null;
  98338. /**
  98339. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  98340. */
  98341. _this.snapDistance = 0;
  98342. /**
  98343. * Event that fires each time the gizmo snaps to a new location.
  98344. * * snapDistance is the the change in distance
  98345. */
  98346. _this.onSnapObservable = new BABYLON.Observable();
  98347. // Create Material
  98348. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98349. coloredMaterial.disableLighting = true;
  98350. coloredMaterial.emissiveColor = color;
  98351. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98352. hoverMaterial.disableLighting = true;
  98353. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98354. // Build mesh on root node
  98355. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98356. // Create circle out of lines
  98357. var tessellation = 20;
  98358. var radius = 0.8;
  98359. var points = new Array();
  98360. for (var i = 0; i < tessellation; i++) {
  98361. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  98362. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  98363. }
  98364. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  98365. rotationMesh.color = coloredMaterial.emissiveColor;
  98366. // Position arrow pointing in its drag axis
  98367. rotationMesh.scaling.scaleInPlace(0.26);
  98368. rotationMesh.material = coloredMaterial;
  98369. rotationMesh.rotation.x = Math.PI / 2;
  98370. parentMesh.addChild(rotationMesh);
  98371. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  98372. _this._rootMesh.addChild(parentMesh);
  98373. parentMesh.scaling.scaleInPlace(1 / 3);
  98374. // Add drag behavior to handle events when the gizmo is dragged
  98375. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  98376. _this.dragBehavior.moveAttached = false;
  98377. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  98378. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  98379. _this._rootMesh.addBehavior(_this.dragBehavior);
  98380. var lastDragPosition = new BABYLON.Vector3();
  98381. _this.dragBehavior.onDragStartObservable.add(function (e) {
  98382. if (_this.attachedMesh) {
  98383. lastDragPosition.copyFrom(e.dragPlanePoint);
  98384. }
  98385. });
  98386. var rotationMatrix = new BABYLON.Matrix();
  98387. var planeNormalTowardsCamera = new BABYLON.Vector3();
  98388. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  98389. var tmpSnapEvent = { snapDistance: 0 };
  98390. var currentSnapDragDistance = 0;
  98391. var tmpMatrix = new BABYLON.Matrix();
  98392. var tmpVector = new BABYLON.Vector3();
  98393. var amountToRotate = new BABYLON.Quaternion();
  98394. _this.dragBehavior.onDragObservable.add(function (event) {
  98395. if (_this.attachedMesh) {
  98396. if (!_this.attachedMesh.rotationQuaternion) {
  98397. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  98398. }
  98399. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  98400. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  98401. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  98402. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  98403. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  98404. var angle = Math.atan2(cross.length(), dot);
  98405. planeNormalTowardsCamera.copyFrom(planeNormal);
  98406. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  98407. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  98408. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  98409. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  98410. }
  98411. // Flip up vector depending on which side the camera is on
  98412. if (gizmoLayer.utilityLayerScene.activeCamera) {
  98413. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  98414. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  98415. planeNormalTowardsCamera.scaleInPlace(-1);
  98416. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  98417. }
  98418. }
  98419. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  98420. if (halfCircleSide)
  98421. angle = -angle;
  98422. // Snapping logic
  98423. var snapped = false;
  98424. if (_this.snapDistance != 0) {
  98425. currentSnapDragDistance += angle;
  98426. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98427. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  98428. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98429. angle = _this.snapDistance * dragSteps;
  98430. snapped = true;
  98431. }
  98432. else {
  98433. angle = 0;
  98434. }
  98435. }
  98436. // If the mesh has a parent, convert needed world rotation to local rotation
  98437. tmpMatrix.reset();
  98438. if (_this.attachedMesh.parent) {
  98439. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98440. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  98441. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  98442. }
  98443. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  98444. var quaternionCoefficient = Math.sin(angle / 2);
  98445. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  98446. // 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
  98447. if (tmpMatrix.determinant() > 0) {
  98448. amountToRotate.toEulerAnglesToRef(tmpVector);
  98449. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  98450. }
  98451. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  98452. // Rotate selected mesh quaternion over fixed axis
  98453. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  98454. }
  98455. else {
  98456. // Rotate selected mesh quaternion over rotated axis
  98457. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  98458. }
  98459. lastDragPosition.copyFrom(event.dragPlanePoint);
  98460. if (snapped) {
  98461. tmpSnapEvent.snapDistance = angle;
  98462. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98463. }
  98464. }
  98465. });
  98466. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98467. if (_this._customMeshSet) {
  98468. return;
  98469. }
  98470. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98471. var material = isHovered ? hoverMaterial : coloredMaterial;
  98472. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98473. m.material = material;
  98474. if (m.color) {
  98475. m.color = material.emissiveColor;
  98476. }
  98477. });
  98478. });
  98479. return _this;
  98480. }
  98481. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  98482. if (this.dragBehavior) {
  98483. this.dragBehavior.enabled = value ? true : false;
  98484. }
  98485. };
  98486. /**
  98487. * Disposes of the gizmo
  98488. */
  98489. PlaneRotationGizmo.prototype.dispose = function () {
  98490. this.onSnapObservable.clear();
  98491. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98492. this.dragBehavior.detach();
  98493. _super.prototype.dispose.call(this);
  98494. };
  98495. return PlaneRotationGizmo;
  98496. }(BABYLON.Gizmo));
  98497. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  98498. })(BABYLON || (BABYLON = {}));
  98499. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  98500. var BABYLON;
  98501. (function (BABYLON) {
  98502. /**
  98503. * Gizmo that enables dragging a mesh along 3 axis
  98504. */
  98505. var PositionGizmo = /** @class */ (function (_super) {
  98506. __extends(PositionGizmo, _super);
  98507. /**
  98508. * Creates a PositionGizmo
  98509. * @param gizmoLayer The utility layer the gizmo will be added to
  98510. */
  98511. function PositionGizmo(gizmoLayer) {
  98512. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98513. var _this = _super.call(this, gizmoLayer) || this;
  98514. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  98515. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  98516. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  98517. _this.attachedMesh = null;
  98518. return _this;
  98519. }
  98520. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  98521. set: function (mesh) {
  98522. if (this.xGizmo) {
  98523. this.xGizmo.attachedMesh = mesh;
  98524. this.yGizmo.attachedMesh = mesh;
  98525. this.zGizmo.attachedMesh = mesh;
  98526. }
  98527. },
  98528. enumerable: true,
  98529. configurable: true
  98530. });
  98531. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  98532. get: function () {
  98533. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  98534. },
  98535. set: function (value) {
  98536. if (this.xGizmo) {
  98537. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98538. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98539. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98540. }
  98541. },
  98542. enumerable: true,
  98543. configurable: true
  98544. });
  98545. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  98546. get: function () {
  98547. return this.xGizmo.snapDistance;
  98548. },
  98549. /**
  98550. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98551. */
  98552. set: function (value) {
  98553. if (this.xGizmo) {
  98554. this.xGizmo.snapDistance = value;
  98555. this.yGizmo.snapDistance = value;
  98556. this.zGizmo.snapDistance = value;
  98557. }
  98558. },
  98559. enumerable: true,
  98560. configurable: true
  98561. });
  98562. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  98563. get: function () {
  98564. return this.xGizmo.scaleRatio;
  98565. },
  98566. /**
  98567. * Ratio for the scale of the gizmo (Default: 1)
  98568. */
  98569. set: function (value) {
  98570. if (this.xGizmo) {
  98571. this.xGizmo.scaleRatio = value;
  98572. this.yGizmo.scaleRatio = value;
  98573. this.zGizmo.scaleRatio = value;
  98574. }
  98575. },
  98576. enumerable: true,
  98577. configurable: true
  98578. });
  98579. /**
  98580. * Disposes of the gizmo
  98581. */
  98582. PositionGizmo.prototype.dispose = function () {
  98583. this.xGizmo.dispose();
  98584. this.yGizmo.dispose();
  98585. this.zGizmo.dispose();
  98586. };
  98587. /**
  98588. * CustomMeshes are not supported by this gizmo
  98589. * @param mesh The mesh to replace the default mesh of the gizmo
  98590. */
  98591. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  98592. 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)");
  98593. };
  98594. return PositionGizmo;
  98595. }(BABYLON.Gizmo));
  98596. BABYLON.PositionGizmo = PositionGizmo;
  98597. })(BABYLON || (BABYLON = {}));
  98598. //# sourceMappingURL=babylon.positionGizmo.js.map
  98599. var BABYLON;
  98600. (function (BABYLON) {
  98601. /**
  98602. * Gizmo that enables rotating a mesh along 3 axis
  98603. */
  98604. var RotationGizmo = /** @class */ (function (_super) {
  98605. __extends(RotationGizmo, _super);
  98606. /**
  98607. * Creates a RotationGizmo
  98608. * @param gizmoLayer The utility layer the gizmo will be added to
  98609. */
  98610. function RotationGizmo(gizmoLayer) {
  98611. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98612. var _this = _super.call(this, gizmoLayer) || this;
  98613. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  98614. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  98615. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  98616. _this.attachedMesh = null;
  98617. return _this;
  98618. }
  98619. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  98620. set: function (mesh) {
  98621. if (this.xGizmo) {
  98622. this.xGizmo.attachedMesh = mesh;
  98623. this.yGizmo.attachedMesh = mesh;
  98624. this.zGizmo.attachedMesh = mesh;
  98625. }
  98626. },
  98627. enumerable: true,
  98628. configurable: true
  98629. });
  98630. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  98631. get: function () {
  98632. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  98633. },
  98634. set: function (value) {
  98635. if (this.xGizmo) {
  98636. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98637. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98638. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98639. }
  98640. },
  98641. enumerable: true,
  98642. configurable: true
  98643. });
  98644. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  98645. get: function () {
  98646. return this.xGizmo.snapDistance;
  98647. },
  98648. /**
  98649. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98650. */
  98651. set: function (value) {
  98652. if (this.xGizmo) {
  98653. this.xGizmo.snapDistance = value;
  98654. this.yGizmo.snapDistance = value;
  98655. this.zGizmo.snapDistance = value;
  98656. }
  98657. },
  98658. enumerable: true,
  98659. configurable: true
  98660. });
  98661. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  98662. get: function () {
  98663. return this.xGizmo.scaleRatio;
  98664. },
  98665. /**
  98666. * Ratio for the scale of the gizmo (Default: 1)
  98667. */
  98668. set: function (value) {
  98669. if (this.xGizmo) {
  98670. this.xGizmo.scaleRatio = value;
  98671. this.yGizmo.scaleRatio = value;
  98672. this.zGizmo.scaleRatio = value;
  98673. }
  98674. },
  98675. enumerable: true,
  98676. configurable: true
  98677. });
  98678. /**
  98679. * Disposes of the gizmo
  98680. */
  98681. RotationGizmo.prototype.dispose = function () {
  98682. this.xGizmo.dispose();
  98683. this.yGizmo.dispose();
  98684. this.zGizmo.dispose();
  98685. };
  98686. /**
  98687. * CustomMeshes are not supported by this gizmo
  98688. * @param mesh The mesh to replace the default mesh of the gizmo
  98689. */
  98690. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  98691. 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)");
  98692. };
  98693. return RotationGizmo;
  98694. }(BABYLON.Gizmo));
  98695. BABYLON.RotationGizmo = RotationGizmo;
  98696. })(BABYLON || (BABYLON = {}));
  98697. //# sourceMappingURL=babylon.rotationGizmo.js.map
  98698. var BABYLON;
  98699. (function (BABYLON) {
  98700. /**
  98701. * Gizmo that enables scaling a mesh along 3 axis
  98702. */
  98703. var ScaleGizmo = /** @class */ (function (_super) {
  98704. __extends(ScaleGizmo, _super);
  98705. /**
  98706. * Creates a ScaleGizmo
  98707. * @param gizmoLayer The utility layer the gizmo will be added to
  98708. */
  98709. function ScaleGizmo(gizmoLayer) {
  98710. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98711. var _this = _super.call(this, gizmoLayer) || this;
  98712. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  98713. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  98714. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  98715. // Create uniform scale gizmo
  98716. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  98717. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98718. _this.uniformScaleGizmo.uniformScaling = true;
  98719. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  98720. octahedron.scaling.scaleInPlace(0.007);
  98721. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  98722. _this.attachedMesh = null;
  98723. return _this;
  98724. }
  98725. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  98726. set: function (mesh) {
  98727. if (this.xGizmo) {
  98728. this.xGizmo.attachedMesh = mesh;
  98729. this.yGizmo.attachedMesh = mesh;
  98730. this.zGizmo.attachedMesh = mesh;
  98731. this.uniformScaleGizmo.attachedMesh = mesh;
  98732. }
  98733. },
  98734. enumerable: true,
  98735. configurable: true
  98736. });
  98737. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  98738. get: function () {
  98739. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  98740. },
  98741. set: function (value) {
  98742. if (this.xGizmo) {
  98743. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98744. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98745. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98746. }
  98747. },
  98748. enumerable: true,
  98749. configurable: true
  98750. });
  98751. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  98752. get: function () {
  98753. return this.xGizmo.snapDistance;
  98754. },
  98755. /**
  98756. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98757. */
  98758. set: function (value) {
  98759. if (this.xGizmo) {
  98760. this.xGizmo.snapDistance = value;
  98761. this.yGizmo.snapDistance = value;
  98762. this.zGizmo.snapDistance = value;
  98763. this.uniformScaleGizmo.snapDistance = value;
  98764. }
  98765. },
  98766. enumerable: true,
  98767. configurable: true
  98768. });
  98769. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  98770. get: function () {
  98771. return this.xGizmo.scaleRatio;
  98772. },
  98773. /**
  98774. * Ratio for the scale of the gizmo (Default: 1)
  98775. */
  98776. set: function (value) {
  98777. if (this.xGizmo) {
  98778. this.xGizmo.scaleRatio = value;
  98779. this.yGizmo.scaleRatio = value;
  98780. this.zGizmo.scaleRatio = value;
  98781. this.uniformScaleGizmo.scaleRatio = value;
  98782. }
  98783. },
  98784. enumerable: true,
  98785. configurable: true
  98786. });
  98787. /**
  98788. * Disposes of the gizmo
  98789. */
  98790. ScaleGizmo.prototype.dispose = function () {
  98791. this.xGizmo.dispose();
  98792. this.yGizmo.dispose();
  98793. this.zGizmo.dispose();
  98794. this.uniformScaleGizmo.dispose();
  98795. };
  98796. return ScaleGizmo;
  98797. }(BABYLON.Gizmo));
  98798. BABYLON.ScaleGizmo = ScaleGizmo;
  98799. })(BABYLON || (BABYLON = {}));
  98800. //# sourceMappingURL=babylon.scaleGizmo.js.map
  98801. var BABYLON;
  98802. (function (BABYLON) {
  98803. /**
  98804. * Bounding box gizmo
  98805. */
  98806. var BoundingBoxGizmo = /** @class */ (function (_super) {
  98807. __extends(BoundingBoxGizmo, _super);
  98808. /**
  98809. * Creates an BoundingBoxGizmo
  98810. * @param gizmoLayer The utility layer the gizmo will be added to
  98811. * @param color The color of the gizmo
  98812. */
  98813. function BoundingBoxGizmo(color, gizmoLayer) {
  98814. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98815. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  98816. var _this = _super.call(this, gizmoLayer) || this;
  98817. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  98818. _this._renderObserver = null;
  98819. _this._pointerObserver = null;
  98820. _this._scaleDragSpeed = 0.2;
  98821. _this._tmpQuaternion = new BABYLON.Quaternion();
  98822. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  98823. _this._tmpRotationMatrix = new BABYLON.Matrix();
  98824. /**
  98825. * 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)
  98826. */
  98827. _this.ignoreChildren = false;
  98828. /**
  98829. * 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)
  98830. */
  98831. _this.includeChildPredicate = null;
  98832. /**
  98833. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  98834. */
  98835. _this.rotationSphereSize = 0.1;
  98836. /**
  98837. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  98838. */
  98839. _this.scaleBoxSize = 0.1;
  98840. /**
  98841. * 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)
  98842. */
  98843. _this.fixedDragMeshScreenSize = false;
  98844. /**
  98845. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  98846. */
  98847. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  98848. /**
  98849. * Fired when a rotation sphere or scale box is dragged
  98850. */
  98851. _this.onDragStartObservable = new BABYLON.Observable();
  98852. /**
  98853. * Fired when a scale box is dragged
  98854. */
  98855. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  98856. /**
  98857. * Fired when a scale box drag is ended
  98858. */
  98859. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  98860. /**
  98861. * Fired when a rotation sphere is dragged
  98862. */
  98863. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  98864. /**
  98865. * Fired when a rotation sphere drag is ended
  98866. */
  98867. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  98868. /**
  98869. * 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)
  98870. */
  98871. _this.scalePivot = null;
  98872. _this._existingMeshScale = new BABYLON.Vector3();
  98873. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  98874. _this._updateScale = false;
  98875. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  98876. // Create Materials
  98877. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98878. coloredMaterial.disableLighting = true;
  98879. coloredMaterial.emissiveColor = color;
  98880. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98881. hoverColoredMaterial.disableLighting = true;
  98882. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98883. // Build bounding box out of lines
  98884. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98885. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  98886. var lines = [];
  98887. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  98888. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  98889. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  98890. 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));
  98891. 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));
  98892. 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));
  98893. 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));
  98894. 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));
  98895. 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));
  98896. 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));
  98897. 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));
  98898. 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));
  98899. lines.forEach(function (l) {
  98900. l.color = color;
  98901. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  98902. l.isPickable = false;
  98903. _this._lineBoundingBox.addChild(l);
  98904. });
  98905. _this._rootMesh.addChild(_this._lineBoundingBox);
  98906. // Create rotation spheres
  98907. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98908. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  98909. var _loop_1 = function (i_1) {
  98910. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  98911. sphere.rotationQuaternion = new BABYLON.Quaternion();
  98912. sphere.material = coloredMaterial;
  98913. // Drag behavior
  98914. _dragBehavior = new BABYLON.PointerDragBehavior({});
  98915. _dragBehavior.moveAttached = false;
  98916. _dragBehavior.updateDragPlane = false;
  98917. sphere.addBehavior(_dragBehavior);
  98918. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  98919. var totalTurnAmountOfDrag = 0;
  98920. _dragBehavior.onDragStartObservable.add(function (event) {
  98921. startingTurnDirection.copyFrom(sphere.forward);
  98922. totalTurnAmountOfDrag = 0;
  98923. });
  98924. _dragBehavior.onDragObservable.add(function (event) {
  98925. _this.onRotationSphereDragObservable.notifyObservers({});
  98926. if (_this.attachedMesh) {
  98927. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  98928. var worldDragDirection = startingTurnDirection;
  98929. // Project the world right on to the drag plane
  98930. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  98931. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  98932. // project drag delta on to the resulting drag axis and rotate based on that
  98933. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  98934. // Make rotation relative to size of mesh.
  98935. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  98936. // Rotate based on axis
  98937. if (!_this.attachedMesh.rotationQuaternion) {
  98938. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  98939. }
  98940. if (!_this._anchorMesh.rotationQuaternion) {
  98941. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  98942. }
  98943. // Do not allow the object to turn more than a full circle
  98944. totalTurnAmountOfDrag += projectDist;
  98945. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  98946. if (i_1 >= 8) {
  98947. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  98948. }
  98949. else if (i_1 >= 4) {
  98950. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  98951. }
  98952. else {
  98953. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  98954. }
  98955. // Rotate around center of bounding box
  98956. _this._anchorMesh.addChild(_this.attachedMesh);
  98957. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  98958. _this._anchorMesh.removeChild(_this.attachedMesh);
  98959. }
  98960. _this.updateBoundingBox();
  98961. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  98962. }
  98963. });
  98964. // Selection/deselection
  98965. _dragBehavior.onDragStartObservable.add(function () {
  98966. _this.onDragStartObservable.notifyObservers({});
  98967. _this._selectNode(sphere);
  98968. });
  98969. _dragBehavior.onDragEndObservable.add(function () {
  98970. _this.onRotationSphereDragEndObservable.notifyObservers({});
  98971. _this._selectNode(null);
  98972. });
  98973. this_1._rotateSpheresParent.addChild(sphere);
  98974. };
  98975. var this_1 = this, _dragBehavior;
  98976. for (var i_1 = 0; i_1 < 12; i_1++) {
  98977. _loop_1(i_1);
  98978. }
  98979. _this._rootMesh.addChild(_this._rotateSpheresParent);
  98980. // Create scale cubes
  98981. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98982. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  98983. for (var i = 0; i < 2; i++) {
  98984. for (var j = 0; j < 2; j++) {
  98985. var _loop_2 = function () {
  98986. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  98987. box.material = coloredMaterial;
  98988. // Dragging logic
  98989. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  98990. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98991. _dragBehavior.moveAttached = false;
  98992. box.addBehavior(_dragBehavior);
  98993. _dragBehavior.onDragObservable.add(function (event) {
  98994. _this.onScaleBoxDragObservable.notifyObservers({});
  98995. if (_this.attachedMesh) {
  98996. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  98997. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  98998. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  98999. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  99000. _this.updateBoundingBox();
  99001. if (_this.scalePivot) {
  99002. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  99003. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  99004. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  99005. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99006. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99007. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  99008. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99009. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  99010. }
  99011. else {
  99012. // Scale from the position of the opposite corner
  99013. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  99014. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99015. }
  99016. _this._anchorMesh.addChild(_this.attachedMesh);
  99017. _this._anchorMesh.scaling.addInPlace(deltaScale);
  99018. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  99019. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  99020. }
  99021. _this._anchorMesh.removeChild(_this.attachedMesh);
  99022. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99023. }
  99024. });
  99025. // Selection/deselection
  99026. _dragBehavior.onDragStartObservable.add(function () {
  99027. _this.onDragStartObservable.notifyObservers({});
  99028. _this._selectNode(box);
  99029. });
  99030. _dragBehavior.onDragEndObservable.add(function () {
  99031. _this.onScaleBoxDragEndObservable.notifyObservers({});
  99032. _this._selectNode(null);
  99033. });
  99034. this_2._scaleBoxesParent.addChild(box);
  99035. };
  99036. var this_2 = this, _dragBehavior;
  99037. for (var k = 0; k < 2; k++) {
  99038. _loop_2();
  99039. }
  99040. }
  99041. }
  99042. _this._rootMesh.addChild(_this._scaleBoxesParent);
  99043. // Hover color change
  99044. var pointerIds = new Array();
  99045. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99046. if (!pointerIds[pointerInfo.event.pointerId]) {
  99047. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  99048. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  99049. pointerIds[pointerInfo.event.pointerId] = mesh;
  99050. mesh.material = hoverColoredMaterial;
  99051. }
  99052. });
  99053. }
  99054. else {
  99055. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  99056. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  99057. delete pointerIds[pointerInfo.event.pointerId];
  99058. }
  99059. }
  99060. });
  99061. // Update bounding box positions
  99062. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  99063. // Only update the bouding box if scaling has changed
  99064. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  99065. _this.updateBoundingBox();
  99066. }
  99067. });
  99068. _this.updateBoundingBox();
  99069. return _this;
  99070. }
  99071. /** @hidden */
  99072. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  99073. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  99074. // Save old pivot and set pivot to 0,0,0
  99075. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  99076. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  99077. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  99078. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  99079. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99080. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99081. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99082. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  99083. }
  99084. }
  99085. BoundingBoxGizmo._PivotCached++;
  99086. };
  99087. /** @hidden */
  99088. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  99089. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  99090. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  99091. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99092. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99093. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99094. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  99095. }
  99096. this._PivotCached--;
  99097. };
  99098. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  99099. if (value) {
  99100. // Reset anchor mesh to match attached mesh's scale
  99101. // This is needed to avoid invalid box/sphere position on first drag
  99102. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  99103. this._anchorMesh.addChild(value);
  99104. this._anchorMesh.removeChild(value);
  99105. BoundingBoxGizmo._RestorePivotPoint(value);
  99106. this.updateBoundingBox();
  99107. }
  99108. };
  99109. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  99110. this._rotateSpheresParent.getChildMeshes()
  99111. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  99112. m.isVisible = (!selectedMesh || m == selectedMesh);
  99113. });
  99114. };
  99115. /**
  99116. * Updates the bounding box information for the Gizmo
  99117. */
  99118. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  99119. if (this.attachedMesh) {
  99120. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  99121. this._update();
  99122. // Rotate based on axis
  99123. if (!this.attachedMesh.rotationQuaternion) {
  99124. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  99125. }
  99126. if (!this._anchorMesh.rotationQuaternion) {
  99127. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  99128. }
  99129. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99130. // Store original position and reset mesh to origin before computing the bounding box
  99131. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99132. this._tmpVector.copyFrom(this.attachedMesh.position);
  99133. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  99134. this.attachedMesh.position.set(0, 0, 0);
  99135. // Update bounding dimensions/positions
  99136. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  99137. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  99138. // Update gizmo to match bounding box scaling and rotation
  99139. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  99140. 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);
  99141. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  99142. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  99143. this._lineBoundingBox.computeWorldMatrix();
  99144. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  99145. // restore position/rotation values
  99146. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  99147. this.attachedMesh.position.copyFrom(this._tmpVector);
  99148. }
  99149. // Update rotation sphere locations
  99150. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  99151. for (var i = 0; i < 3; i++) {
  99152. for (var j = 0; j < 2; j++) {
  99153. for (var k = 0; k < 2; k++) {
  99154. var index = ((i * 4) + (j * 2)) + k;
  99155. if (i == 0) {
  99156. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99157. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99158. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99159. }
  99160. if (i == 1) {
  99161. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  99162. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99163. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99164. }
  99165. if (i == 2) {
  99166. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  99167. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99168. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99169. }
  99170. if (this.fixedDragMeshScreenSize) {
  99171. this._rootMesh.computeWorldMatrix();
  99172. this._rotateSpheresParent.computeWorldMatrix();
  99173. rotateSpheres[index].computeWorldMatrix();
  99174. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  99175. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  99176. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  99177. }
  99178. else {
  99179. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  99180. }
  99181. }
  99182. }
  99183. }
  99184. // Update scale box locations
  99185. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  99186. for (var i = 0; i < 2; i++) {
  99187. for (var j = 0; j < 2; j++) {
  99188. for (var k = 0; k < 2; k++) {
  99189. var index = ((i * 4) + (j * 2)) + k;
  99190. if (scaleBoxes[index]) {
  99191. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99192. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99193. if (this.fixedDragMeshScreenSize) {
  99194. this._rootMesh.computeWorldMatrix();
  99195. this._scaleBoxesParent.computeWorldMatrix();
  99196. scaleBoxes[index].computeWorldMatrix();
  99197. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  99198. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  99199. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  99200. }
  99201. else {
  99202. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  99203. }
  99204. }
  99205. }
  99206. }
  99207. }
  99208. if (this.attachedMesh) {
  99209. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  99210. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  99211. }
  99212. };
  99213. /**
  99214. * Enables rotation on the specified axis and disables rotation on the others
  99215. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  99216. */
  99217. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  99218. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  99219. if (i < 4) {
  99220. m.setEnabled(axis.indexOf("x") != -1);
  99221. }
  99222. else if (i < 8) {
  99223. m.setEnabled(axis.indexOf("y") != -1);
  99224. }
  99225. else {
  99226. m.setEnabled(axis.indexOf("z") != -1);
  99227. }
  99228. });
  99229. };
  99230. /**
  99231. * Disposes of the gizmo
  99232. */
  99233. BoundingBoxGizmo.prototype.dispose = function () {
  99234. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99235. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  99236. this._lineBoundingBox.dispose();
  99237. this._rotateSpheresParent.dispose();
  99238. this._scaleBoxesParent.dispose();
  99239. _super.prototype.dispose.call(this);
  99240. };
  99241. /**
  99242. * 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)
  99243. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  99244. * @returns the bounding box mesh with the passed in mesh as a child
  99245. */
  99246. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  99247. var makeNotPickable = function (root) {
  99248. root.isPickable = false;
  99249. root.getChildMeshes().forEach(function (c) {
  99250. makeNotPickable(c);
  99251. });
  99252. };
  99253. makeNotPickable(mesh);
  99254. // Reset position to get boudning box from origin with no rotation
  99255. if (!mesh.rotationQuaternion) {
  99256. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  99257. }
  99258. var oldPos = mesh.position.clone();
  99259. var oldRot = mesh.rotationQuaternion.clone();
  99260. mesh.rotationQuaternion.set(0, 0, 0, 1);
  99261. mesh.position.set(0, 0, 0);
  99262. // Update bounding dimensions/positions
  99263. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  99264. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  99265. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  99266. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  99267. // Restore original positions
  99268. mesh.addChild(box);
  99269. mesh.rotationQuaternion.copyFrom(oldRot);
  99270. mesh.position.copyFrom(oldPos);
  99271. // Reverse parenting
  99272. mesh.removeChild(box);
  99273. box.addChild(mesh);
  99274. box.visibility = 0;
  99275. return box;
  99276. };
  99277. /**
  99278. * CustomMeshes are not supported by this gizmo
  99279. * @param mesh The mesh to replace the default mesh of the gizmo
  99280. */
  99281. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  99282. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  99283. };
  99284. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  99285. // store/remove pivot point should only be applied during their outermost calls
  99286. BoundingBoxGizmo._PivotCached = 0;
  99287. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  99288. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  99289. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  99290. return BoundingBoxGizmo;
  99291. }(BABYLON.Gizmo));
  99292. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  99293. })(BABYLON || (BABYLON = {}));
  99294. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  99295. var BABYLON;
  99296. (function (BABYLON) {
  99297. /**
  99298. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  99299. */
  99300. var GizmoManager = /** @class */ (function () {
  99301. /**
  99302. * Instatiates a gizmo manager
  99303. * @param scene the scene to overlay the gizmos on top of
  99304. */
  99305. function GizmoManager(scene) {
  99306. var _this = this;
  99307. this.scene = scene;
  99308. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  99309. this._pointerObserver = null;
  99310. this._attachedMesh = null;
  99311. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  99312. /**
  99313. * When bounding box gizmo is enabled, this can be used to track drag/end events
  99314. */
  99315. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  99316. /**
  99317. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  99318. */
  99319. this.attachableMeshes = null;
  99320. /**
  99321. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  99322. */
  99323. this.usePointerToAttachGizmos = true;
  99324. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  99325. // Instatiate/dispose gizmos based on pointer actions
  99326. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  99327. if (!_this.usePointerToAttachGizmos) {
  99328. return;
  99329. }
  99330. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99331. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  99332. var node = pointerInfo.pickInfo.pickedMesh;
  99333. if (_this.attachableMeshes == null) {
  99334. // Attach to the most parent node
  99335. while (node && node.parent != null) {
  99336. node = node.parent;
  99337. }
  99338. }
  99339. else {
  99340. // Attach to the parent node that is an attachableMesh
  99341. var found = false;
  99342. _this.attachableMeshes.forEach(function (mesh) {
  99343. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  99344. node = mesh;
  99345. found = true;
  99346. }
  99347. });
  99348. if (!found) {
  99349. node = null;
  99350. }
  99351. }
  99352. if (node instanceof BABYLON.AbstractMesh) {
  99353. _this.attachToMesh(node);
  99354. }
  99355. else {
  99356. _this.attachToMesh(null);
  99357. }
  99358. }
  99359. else {
  99360. _this.attachToMesh(null);
  99361. }
  99362. }
  99363. });
  99364. }
  99365. /**
  99366. * Attaches a set of gizmos to the specified mesh
  99367. * @param mesh The mesh the gizmo's should be attached to
  99368. */
  99369. GizmoManager.prototype.attachToMesh = function (mesh) {
  99370. if (this._attachedMesh) {
  99371. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  99372. }
  99373. this._attachedMesh = mesh;
  99374. for (var key in this.gizmos) {
  99375. var gizmo = (this.gizmos[key]);
  99376. if (gizmo && this._gizmosEnabled[key]) {
  99377. gizmo.attachedMesh = mesh;
  99378. }
  99379. }
  99380. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  99381. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  99382. }
  99383. };
  99384. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  99385. get: function () {
  99386. return this._gizmosEnabled.positionGizmo;
  99387. },
  99388. /**
  99389. * If the position gizmo is enabled
  99390. */
  99391. set: function (value) {
  99392. if (value) {
  99393. if (!this.gizmos.positionGizmo) {
  99394. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  99395. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99396. }
  99397. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  99398. }
  99399. else if (this.gizmos.positionGizmo) {
  99400. this.gizmos.positionGizmo.attachedMesh = null;
  99401. }
  99402. this._gizmosEnabled.positionGizmo = value;
  99403. },
  99404. enumerable: true,
  99405. configurable: true
  99406. });
  99407. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  99408. get: function () {
  99409. return this._gizmosEnabled.rotationGizmo;
  99410. },
  99411. /**
  99412. * If the rotation gizmo is enabled
  99413. */
  99414. set: function (value) {
  99415. if (value) {
  99416. if (!this.gizmos.rotationGizmo) {
  99417. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  99418. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99419. }
  99420. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  99421. }
  99422. else if (this.gizmos.rotationGizmo) {
  99423. this.gizmos.rotationGizmo.attachedMesh = null;
  99424. }
  99425. this._gizmosEnabled.rotationGizmo = value;
  99426. },
  99427. enumerable: true,
  99428. configurable: true
  99429. });
  99430. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  99431. get: function () {
  99432. return this._gizmosEnabled.scaleGizmo;
  99433. },
  99434. /**
  99435. * If the scale gizmo is enabled
  99436. */
  99437. set: function (value) {
  99438. if (value) {
  99439. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  99440. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  99441. }
  99442. else if (this.gizmos.scaleGizmo) {
  99443. this.gizmos.scaleGizmo.attachedMesh = null;
  99444. }
  99445. this._gizmosEnabled.scaleGizmo = value;
  99446. },
  99447. enumerable: true,
  99448. configurable: true
  99449. });
  99450. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  99451. get: function () {
  99452. return this._gizmosEnabled.boundingBoxGizmo;
  99453. },
  99454. /**
  99455. * If the boundingBox gizmo is enabled
  99456. */
  99457. set: function (value) {
  99458. if (value) {
  99459. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  99460. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  99461. if (this._attachedMesh) {
  99462. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  99463. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  99464. }
  99465. }
  99466. else if (this.gizmos.boundingBoxGizmo) {
  99467. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  99468. }
  99469. this._gizmosEnabled.boundingBoxGizmo = value;
  99470. },
  99471. enumerable: true,
  99472. configurable: true
  99473. });
  99474. /**
  99475. * Disposes of the gizmo manager
  99476. */
  99477. GizmoManager.prototype.dispose = function () {
  99478. this.scene.onPointerObservable.remove(this._pointerObserver);
  99479. for (var key in this.gizmos) {
  99480. var gizmo = (this.gizmos[key]);
  99481. if (gizmo) {
  99482. gizmo.dispose();
  99483. }
  99484. }
  99485. this.boundingBoxDragBehavior.detach();
  99486. };
  99487. return GizmoManager;
  99488. }());
  99489. BABYLON.GizmoManager = GizmoManager;
  99490. })(BABYLON || (BABYLON = {}));
  99491. //# sourceMappingURL=babylon.gizmoManager.js.map
  99492. var BABYLON;
  99493. (function (BABYLON) {
  99494. /**
  99495. * Defines a target to use with MorphTargetManager
  99496. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  99497. */
  99498. var MorphTarget = /** @class */ (function () {
  99499. /**
  99500. * Creates a new MorphTarget
  99501. * @param name defines the name of the target
  99502. * @param influence defines the influence to use
  99503. */
  99504. function MorphTarget(
  99505. /** defines the name of the target */
  99506. name, influence, scene) {
  99507. if (influence === void 0) { influence = 0; }
  99508. if (scene === void 0) { scene = null; }
  99509. this.name = name;
  99510. /**
  99511. * Gets or sets the list of animations
  99512. */
  99513. this.animations = new Array();
  99514. this._positions = null;
  99515. this._normals = null;
  99516. this._tangents = null;
  99517. /**
  99518. * Observable raised when the influence changes
  99519. */
  99520. this.onInfluenceChanged = new BABYLON.Observable();
  99521. this._animationPropertiesOverride = null;
  99522. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99523. this.influence = influence;
  99524. }
  99525. Object.defineProperty(MorphTarget.prototype, "influence", {
  99526. /**
  99527. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  99528. */
  99529. get: function () {
  99530. return this._influence;
  99531. },
  99532. set: function (influence) {
  99533. if (this._influence === influence) {
  99534. return;
  99535. }
  99536. var previous = this._influence;
  99537. this._influence = influence;
  99538. if (this.onInfluenceChanged.hasObservers) {
  99539. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  99540. }
  99541. },
  99542. enumerable: true,
  99543. configurable: true
  99544. });
  99545. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  99546. /**
  99547. * Gets or sets the animation properties override
  99548. */
  99549. get: function () {
  99550. if (!this._animationPropertiesOverride && this._scene) {
  99551. return this._scene.animationPropertiesOverride;
  99552. }
  99553. return this._animationPropertiesOverride;
  99554. },
  99555. set: function (value) {
  99556. this._animationPropertiesOverride = value;
  99557. },
  99558. enumerable: true,
  99559. configurable: true
  99560. });
  99561. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  99562. /**
  99563. * Gets a boolean defining if the target contains position data
  99564. */
  99565. get: function () {
  99566. return !!this._positions;
  99567. },
  99568. enumerable: true,
  99569. configurable: true
  99570. });
  99571. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  99572. /**
  99573. * Gets a boolean defining if the target contains normal data
  99574. */
  99575. get: function () {
  99576. return !!this._normals;
  99577. },
  99578. enumerable: true,
  99579. configurable: true
  99580. });
  99581. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  99582. /**
  99583. * Gets a boolean defining if the target contains tangent data
  99584. */
  99585. get: function () {
  99586. return !!this._tangents;
  99587. },
  99588. enumerable: true,
  99589. configurable: true
  99590. });
  99591. /**
  99592. * Affects position data to this target
  99593. * @param data defines the position data to use
  99594. */
  99595. MorphTarget.prototype.setPositions = function (data) {
  99596. this._positions = data;
  99597. };
  99598. /**
  99599. * Gets the position data stored in this target
  99600. * @returns a FloatArray containing the position data (or null if not present)
  99601. */
  99602. MorphTarget.prototype.getPositions = function () {
  99603. return this._positions;
  99604. };
  99605. /**
  99606. * Affects normal data to this target
  99607. * @param data defines the normal data to use
  99608. */
  99609. MorphTarget.prototype.setNormals = function (data) {
  99610. this._normals = data;
  99611. };
  99612. /**
  99613. * Gets the normal data stored in this target
  99614. * @returns a FloatArray containing the normal data (or null if not present)
  99615. */
  99616. MorphTarget.prototype.getNormals = function () {
  99617. return this._normals;
  99618. };
  99619. /**
  99620. * Affects tangent data to this target
  99621. * @param data defines the tangent data to use
  99622. */
  99623. MorphTarget.prototype.setTangents = function (data) {
  99624. this._tangents = data;
  99625. };
  99626. /**
  99627. * Gets the tangent data stored in this target
  99628. * @returns a FloatArray containing the tangent data (or null if not present)
  99629. */
  99630. MorphTarget.prototype.getTangents = function () {
  99631. return this._tangents;
  99632. };
  99633. /**
  99634. * Serializes the current target into a Serialization object
  99635. * @returns the serialized object
  99636. */
  99637. MorphTarget.prototype.serialize = function () {
  99638. var serializationObject = {};
  99639. serializationObject.name = this.name;
  99640. serializationObject.influence = this.influence;
  99641. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  99642. if (this.hasNormals) {
  99643. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  99644. }
  99645. if (this.hasTangents) {
  99646. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  99647. }
  99648. // Animations
  99649. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  99650. return serializationObject;
  99651. };
  99652. // Statics
  99653. /**
  99654. * Creates a new target from serialized data
  99655. * @param serializationObject defines the serialized data to use
  99656. * @returns a new MorphTarget
  99657. */
  99658. MorphTarget.Parse = function (serializationObject) {
  99659. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  99660. result.setPositions(serializationObject.positions);
  99661. if (serializationObject.normals) {
  99662. result.setNormals(serializationObject.normals);
  99663. }
  99664. if (serializationObject.tangents) {
  99665. result.setTangents(serializationObject.tangents);
  99666. }
  99667. // Animations
  99668. if (serializationObject.animations) {
  99669. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  99670. var parsedAnimation = serializationObject.animations[animationIndex];
  99671. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  99672. }
  99673. }
  99674. return result;
  99675. };
  99676. /**
  99677. * Creates a MorphTarget from mesh data
  99678. * @param mesh defines the source mesh
  99679. * @param name defines the name to use for the new target
  99680. * @param influence defines the influence to attach to the target
  99681. * @returns a new MorphTarget
  99682. */
  99683. MorphTarget.FromMesh = function (mesh, name, influence) {
  99684. if (!name) {
  99685. name = mesh.name;
  99686. }
  99687. var result = new MorphTarget(name, influence, mesh.getScene());
  99688. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  99689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  99690. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  99691. }
  99692. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  99693. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  99694. }
  99695. return result;
  99696. };
  99697. return MorphTarget;
  99698. }());
  99699. BABYLON.MorphTarget = MorphTarget;
  99700. })(BABYLON || (BABYLON = {}));
  99701. //# sourceMappingURL=babylon.morphTarget.js.map
  99702. var BABYLON;
  99703. (function (BABYLON) {
  99704. /**
  99705. * This class is used to deform meshes using morphing between different targets
  99706. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  99707. */
  99708. var MorphTargetManager = /** @class */ (function () {
  99709. /**
  99710. * Creates a new MorphTargetManager
  99711. * @param scene defines the current scene
  99712. */
  99713. function MorphTargetManager(scene) {
  99714. if (scene === void 0) { scene = null; }
  99715. this._targets = new Array();
  99716. this._targetObservable = new Array();
  99717. this._activeTargets = new BABYLON.SmartArray(16);
  99718. this._supportsNormals = false;
  99719. this._supportsTangents = false;
  99720. this._vertexCount = 0;
  99721. this._uniqueId = 0;
  99722. this._tempInfluences = new Array();
  99723. if (!scene) {
  99724. scene = BABYLON.Engine.LastCreatedScene;
  99725. }
  99726. this._scene = scene;
  99727. if (this._scene) {
  99728. this._scene.morphTargetManagers.push(this);
  99729. this._uniqueId = this._scene.getUniqueId();
  99730. }
  99731. }
  99732. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  99733. /**
  99734. * Gets the unique ID of this manager
  99735. */
  99736. get: function () {
  99737. return this._uniqueId;
  99738. },
  99739. enumerable: true,
  99740. configurable: true
  99741. });
  99742. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  99743. /**
  99744. * Gets the number of vertices handled by this manager
  99745. */
  99746. get: function () {
  99747. return this._vertexCount;
  99748. },
  99749. enumerable: true,
  99750. configurable: true
  99751. });
  99752. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  99753. /**
  99754. * Gets a boolean indicating if this manager supports morphing of normals
  99755. */
  99756. get: function () {
  99757. return this._supportsNormals;
  99758. },
  99759. enumerable: true,
  99760. configurable: true
  99761. });
  99762. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  99763. /**
  99764. * Gets a boolean indicating if this manager supports morphing of tangents
  99765. */
  99766. get: function () {
  99767. return this._supportsTangents;
  99768. },
  99769. enumerable: true,
  99770. configurable: true
  99771. });
  99772. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  99773. /**
  99774. * Gets the number of targets stored in this manager
  99775. */
  99776. get: function () {
  99777. return this._targets.length;
  99778. },
  99779. enumerable: true,
  99780. configurable: true
  99781. });
  99782. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  99783. /**
  99784. * Gets the number of influencers (ie. the number of targets with influences > 0)
  99785. */
  99786. get: function () {
  99787. return this._activeTargets.length;
  99788. },
  99789. enumerable: true,
  99790. configurable: true
  99791. });
  99792. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  99793. /**
  99794. * Gets the list of influences (one per target)
  99795. */
  99796. get: function () {
  99797. return this._influences;
  99798. },
  99799. enumerable: true,
  99800. configurable: true
  99801. });
  99802. /**
  99803. * Gets the active target at specified index. An active target is a target with an influence > 0
  99804. * @param index defines the index to check
  99805. * @returns the requested target
  99806. */
  99807. MorphTargetManager.prototype.getActiveTarget = function (index) {
  99808. return this._activeTargets.data[index];
  99809. };
  99810. /**
  99811. * Gets the target at specified index
  99812. * @param index defines the index to check
  99813. * @returns the requested target
  99814. */
  99815. MorphTargetManager.prototype.getTarget = function (index) {
  99816. return this._targets[index];
  99817. };
  99818. /**
  99819. * Add a new target to this manager
  99820. * @param target defines the target to add
  99821. */
  99822. MorphTargetManager.prototype.addTarget = function (target) {
  99823. var _this = this;
  99824. this._targets.push(target);
  99825. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  99826. _this._syncActiveTargets(needUpdate);
  99827. }));
  99828. this._syncActiveTargets(true);
  99829. };
  99830. /**
  99831. * Removes a target from the manager
  99832. * @param target defines the target to remove
  99833. */
  99834. MorphTargetManager.prototype.removeTarget = function (target) {
  99835. var index = this._targets.indexOf(target);
  99836. if (index >= 0) {
  99837. this._targets.splice(index, 1);
  99838. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  99839. this._syncActiveTargets(true);
  99840. }
  99841. };
  99842. /**
  99843. * Serializes the current manager into a Serialization object
  99844. * @returns the serialized object
  99845. */
  99846. MorphTargetManager.prototype.serialize = function () {
  99847. var serializationObject = {};
  99848. serializationObject.id = this.uniqueId;
  99849. serializationObject.targets = [];
  99850. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99851. var target = _a[_i];
  99852. serializationObject.targets.push(target.serialize());
  99853. }
  99854. return serializationObject;
  99855. };
  99856. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  99857. var influenceCount = 0;
  99858. this._activeTargets.reset();
  99859. this._supportsNormals = true;
  99860. this._supportsTangents = true;
  99861. this._vertexCount = 0;
  99862. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99863. var target = _a[_i];
  99864. this._activeTargets.push(target);
  99865. this._tempInfluences[influenceCount++] = target.influence;
  99866. var positions = target.getPositions();
  99867. if (positions) {
  99868. this._supportsNormals = this._supportsNormals && target.hasNormals;
  99869. this._supportsTangents = this._supportsTangents && target.hasTangents;
  99870. var vertexCount = positions.length / 3;
  99871. if (this._vertexCount === 0) {
  99872. this._vertexCount = vertexCount;
  99873. }
  99874. else if (this._vertexCount !== vertexCount) {
  99875. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  99876. return;
  99877. }
  99878. }
  99879. }
  99880. if (!this._influences || this._influences.length !== influenceCount) {
  99881. this._influences = new Float32Array(influenceCount);
  99882. }
  99883. for (var index = 0; index < influenceCount; index++) {
  99884. this._influences[index] = this._tempInfluences[index];
  99885. }
  99886. if (needUpdate) {
  99887. this.synchronize();
  99888. }
  99889. };
  99890. /**
  99891. * Syncrhonize the targets with all the meshes using this morph target manager
  99892. */
  99893. MorphTargetManager.prototype.synchronize = function () {
  99894. if (!this._scene) {
  99895. return;
  99896. }
  99897. // Flag meshes as dirty to resync with the active targets
  99898. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  99899. var mesh = _a[_i];
  99900. if (mesh.morphTargetManager === this) {
  99901. mesh._syncGeometryWithMorphTargetManager();
  99902. }
  99903. }
  99904. };
  99905. // Statics
  99906. /**
  99907. * Creates a new MorphTargetManager from serialized data
  99908. * @param serializationObject defines the serialized data
  99909. * @param scene defines the hosting scene
  99910. * @returns the new MorphTargetManager
  99911. */
  99912. MorphTargetManager.Parse = function (serializationObject, scene) {
  99913. var result = new MorphTargetManager(scene);
  99914. result._uniqueId = serializationObject.id;
  99915. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  99916. var targetData = _a[_i];
  99917. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  99918. }
  99919. return result;
  99920. };
  99921. return MorphTargetManager;
  99922. }());
  99923. BABYLON.MorphTargetManager = MorphTargetManager;
  99924. })(BABYLON || (BABYLON = {}));
  99925. //# sourceMappingURL=babylon.morphTargetManager.js.map
  99926. var BABYLON;
  99927. (function (BABYLON) {
  99928. var Octree = /** @class */ (function () {
  99929. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  99930. if (maxDepth === void 0) { maxDepth = 2; }
  99931. this.maxDepth = maxDepth;
  99932. this.dynamicContent = new Array();
  99933. this._maxBlockCapacity = maxBlockCapacity || 64;
  99934. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  99935. this._creationFunc = creationFunc;
  99936. }
  99937. // Methods
  99938. Octree.prototype.update = function (worldMin, worldMax, entries) {
  99939. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  99940. };
  99941. Octree.prototype.addMesh = function (entry) {
  99942. for (var index = 0; index < this.blocks.length; index++) {
  99943. var block = this.blocks[index];
  99944. block.addEntry(entry);
  99945. }
  99946. };
  99947. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  99948. this._selectionContent.reset();
  99949. for (var index = 0; index < this.blocks.length; index++) {
  99950. var block = this.blocks[index];
  99951. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  99952. }
  99953. if (allowDuplicate) {
  99954. this._selectionContent.concat(this.dynamicContent);
  99955. }
  99956. else {
  99957. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99958. }
  99959. return this._selectionContent;
  99960. };
  99961. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  99962. this._selectionContent.reset();
  99963. for (var index = 0; index < this.blocks.length; index++) {
  99964. var block = this.blocks[index];
  99965. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  99966. }
  99967. if (allowDuplicate) {
  99968. this._selectionContent.concat(this.dynamicContent);
  99969. }
  99970. else {
  99971. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99972. }
  99973. return this._selectionContent;
  99974. };
  99975. Octree.prototype.intersectsRay = function (ray) {
  99976. this._selectionContent.reset();
  99977. for (var index = 0; index < this.blocks.length; index++) {
  99978. var block = this.blocks[index];
  99979. block.intersectsRay(ray, this._selectionContent);
  99980. }
  99981. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99982. return this._selectionContent;
  99983. };
  99984. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  99985. target.blocks = new Array();
  99986. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  99987. // Segmenting space
  99988. for (var x = 0; x < 2; x++) {
  99989. for (var y = 0; y < 2; y++) {
  99990. for (var z = 0; z < 2; z++) {
  99991. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  99992. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  99993. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  99994. block.addEntries(entries);
  99995. target.blocks.push(block);
  99996. }
  99997. }
  99998. }
  99999. };
  100000. Octree.CreationFuncForMeshes = function (entry, block) {
  100001. var boundingInfo = entry.getBoundingInfo();
  100002. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100003. block.entries.push(entry);
  100004. }
  100005. };
  100006. Octree.CreationFuncForSubMeshes = function (entry, block) {
  100007. var boundingInfo = entry.getBoundingInfo();
  100008. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100009. block.entries.push(entry);
  100010. }
  100011. };
  100012. return Octree;
  100013. }());
  100014. BABYLON.Octree = Octree;
  100015. })(BABYLON || (BABYLON = {}));
  100016. //# sourceMappingURL=babylon.octree.js.map
  100017. var BABYLON;
  100018. (function (BABYLON) {
  100019. /**
  100020. * Class used to store a cell in an octree
  100021. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100022. */
  100023. var OctreeBlock = /** @class */ (function () {
  100024. /**
  100025. * Creates a new block
  100026. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  100027. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  100028. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100029. * @param depth defines the current depth of this block in the octree
  100030. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  100031. * @param creationFunc defines a callback to call when an element is added to the block
  100032. */
  100033. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  100034. /**
  100035. * Gets the content of the current block
  100036. */
  100037. this.entries = new Array();
  100038. this._boundingVectors = new Array();
  100039. this._capacity = capacity;
  100040. this._depth = depth;
  100041. this._maxDepth = maxDepth;
  100042. this._creationFunc = creationFunc;
  100043. this._minPoint = minPoint;
  100044. this._maxPoint = maxPoint;
  100045. this._boundingVectors.push(minPoint.clone());
  100046. this._boundingVectors.push(maxPoint.clone());
  100047. this._boundingVectors.push(minPoint.clone());
  100048. this._boundingVectors[2].x = maxPoint.x;
  100049. this._boundingVectors.push(minPoint.clone());
  100050. this._boundingVectors[3].y = maxPoint.y;
  100051. this._boundingVectors.push(minPoint.clone());
  100052. this._boundingVectors[4].z = maxPoint.z;
  100053. this._boundingVectors.push(maxPoint.clone());
  100054. this._boundingVectors[5].z = minPoint.z;
  100055. this._boundingVectors.push(maxPoint.clone());
  100056. this._boundingVectors[6].x = minPoint.x;
  100057. this._boundingVectors.push(maxPoint.clone());
  100058. this._boundingVectors[7].y = minPoint.y;
  100059. }
  100060. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  100061. // Property
  100062. /**
  100063. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100064. */
  100065. get: function () {
  100066. return this._capacity;
  100067. },
  100068. enumerable: true,
  100069. configurable: true
  100070. });
  100071. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  100072. /**
  100073. * Gets the minimum vector (in world space) of the block's bounding box
  100074. */
  100075. get: function () {
  100076. return this._minPoint;
  100077. },
  100078. enumerable: true,
  100079. configurable: true
  100080. });
  100081. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  100082. /**
  100083. * Gets the maximum vector (in world space) of the block's bounding box
  100084. */
  100085. get: function () {
  100086. return this._maxPoint;
  100087. },
  100088. enumerable: true,
  100089. configurable: true
  100090. });
  100091. // Methods
  100092. /**
  100093. * Add a new element to this block
  100094. * @param entry defines the element to add
  100095. */
  100096. OctreeBlock.prototype.addEntry = function (entry) {
  100097. if (this.blocks) {
  100098. for (var index = 0; index < this.blocks.length; index++) {
  100099. var block = this.blocks[index];
  100100. block.addEntry(entry);
  100101. }
  100102. return;
  100103. }
  100104. this._creationFunc(entry, this);
  100105. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  100106. this.createInnerBlocks();
  100107. }
  100108. };
  100109. /**
  100110. * Add an array of elements to this block
  100111. * @param entries defines the array of elements to add
  100112. */
  100113. OctreeBlock.prototype.addEntries = function (entries) {
  100114. for (var index = 0; index < entries.length; index++) {
  100115. var mesh = entries[index];
  100116. this.addEntry(mesh);
  100117. }
  100118. };
  100119. /**
  100120. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  100121. * @param frustumPlanes defines the frustum planes to test
  100122. * @param selection defines the array to store current content if selection is positive
  100123. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100124. */
  100125. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  100126. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  100127. if (this.blocks) {
  100128. for (var index = 0; index < this.blocks.length; index++) {
  100129. var block = this.blocks[index];
  100130. block.select(frustumPlanes, selection, allowDuplicate);
  100131. }
  100132. return;
  100133. }
  100134. if (allowDuplicate) {
  100135. selection.concat(this.entries);
  100136. }
  100137. else {
  100138. selection.concatWithNoDuplicate(this.entries);
  100139. }
  100140. }
  100141. };
  100142. /**
  100143. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  100144. * @param sphereCenter defines the bounding sphere center
  100145. * @param sphereRadius defines the bounding sphere radius
  100146. * @param selection defines the array to store current content if selection is positive
  100147. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100148. */
  100149. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  100150. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  100151. if (this.blocks) {
  100152. for (var index = 0; index < this.blocks.length; index++) {
  100153. var block = this.blocks[index];
  100154. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  100155. }
  100156. return;
  100157. }
  100158. if (allowDuplicate) {
  100159. selection.concat(this.entries);
  100160. }
  100161. else {
  100162. selection.concatWithNoDuplicate(this.entries);
  100163. }
  100164. }
  100165. };
  100166. /**
  100167. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  100168. * @param ray defines the ray to test with
  100169. * @param selection defines the array to store current content if selection is positive
  100170. */
  100171. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  100172. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  100173. if (this.blocks) {
  100174. for (var index = 0; index < this.blocks.length; index++) {
  100175. var block = this.blocks[index];
  100176. block.intersectsRay(ray, selection);
  100177. }
  100178. return;
  100179. }
  100180. selection.concatWithNoDuplicate(this.entries);
  100181. }
  100182. };
  100183. /**
  100184. * Subdivide the content into child blocks (this block will then be empty)
  100185. */
  100186. OctreeBlock.prototype.createInnerBlocks = function () {
  100187. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  100188. };
  100189. return OctreeBlock;
  100190. }());
  100191. BABYLON.OctreeBlock = OctreeBlock;
  100192. })(BABYLON || (BABYLON = {}));
  100193. //# sourceMappingURL=babylon.octreeBlock.js.map
  100194. var BABYLON;
  100195. (function (BABYLON) {
  100196. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  100197. if (maxCapacity === void 0) { maxCapacity = 64; }
  100198. if (maxDepth === void 0) { maxDepth = 2; }
  100199. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  100200. if (!component) {
  100201. component = new OctreeSceneComponent(this);
  100202. this._addComponent(component);
  100203. }
  100204. if (!this._selectionOctree) {
  100205. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  100206. }
  100207. var worldExtends = this.getWorldExtends();
  100208. // Update octree
  100209. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  100210. return this._selectionOctree;
  100211. };
  100212. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  100213. get: function () {
  100214. return this._selectionOctree;
  100215. },
  100216. enumerable: true,
  100217. configurable: true
  100218. });
  100219. /**
  100220. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  100221. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  100222. * @param maxCapacity defines the maximum size of each block (64 by default)
  100223. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  100224. * @returns the new octree
  100225. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  100226. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100227. */
  100228. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  100229. if (maxCapacity === void 0) { maxCapacity = 64; }
  100230. if (maxDepth === void 0) { maxDepth = 2; }
  100231. var scene = this.getScene();
  100232. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  100233. if (!component) {
  100234. component = new OctreeSceneComponent(scene);
  100235. scene._addComponent(component);
  100236. }
  100237. if (!this._submeshesOctree) {
  100238. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  100239. }
  100240. this.computeWorldMatrix(true);
  100241. var boundingInfo = this.getBoundingInfo();
  100242. // Update octree
  100243. var bbox = boundingInfo.boundingBox;
  100244. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  100245. return this._submeshesOctree;
  100246. };
  100247. /**
  100248. * Defines the octree scene component responsible to manage any octrees
  100249. * in a given scene.
  100250. */
  100251. var OctreeSceneComponent = /** @class */ (function () {
  100252. /**
  100253. * Creates a new instance of the component for the given scene
  100254. * @param scene Defines the scene to register the component in
  100255. */
  100256. function OctreeSceneComponent(scene) {
  100257. /**
  100258. * The component name helpfull to identify the component in the list of scene components.
  100259. */
  100260. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  100261. /**
  100262. * Indicates if the meshes have been checked to make sure they are isEnabled()
  100263. */
  100264. this.checksIsEnabled = true;
  100265. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  100266. this.scene = scene;
  100267. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  100268. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  100269. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  100270. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  100271. }
  100272. /**
  100273. * Registers the component in a given scene
  100274. */
  100275. OctreeSceneComponent.prototype.register = function () {
  100276. var _this = this;
  100277. this.scene.onMeshRemovedObservable.add(function (mesh) {
  100278. var sceneOctree = _this.scene.selectionOctree;
  100279. if (sceneOctree !== undefined && sceneOctree !== null) {
  100280. var index = sceneOctree.dynamicContent.indexOf(mesh);
  100281. if (index !== -1) {
  100282. sceneOctree.dynamicContent.splice(index, 1);
  100283. }
  100284. }
  100285. });
  100286. this.scene.onMeshImportedObservable.add(function (mesh) {
  100287. var sceneOctree = _this.scene.selectionOctree;
  100288. if (sceneOctree !== undefined && sceneOctree !== null) {
  100289. sceneOctree.addMesh(mesh);
  100290. }
  100291. });
  100292. };
  100293. /**
  100294. * Return the list of active meshes
  100295. * @returns the list of active meshes
  100296. */
  100297. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  100298. if (this.scene._selectionOctree) {
  100299. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  100300. return selection;
  100301. }
  100302. return this.scene._getDefaultMeshCandidates();
  100303. };
  100304. /**
  100305. * Return the list of active sub meshes
  100306. * @param mesh The mesh to get the candidates sub meshes from
  100307. * @returns the list of active sub meshes
  100308. */
  100309. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  100310. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  100311. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  100312. return intersections;
  100313. }
  100314. return this.scene._getDefaultSubMeshCandidates(mesh);
  100315. };
  100316. /**
  100317. * Return the list of sub meshes intersecting with a given local ray
  100318. * @param mesh defines the mesh to find the submesh for
  100319. * @param localRay defines the ray in local space
  100320. * @returns the list of intersecting sub meshes
  100321. */
  100322. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  100323. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  100324. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  100325. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  100326. return intersections;
  100327. }
  100328. return this.scene._getDefaultSubMeshCandidates(mesh);
  100329. };
  100330. /**
  100331. * Return the list of sub meshes colliding with a collider
  100332. * @param mesh defines the mesh to find the submesh for
  100333. * @param collider defines the collider to evaluate the collision against
  100334. * @returns the list of colliding sub meshes
  100335. */
  100336. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  100337. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  100338. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  100339. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  100340. return intersections;
  100341. }
  100342. return this.scene._getDefaultSubMeshCandidates(mesh);
  100343. };
  100344. /**
  100345. * Rebuilds the elements related to this component in case of
  100346. * context lost for instance.
  100347. */
  100348. OctreeSceneComponent.prototype.rebuild = function () {
  100349. // Nothing to do here.
  100350. };
  100351. /**
  100352. * Disposes the component and the associated ressources.
  100353. */
  100354. OctreeSceneComponent.prototype.dispose = function () {
  100355. // Nothing to do here.
  100356. };
  100357. return OctreeSceneComponent;
  100358. }());
  100359. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  100360. })(BABYLON || (BABYLON = {}));
  100361. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  100362. var BABYLON;
  100363. (function (BABYLON) {
  100364. /**
  100365. * Postprocess used to generate anaglyphic rendering
  100366. */
  100367. var AnaglyphPostProcess = /** @class */ (function (_super) {
  100368. __extends(AnaglyphPostProcess, _super);
  100369. /**
  100370. * Creates a new AnaglyphPostProcess
  100371. * @param name defines postprocess name
  100372. * @param options defines creation options or target ratio scale
  100373. * @param rigCameras defines cameras using this postprocess
  100374. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  100375. * @param engine defines hosting engine
  100376. * @param reusable defines if the postprocess will be reused multiple times per frame
  100377. */
  100378. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  100379. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  100380. _this._passedProcess = rigCameras[0]._rigPostProcess;
  100381. _this.onApplyObservable.add(function (effect) {
  100382. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  100383. });
  100384. return _this;
  100385. }
  100386. return AnaglyphPostProcess;
  100387. }(BABYLON.PostProcess));
  100388. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  100389. })(BABYLON || (BABYLON = {}));
  100390. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  100391. var BABYLON;
  100392. (function (BABYLON) {
  100393. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  100394. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100395. });
  100396. /**
  100397. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  100398. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100399. */
  100400. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  100401. __extends(AnaglyphArcRotateCamera, _super);
  100402. /**
  100403. * Creates a new AnaglyphArcRotateCamera
  100404. * @param name defines camera name
  100405. * @param alpha defines alpha angle (in radians)
  100406. * @param beta defines beta angle (in radians)
  100407. * @param radius defines radius
  100408. * @param target defines camera target
  100409. * @param interaxialDistance defines distance between each color axis
  100410. * @param scene defines the hosting scene
  100411. */
  100412. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  100413. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100414. _this.interaxialDistance = interaxialDistance;
  100415. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100416. return _this;
  100417. }
  100418. /**
  100419. * Gets camera class name
  100420. * @returns AnaglyphArcRotateCamera
  100421. */
  100422. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  100423. return "AnaglyphArcRotateCamera";
  100424. };
  100425. return AnaglyphArcRotateCamera;
  100426. }(BABYLON.ArcRotateCamera));
  100427. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  100428. })(BABYLON || (BABYLON = {}));
  100429. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  100430. var BABYLON;
  100431. (function (BABYLON) {
  100432. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  100433. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100434. });
  100435. /**
  100436. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  100437. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100438. */
  100439. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  100440. __extends(AnaglyphFreeCamera, _super);
  100441. /**
  100442. * Creates a new AnaglyphFreeCamera
  100443. * @param name defines camera name
  100444. * @param position defines initial position
  100445. * @param interaxialDistance defines distance between each color axis
  100446. * @param scene defines the hosting scene
  100447. */
  100448. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  100449. var _this = _super.call(this, name, position, scene) || this;
  100450. _this.interaxialDistance = interaxialDistance;
  100451. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100452. return _this;
  100453. }
  100454. /**
  100455. * Gets camera class name
  100456. * @returns AnaglyphFreeCamera
  100457. */
  100458. AnaglyphFreeCamera.prototype.getClassName = function () {
  100459. return "AnaglyphFreeCamera";
  100460. };
  100461. return AnaglyphFreeCamera;
  100462. }(BABYLON.FreeCamera));
  100463. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  100464. })(BABYLON || (BABYLON = {}));
  100465. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  100466. var BABYLON;
  100467. (function (BABYLON) {
  100468. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  100469. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100470. });
  100471. /**
  100472. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  100473. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100474. */
  100475. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  100476. __extends(AnaglyphGamepadCamera, _super);
  100477. /**
  100478. * Creates a new AnaglyphGamepadCamera
  100479. * @param name defines camera name
  100480. * @param position defines initial position
  100481. * @param interaxialDistance defines distance between each color axis
  100482. * @param scene defines the hosting scene
  100483. */
  100484. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  100485. var _this = _super.call(this, name, position, scene) || this;
  100486. _this.interaxialDistance = interaxialDistance;
  100487. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100488. return _this;
  100489. }
  100490. /**
  100491. * Gets camera class name
  100492. * @returns AnaglyphGamepadCamera
  100493. */
  100494. AnaglyphGamepadCamera.prototype.getClassName = function () {
  100495. return "AnaglyphGamepadCamera";
  100496. };
  100497. return AnaglyphGamepadCamera;
  100498. }(BABYLON.GamepadCamera));
  100499. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  100500. })(BABYLON || (BABYLON = {}));
  100501. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  100502. var BABYLON;
  100503. (function (BABYLON) {
  100504. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  100505. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100506. });
  100507. /**
  100508. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  100509. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100510. */
  100511. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  100512. __extends(AnaglyphUniversalCamera, _super);
  100513. /**
  100514. * Creates a new AnaglyphUniversalCamera
  100515. * @param name defines camera name
  100516. * @param position defines initial position
  100517. * @param interaxialDistance defines distance between each color axis
  100518. * @param scene defines the hosting scene
  100519. */
  100520. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  100521. var _this = _super.call(this, name, position, scene) || this;
  100522. _this.interaxialDistance = interaxialDistance;
  100523. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100524. return _this;
  100525. }
  100526. /**
  100527. * Gets camera class name
  100528. * @returns AnaglyphUniversalCamera
  100529. */
  100530. AnaglyphUniversalCamera.prototype.getClassName = function () {
  100531. return "AnaglyphUniversalCamera";
  100532. };
  100533. return AnaglyphUniversalCamera;
  100534. }(BABYLON.UniversalCamera));
  100535. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  100536. })(BABYLON || (BABYLON = {}));
  100537. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  100538. var BABYLON;
  100539. (function (BABYLON) {
  100540. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  100541. __extends(StereoscopicInterlacePostProcess, _super);
  100542. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  100543. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  100544. _this._passedProcess = rigCameras[0]._rigPostProcess;
  100545. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  100546. _this.onSizeChangedObservable.add(function () {
  100547. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  100548. });
  100549. _this.onApplyObservable.add(function (effect) {
  100550. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  100551. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  100552. });
  100553. return _this;
  100554. }
  100555. return StereoscopicInterlacePostProcess;
  100556. }(BABYLON.PostProcess));
  100557. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  100558. })(BABYLON || (BABYLON = {}));
  100559. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  100560. var BABYLON;
  100561. (function (BABYLON) {
  100562. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  100563. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100564. });
  100565. /**
  100566. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  100567. * @see http://doc.babylonjs.com/features/cameras
  100568. */
  100569. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  100570. __extends(StereoscopicArcRotateCamera, _super);
  100571. /**
  100572. * Creates a new StereoscopicArcRotateCamera
  100573. * @param name defines camera name
  100574. * @param alpha defines alpha angle (in radians)
  100575. * @param beta defines beta angle (in radians)
  100576. * @param radius defines radius
  100577. * @param target defines camera target
  100578. * @param interaxialDistance defines distance between each color axis
  100579. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100580. * @param scene defines the hosting scene
  100581. */
  100582. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  100583. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100584. _this.interaxialDistance = interaxialDistance;
  100585. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100586. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100587. return _this;
  100588. }
  100589. /**
  100590. * Gets camera class name
  100591. * @returns StereoscopicArcRotateCamera
  100592. */
  100593. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  100594. return "StereoscopicArcRotateCamera";
  100595. };
  100596. return StereoscopicArcRotateCamera;
  100597. }(BABYLON.ArcRotateCamera));
  100598. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  100599. })(BABYLON || (BABYLON = {}));
  100600. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  100601. var BABYLON;
  100602. (function (BABYLON) {
  100603. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  100604. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100605. });
  100606. /**
  100607. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  100608. * @see http://doc.babylonjs.com/features/cameras
  100609. */
  100610. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  100611. __extends(StereoscopicFreeCamera, _super);
  100612. /**
  100613. * Creates a new StereoscopicFreeCamera
  100614. * @param name defines camera name
  100615. * @param position defines initial position
  100616. * @param interaxialDistance defines distance between each color axis
  100617. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100618. * @param scene defines the hosting scene
  100619. */
  100620. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  100621. var _this = _super.call(this, name, position, scene) || this;
  100622. _this.interaxialDistance = interaxialDistance;
  100623. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100624. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100625. return _this;
  100626. }
  100627. /**
  100628. * Gets camera class name
  100629. * @returns StereoscopicFreeCamera
  100630. */
  100631. StereoscopicFreeCamera.prototype.getClassName = function () {
  100632. return "StereoscopicFreeCamera";
  100633. };
  100634. return StereoscopicFreeCamera;
  100635. }(BABYLON.FreeCamera));
  100636. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  100637. })(BABYLON || (BABYLON = {}));
  100638. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  100639. var BABYLON;
  100640. (function (BABYLON) {
  100641. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  100642. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100643. });
  100644. /**
  100645. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  100646. * @see http://doc.babylonjs.com/features/cameras
  100647. */
  100648. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  100649. __extends(StereoscopicGamepadCamera, _super);
  100650. /**
  100651. * Creates a new StereoscopicGamepadCamera
  100652. * @param name defines camera name
  100653. * @param position defines initial position
  100654. * @param interaxialDistance defines distance between each color axis
  100655. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100656. * @param scene defines the hosting scene
  100657. */
  100658. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  100659. var _this = _super.call(this, name, position, scene) || this;
  100660. _this.interaxialDistance = interaxialDistance;
  100661. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100662. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100663. return _this;
  100664. }
  100665. /**
  100666. * Gets camera class name
  100667. * @returns StereoscopicGamepadCamera
  100668. */
  100669. StereoscopicGamepadCamera.prototype.getClassName = function () {
  100670. return "StereoscopicGamepadCamera";
  100671. };
  100672. return StereoscopicGamepadCamera;
  100673. }(BABYLON.GamepadCamera));
  100674. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  100675. })(BABYLON || (BABYLON = {}));
  100676. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  100677. var BABYLON;
  100678. (function (BABYLON) {
  100679. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  100680. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100681. });
  100682. /**
  100683. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  100684. * @see http://doc.babylonjs.com/features/cameras
  100685. */
  100686. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  100687. __extends(StereoscopicUniversalCamera, _super);
  100688. /**
  100689. * Creates a new StereoscopicUniversalCamera
  100690. * @param name defines camera name
  100691. * @param position defines initial position
  100692. * @param interaxialDistance defines distance between each color axis
  100693. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100694. * @param scene defines the hosting scene
  100695. */
  100696. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  100697. var _this = _super.call(this, name, position, scene) || this;
  100698. _this.interaxialDistance = interaxialDistance;
  100699. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100700. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100701. return _this;
  100702. }
  100703. /**
  100704. * Gets camera class name
  100705. * @returns StereoscopicUniversalCamera
  100706. */
  100707. StereoscopicUniversalCamera.prototype.getClassName = function () {
  100708. return "StereoscopicUniversalCamera";
  100709. };
  100710. return StereoscopicUniversalCamera;
  100711. }(BABYLON.UniversalCamera));
  100712. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  100713. })(BABYLON || (BABYLON = {}));
  100714. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  100715. var BABYLON;
  100716. (function (BABYLON) {
  100717. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  100718. __extends(VRDistortionCorrectionPostProcess, _super);
  100719. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  100720. var _this = _super.call(this, name, "vrDistortionCorrection", [
  100721. 'LensCenter',
  100722. 'Scale',
  100723. 'ScaleIn',
  100724. 'HmdWarpParam'
  100725. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  100726. _this._isRightEye = isRightEye;
  100727. _this._distortionFactors = vrMetrics.distortionK;
  100728. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  100729. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  100730. _this.adaptScaleToCurrentViewport = true;
  100731. _this.onSizeChangedObservable.add(function () {
  100732. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  100733. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  100734. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  100735. });
  100736. _this.onApplyObservable.add(function (effect) {
  100737. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  100738. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  100739. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  100740. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  100741. });
  100742. return _this;
  100743. }
  100744. return VRDistortionCorrectionPostProcess;
  100745. }(BABYLON.PostProcess));
  100746. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  100747. })(BABYLON || (BABYLON = {}));
  100748. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  100749. var BABYLON;
  100750. (function (BABYLON) {
  100751. /**
  100752. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  100753. * Screen rotation is taken into account.
  100754. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100755. */
  100756. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  100757. /**
  100758. * Instantiates a new input
  100759. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100760. */
  100761. function FreeCameraDeviceOrientationInput() {
  100762. var _this = this;
  100763. this._screenOrientationAngle = 0;
  100764. this._screenQuaternion = new BABYLON.Quaternion();
  100765. this._alpha = 0;
  100766. this._beta = 0;
  100767. this._gamma = 0;
  100768. this._orientationChanged = function () {
  100769. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  100770. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  100771. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  100772. };
  100773. this._deviceOrientation = function (evt) {
  100774. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  100775. _this._beta = evt.beta !== null ? evt.beta : 0;
  100776. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  100777. };
  100778. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  100779. this._orientationChanged();
  100780. }
  100781. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  100782. /**
  100783. * Define the camera controlled by the input.
  100784. */
  100785. get: function () {
  100786. return this._camera;
  100787. },
  100788. set: function (camera) {
  100789. this._camera = camera;
  100790. if (this._camera != null && !this._camera.rotationQuaternion) {
  100791. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  100792. }
  100793. },
  100794. enumerable: true,
  100795. configurable: true
  100796. });
  100797. /**
  100798. * Attach the input controls to a specific dom element to get the input from.
  100799. * @param element Defines the element the controls should be listened from
  100800. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100801. */
  100802. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100803. window.addEventListener("orientationchange", this._orientationChanged);
  100804. window.addEventListener("deviceorientation", this._deviceOrientation);
  100805. //In certain cases, the attach control is called AFTER orientation was changed,
  100806. //So this is needed.
  100807. this._orientationChanged();
  100808. };
  100809. /**
  100810. * Detach the current controls from the specified dom element.
  100811. * @param element Defines the element to stop listening the inputs from
  100812. */
  100813. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  100814. window.removeEventListener("orientationchange", this._orientationChanged);
  100815. window.removeEventListener("deviceorientation", this._deviceOrientation);
  100816. };
  100817. /**
  100818. * Update the current camera state depending on the inputs that have been used this frame.
  100819. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100820. */
  100821. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  100822. //if no device orientation provided, don't update the rotation.
  100823. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  100824. if (!this._alpha)
  100825. return;
  100826. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  100827. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  100828. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  100829. //Mirror on XY Plane
  100830. this._camera.rotationQuaternion.z *= -1;
  100831. this._camera.rotationQuaternion.w *= -1;
  100832. };
  100833. /**
  100834. * Gets the class name of the current intput.
  100835. * @returns the class name
  100836. */
  100837. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  100838. return "FreeCameraDeviceOrientationInput";
  100839. };
  100840. /**
  100841. * Get the friendly name associated with the input class.
  100842. * @returns the input friendly name
  100843. */
  100844. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  100845. return "deviceOrientation";
  100846. };
  100847. return FreeCameraDeviceOrientationInput;
  100848. }());
  100849. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  100850. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  100851. })(BABYLON || (BABYLON = {}));
  100852. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  100853. var BABYLON;
  100854. (function (BABYLON) {
  100855. /**
  100856. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  100857. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100858. */
  100859. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  100860. /**
  100861. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  100862. */
  100863. function ArcRotateCameraVRDeviceOrientationInput() {
  100864. /**
  100865. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  100866. */
  100867. this.alphaCorrection = 1;
  100868. /**
  100869. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  100870. */
  100871. this.betaCorrection = 1;
  100872. /**
  100873. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  100874. */
  100875. this.gammaCorrection = 1;
  100876. this._alpha = 0;
  100877. this._gamma = 0;
  100878. this._dirty = false;
  100879. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  100880. }
  100881. /**
  100882. * Attach the input controls to a specific dom element to get the input from.
  100883. * @param element Defines the element the controls should be listened from
  100884. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100885. */
  100886. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100887. this.camera.attachControl(element, noPreventDefault);
  100888. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  100889. };
  100890. /** @hidden */
  100891. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  100892. if (evt.alpha !== null) {
  100893. this._alpha = +evt.alpha | 0;
  100894. }
  100895. if (evt.gamma !== null) {
  100896. this._gamma = +evt.gamma | 0;
  100897. }
  100898. this._dirty = true;
  100899. };
  100900. /**
  100901. * Update the current camera state depending on the inputs that have been used this frame.
  100902. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100903. */
  100904. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  100905. if (this._dirty) {
  100906. this._dirty = false;
  100907. if (this._gamma < 0) {
  100908. this._gamma = 180 + this._gamma;
  100909. }
  100910. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  100911. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  100912. }
  100913. };
  100914. /**
  100915. * Detach the current controls from the specified dom element.
  100916. * @param element Defines the element to stop listening the inputs from
  100917. */
  100918. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  100919. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  100920. };
  100921. /**
  100922. * Gets the class name of the current intput.
  100923. * @returns the class name
  100924. */
  100925. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  100926. return "ArcRotateCameraVRDeviceOrientationInput";
  100927. };
  100928. /**
  100929. * Get the friendly name associated with the input class.
  100930. * @returns the input friendly name
  100931. */
  100932. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  100933. return "VRDeviceOrientation";
  100934. };
  100935. return ArcRotateCameraVRDeviceOrientationInput;
  100936. }());
  100937. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  100938. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  100939. })(BABYLON || (BABYLON = {}));
  100940. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  100941. var BABYLON;
  100942. (function (BABYLON) {
  100943. /**
  100944. * This represents all the required metrics to create a VR camera.
  100945. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  100946. */
  100947. var VRCameraMetrics = /** @class */ (function () {
  100948. function VRCameraMetrics() {
  100949. /**
  100950. * Define if the current vr camera should compensate the distortion of the lense or not.
  100951. */
  100952. this.compensateDistortion = true;
  100953. }
  100954. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  100955. /**
  100956. * Gets the rendering aspect ratio based on the provided resolutions.
  100957. */
  100958. get: function () {
  100959. return this.hResolution / (2 * this.vResolution);
  100960. },
  100961. enumerable: true,
  100962. configurable: true
  100963. });
  100964. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  100965. /**
  100966. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  100967. */
  100968. get: function () {
  100969. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  100970. },
  100971. enumerable: true,
  100972. configurable: true
  100973. });
  100974. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  100975. /**
  100976. * @hidden
  100977. */
  100978. get: function () {
  100979. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  100980. var h = (4 * meters) / this.hScreenSize;
  100981. return BABYLON.Matrix.Translation(h, 0, 0);
  100982. },
  100983. enumerable: true,
  100984. configurable: true
  100985. });
  100986. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  100987. /**
  100988. * @hidden
  100989. */
  100990. get: function () {
  100991. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  100992. var h = (4 * meters) / this.hScreenSize;
  100993. return BABYLON.Matrix.Translation(-h, 0, 0);
  100994. },
  100995. enumerable: true,
  100996. configurable: true
  100997. });
  100998. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  100999. /**
  101000. * @hidden
  101001. */
  101002. get: function () {
  101003. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  101004. },
  101005. enumerable: true,
  101006. configurable: true
  101007. });
  101008. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  101009. /**
  101010. * @hidden
  101011. */
  101012. get: function () {
  101013. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  101014. },
  101015. enumerable: true,
  101016. configurable: true
  101017. });
  101018. /**
  101019. * Get the default VRMetrics based on the most generic setup.
  101020. * @returns the default vr metrics
  101021. */
  101022. VRCameraMetrics.GetDefault = function () {
  101023. var result = new VRCameraMetrics();
  101024. result.hResolution = 1280;
  101025. result.vResolution = 800;
  101026. result.hScreenSize = 0.149759993;
  101027. result.vScreenSize = 0.0935999975;
  101028. result.vScreenCenter = 0.0467999987;
  101029. result.eyeToScreenDistance = 0.0410000011;
  101030. result.lensSeparationDistance = 0.0635000020;
  101031. result.interpupillaryDistance = 0.0640000030;
  101032. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  101033. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  101034. result.postProcessScaleFactor = 1.714605507808412;
  101035. result.lensCenterOffset = 0.151976421;
  101036. return result;
  101037. };
  101038. return VRCameraMetrics;
  101039. }());
  101040. BABYLON.VRCameraMetrics = VRCameraMetrics;
  101041. })(BABYLON || (BABYLON = {}));
  101042. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  101043. var BABYLON;
  101044. (function (BABYLON) {
  101045. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  101046. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101047. });
  101048. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  101049. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101050. });
  101051. /**
  101052. * This represents a WebVR camera.
  101053. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  101054. * @example http://doc.babylonjs.com/how_to/webvr_camera
  101055. */
  101056. var WebVRFreeCamera = /** @class */ (function (_super) {
  101057. __extends(WebVRFreeCamera, _super);
  101058. /**
  101059. * Instantiates a WebVRFreeCamera.
  101060. * @param name The name of the WebVRFreeCamera
  101061. * @param position The starting anchor position for the camera
  101062. * @param scene The scene the camera belongs to
  101063. * @param webVROptions a set of customizable options for the webVRCamera
  101064. */
  101065. function WebVRFreeCamera(name, position, scene, webVROptions) {
  101066. if (webVROptions === void 0) { webVROptions = {}; }
  101067. var _this = _super.call(this, name, position, scene) || this;
  101068. _this.webVROptions = webVROptions;
  101069. /**
  101070. * @hidden
  101071. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  101072. */
  101073. _this._vrDevice = null;
  101074. /**
  101075. * The rawPose of the vrDevice.
  101076. */
  101077. _this.rawPose = null;
  101078. _this._specsVersion = "1.1";
  101079. _this._attached = false;
  101080. _this._descendants = [];
  101081. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  101082. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  101083. /** @hidden */
  101084. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  101085. _this._standingMatrix = null;
  101086. /**
  101087. * Represents device position in babylon space.
  101088. */
  101089. _this.devicePosition = BABYLON.Vector3.Zero();
  101090. /**
  101091. * Represents device rotation in babylon space.
  101092. */
  101093. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  101094. /**
  101095. * The scale of the device to be used when translating from device space to babylon space.
  101096. */
  101097. _this.deviceScaleFactor = 1;
  101098. _this._deviceToWorld = BABYLON.Matrix.Identity();
  101099. _this._worldToDevice = BABYLON.Matrix.Identity();
  101100. /**
  101101. * References to the webVR controllers for the vrDevice.
  101102. */
  101103. _this.controllers = [];
  101104. /**
  101105. * Emits an event when a controller is attached.
  101106. */
  101107. _this.onControllersAttachedObservable = new BABYLON.Observable();
  101108. /**
  101109. * Emits an event when a controller's mesh has been loaded;
  101110. */
  101111. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  101112. /**
  101113. * Emits an event when the HMD's pose has been updated.
  101114. */
  101115. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  101116. _this._poseSet = false;
  101117. /**
  101118. * If the rig cameras be used as parent instead of this camera.
  101119. */
  101120. _this.rigParenting = true;
  101121. _this._defaultHeight = undefined;
  101122. _this._htmlElementAttached = null;
  101123. _this._detachIfAttached = function () {
  101124. var vrDisplay = _this.getEngine().getVRDevice();
  101125. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  101126. _this.detachControl(_this._htmlElementAttached);
  101127. }
  101128. };
  101129. _this._workingVector = BABYLON.Vector3.Zero();
  101130. _this._oneVector = BABYLON.Vector3.One();
  101131. _this._workingMatrix = BABYLON.Matrix.Identity();
  101132. _this._tmpMatrix = new BABYLON.Matrix();
  101133. _this._cache.position = BABYLON.Vector3.Zero();
  101134. if (webVROptions.defaultHeight) {
  101135. _this._defaultHeight = webVROptions.defaultHeight;
  101136. _this.position.y = _this._defaultHeight;
  101137. }
  101138. _this.minZ = 0.1;
  101139. //legacy support - the compensation boolean was removed.
  101140. if (arguments.length === 5) {
  101141. _this.webVROptions = arguments[4];
  101142. }
  101143. // default webVR options
  101144. if (_this.webVROptions.trackPosition == undefined) {
  101145. _this.webVROptions.trackPosition = true;
  101146. }
  101147. if (_this.webVROptions.controllerMeshes == undefined) {
  101148. _this.webVROptions.controllerMeshes = true;
  101149. }
  101150. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  101151. _this.webVROptions.defaultLightingOnControllers = true;
  101152. }
  101153. _this.rotationQuaternion = new BABYLON.Quaternion();
  101154. if (_this.webVROptions && _this.webVROptions.positionScale) {
  101155. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  101156. }
  101157. //enable VR
  101158. var engine = _this.getEngine();
  101159. _this._onVREnabled = function (success) { if (success) {
  101160. _this.initControllers();
  101161. } };
  101162. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  101163. engine.initWebVR().add(function (event) {
  101164. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  101165. return;
  101166. }
  101167. _this._vrDevice = event.vrDisplay;
  101168. //reset the rig parameters.
  101169. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  101170. if (_this._attached) {
  101171. _this.getEngine().enableVR();
  101172. }
  101173. });
  101174. if (typeof (VRFrameData) !== "undefined")
  101175. _this._frameData = new VRFrameData();
  101176. /**
  101177. * The idea behind the following lines:
  101178. * objects that have the camera as parent should actually have the rig cameras as a parent.
  101179. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  101180. * the second will not show it correctly.
  101181. *
  101182. * To solve this - each object that has the camera as parent will be added to a protected array.
  101183. * When the rig camera renders, it will take this array and set all of those to be its children.
  101184. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  101185. * Amazing!
  101186. */
  101187. scene.onBeforeCameraRenderObservable.add(function (camera) {
  101188. if (camera.parent === _this && _this.rigParenting) {
  101189. _this._descendants = _this.getDescendants(true, function (n) {
  101190. // don't take the cameras or the controllers!
  101191. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  101192. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  101193. return !isController && !isRigCamera;
  101194. });
  101195. _this._descendants.forEach(function (node) {
  101196. node.parent = camera;
  101197. });
  101198. }
  101199. });
  101200. scene.onAfterCameraRenderObservable.add(function (camera) {
  101201. if (camera.parent === _this && _this.rigParenting) {
  101202. _this._descendants.forEach(function (node) {
  101203. node.parent = _this;
  101204. });
  101205. }
  101206. });
  101207. return _this;
  101208. }
  101209. /**
  101210. * Gets the device distance from the ground in meters.
  101211. * @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.
  101212. */
  101213. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  101214. if (this._standingMatrix) {
  101215. // Add standing matrix offset to get real offset from ground in room
  101216. this._standingMatrix.getTranslationToRef(this._workingVector);
  101217. return this._deviceRoomPosition.y + this._workingVector.y;
  101218. }
  101219. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  101220. return this._defaultHeight || 0;
  101221. };
  101222. /**
  101223. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  101224. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  101225. */
  101226. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  101227. var _this = this;
  101228. if (callback === void 0) { callback = function (bool) { }; }
  101229. // Use standing matrix if available
  101230. this.getEngine().initWebVRAsync().then(function (result) {
  101231. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  101232. callback(false);
  101233. }
  101234. else {
  101235. _this._standingMatrix = new BABYLON.Matrix();
  101236. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  101237. if (!_this.getScene().useRightHandedSystem) {
  101238. [2, 6, 8, 9, 14].forEach(function (num) {
  101239. if (_this._standingMatrix) {
  101240. _this._standingMatrix.m[num] *= -1;
  101241. }
  101242. });
  101243. }
  101244. callback(true);
  101245. }
  101246. });
  101247. };
  101248. /**
  101249. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  101250. * @returns A promise with a boolean set to if the standing matrix is supported.
  101251. */
  101252. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  101253. var _this = this;
  101254. return new Promise(function (res, rej) {
  101255. _this.useStandingMatrix(function (supported) {
  101256. res(supported);
  101257. });
  101258. });
  101259. };
  101260. /**
  101261. * Disposes the camera
  101262. */
  101263. WebVRFreeCamera.prototype.dispose = function () {
  101264. this._detachIfAttached();
  101265. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  101266. if (this._updateCacheWhenTrackingDisabledObserver) {
  101267. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  101268. }
  101269. _super.prototype.dispose.call(this);
  101270. };
  101271. /**
  101272. * Gets a vrController by name.
  101273. * @param name The name of the controller to retreive
  101274. * @returns the controller matching the name specified or null if not found
  101275. */
  101276. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  101277. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  101278. var gp = _a[_i];
  101279. if (gp.hand === name) {
  101280. return gp;
  101281. }
  101282. }
  101283. return null;
  101284. };
  101285. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  101286. /**
  101287. * The controller corrisponding to the users left hand.
  101288. */
  101289. get: function () {
  101290. if (!this._leftController) {
  101291. this._leftController = this.getControllerByName("left");
  101292. }
  101293. return this._leftController;
  101294. },
  101295. enumerable: true,
  101296. configurable: true
  101297. });
  101298. ;
  101299. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  101300. /**
  101301. * The controller corrisponding to the users right hand.
  101302. */
  101303. get: function () {
  101304. if (!this._rightController) {
  101305. this._rightController = this.getControllerByName("right");
  101306. }
  101307. return this._rightController;
  101308. },
  101309. enumerable: true,
  101310. configurable: true
  101311. });
  101312. ;
  101313. /**
  101314. * Casts a ray forward from the vrCamera's gaze.
  101315. * @param length Length of the ray (default: 100)
  101316. * @returns the ray corrisponding to the gaze
  101317. */
  101318. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  101319. if (length === void 0) { length = 100; }
  101320. if (this.leftCamera) {
  101321. // Use left eye to avoid computation to compute center on every call
  101322. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  101323. }
  101324. else {
  101325. return _super.prototype.getForwardRay.call(this, length);
  101326. }
  101327. };
  101328. /**
  101329. * @hidden
  101330. * Updates the camera based on device's frame data
  101331. */
  101332. WebVRFreeCamera.prototype._checkInputs = function () {
  101333. if (this._vrDevice && this._vrDevice.isPresenting) {
  101334. this._vrDevice.getFrameData(this._frameData);
  101335. this.updateFromDevice(this._frameData.pose);
  101336. }
  101337. _super.prototype._checkInputs.call(this);
  101338. };
  101339. /**
  101340. * Updates the poseControlled values based on the input device pose.
  101341. * @param poseData Pose coming from the device
  101342. */
  101343. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  101344. if (poseData && poseData.orientation) {
  101345. this.rawPose = poseData;
  101346. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  101347. if (this.getScene().useRightHandedSystem) {
  101348. this._deviceRoomRotationQuaternion.z *= -1;
  101349. this._deviceRoomRotationQuaternion.w *= -1;
  101350. }
  101351. if (this.webVROptions.trackPosition && this.rawPose.position) {
  101352. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  101353. if (this.getScene().useRightHandedSystem) {
  101354. this._deviceRoomPosition.z *= -1;
  101355. }
  101356. }
  101357. this._poseSet = true;
  101358. }
  101359. };
  101360. /**
  101361. * WebVR's attach control will start broadcasting frames to the device.
  101362. * Note that in certain browsers (chrome for example) this function must be called
  101363. * within a user-interaction callback. Example:
  101364. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  101365. *
  101366. * @param element html element to attach the vrDevice to
  101367. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  101368. */
  101369. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  101370. _super.prototype.attachControl.call(this, element, noPreventDefault);
  101371. this._attached = true;
  101372. this._htmlElementAttached = element;
  101373. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  101374. if (this._vrDevice) {
  101375. this.getEngine().enableVR();
  101376. }
  101377. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  101378. };
  101379. /**
  101380. * Detaches the camera from the html element and disables VR
  101381. *
  101382. * @param element html element to detach from
  101383. */
  101384. WebVRFreeCamera.prototype.detachControl = function (element) {
  101385. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  101386. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  101387. _super.prototype.detachControl.call(this, element);
  101388. this._attached = false;
  101389. this.getEngine().disableVR();
  101390. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  101391. };
  101392. /**
  101393. * @returns the name of this class
  101394. */
  101395. WebVRFreeCamera.prototype.getClassName = function () {
  101396. return "WebVRFreeCamera";
  101397. };
  101398. /**
  101399. * Calls resetPose on the vrDisplay
  101400. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  101401. */
  101402. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  101403. //uses the vrDisplay's "resetPose()".
  101404. //pitch and roll won't be affected.
  101405. this._vrDevice.resetPose();
  101406. };
  101407. /**
  101408. * @hidden
  101409. * Updates the rig cameras (left and right eye)
  101410. */
  101411. WebVRFreeCamera.prototype._updateRigCameras = function () {
  101412. var camLeft = this._rigCameras[0];
  101413. var camRight = this._rigCameras[1];
  101414. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  101415. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  101416. camLeft.position.copyFrom(this._deviceRoomPosition);
  101417. camRight.position.copyFrom(this._deviceRoomPosition);
  101418. };
  101419. // Remove translation from 6dof headset if trackposition is set to false
  101420. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  101421. if (isViewMatrix === void 0) { isViewMatrix = false; }
  101422. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  101423. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  101424. if (!isViewMatrix) {
  101425. this._tmpMatrix.invert();
  101426. }
  101427. this._tmpMatrix.multiplyToRef(matrix, matrix);
  101428. }
  101429. };
  101430. /**
  101431. * @hidden
  101432. * Updates the cached values of the camera
  101433. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  101434. */
  101435. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  101436. var _this = this;
  101437. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  101438. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  101439. if (!this.updateCacheCalled) {
  101440. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  101441. this.updateCacheCalled = true;
  101442. this.update();
  101443. }
  101444. // Set working vector to the device position in room space rotated by the new rotation
  101445. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  101446. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  101447. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  101448. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  101449. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  101450. // Add translation from anchor position
  101451. this._deviceToWorld.getTranslationToRef(this._workingVector);
  101452. this._workingVector.addInPlace(this.position);
  101453. this._workingVector.subtractInPlace(this._cache.position);
  101454. this._deviceToWorld.setTranslation(this._workingVector);
  101455. // Set an inverted matrix to be used when updating the camera
  101456. this._deviceToWorld.invertToRef(this._worldToDevice);
  101457. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  101458. this.controllers.forEach(function (controller) {
  101459. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  101460. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  101461. controller.update();
  101462. });
  101463. }
  101464. if (!ignoreParentClass) {
  101465. _super.prototype._updateCache.call(this);
  101466. }
  101467. this.updateCacheCalled = false;
  101468. };
  101469. /**
  101470. * @hidden
  101471. * Get current device position in babylon world
  101472. */
  101473. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  101474. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  101475. };
  101476. /**
  101477. * Updates the current device position and rotation in the babylon world
  101478. */
  101479. WebVRFreeCamera.prototype.update = function () {
  101480. this._computeDevicePosition();
  101481. // Get current device rotation in babylon world
  101482. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  101483. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  101484. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  101485. if (this._poseSet) {
  101486. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  101487. }
  101488. _super.prototype.update.call(this);
  101489. };
  101490. /**
  101491. * @hidden
  101492. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  101493. * @returns an identity matrix
  101494. */
  101495. WebVRFreeCamera.prototype._getViewMatrix = function () {
  101496. return BABYLON.Matrix.Identity();
  101497. };
  101498. /**
  101499. * This function is called by the two RIG cameras.
  101500. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  101501. */
  101502. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  101503. var _this = this;
  101504. // Update the parent camera prior to using a child camera to avoid desynchronization
  101505. var parentCamera = this._cameraRigParams["parentCamera"];
  101506. parentCamera._updateCache();
  101507. //WebVR 1.1
  101508. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  101509. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  101510. if (!this.getScene().useRightHandedSystem) {
  101511. [2, 6, 8, 9, 14].forEach(function (num) {
  101512. _this._webvrViewMatrix.m[num] *= -1;
  101513. });
  101514. }
  101515. // update the camera rotation matrix
  101516. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  101517. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  101518. // Computing target and final matrix
  101519. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  101520. // should the view matrix be updated with scale and position offset?
  101521. if (parentCamera.deviceScaleFactor !== 1) {
  101522. this._webvrViewMatrix.invert();
  101523. // scale the position, if set
  101524. if (parentCamera.deviceScaleFactor) {
  101525. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  101526. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  101527. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  101528. }
  101529. this._webvrViewMatrix.invert();
  101530. }
  101531. // Remove translation from 6dof headset if trackposition is set to false
  101532. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  101533. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  101534. // Compute global position
  101535. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  101536. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  101537. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  101538. this._workingMatrix.getTranslationToRef(this._globalPosition);
  101539. this._markSyncedWithParent();
  101540. return this._webvrViewMatrix;
  101541. };
  101542. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  101543. var _this = this;
  101544. var parentCamera = this.parent;
  101545. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  101546. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  101547. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  101548. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  101549. //babylon compatible matrix
  101550. if (!this.getScene().useRightHandedSystem) {
  101551. [8, 9, 10, 11].forEach(function (num) {
  101552. _this._projectionMatrix.m[num] *= -1;
  101553. });
  101554. }
  101555. return this._projectionMatrix;
  101556. };
  101557. /**
  101558. * Initializes the controllers and their meshes
  101559. */
  101560. WebVRFreeCamera.prototype.initControllers = function () {
  101561. var _this = this;
  101562. this.controllers = [];
  101563. var manager = this.getScene().gamepadManager;
  101564. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  101565. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  101566. var webVrController = gamepad;
  101567. if (webVrController.defaultModel) {
  101568. webVrController.defaultModel.setEnabled(false);
  101569. }
  101570. if (webVrController.hand === "right") {
  101571. _this._rightController = null;
  101572. }
  101573. if (webVrController.hand === "left") {
  101574. _this._leftController = null;
  101575. }
  101576. var controllerIndex = _this.controllers.indexOf(webVrController);
  101577. if (controllerIndex !== -1) {
  101578. _this.controllers.splice(controllerIndex, 1);
  101579. }
  101580. }
  101581. });
  101582. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  101583. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  101584. var webVrController_1 = gamepad;
  101585. if (!_this.webVROptions.trackPosition) {
  101586. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  101587. // Cache must be updated before rendering controllers to avoid them being one frame behind
  101588. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  101589. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  101590. _this._updateCache();
  101591. });
  101592. }
  101593. }
  101594. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  101595. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  101596. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  101597. if (_this.webVROptions.controllerMeshes) {
  101598. if (webVrController_1.defaultModel) {
  101599. webVrController_1.defaultModel.setEnabled(true);
  101600. }
  101601. else {
  101602. // Load the meshes
  101603. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  101604. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  101605. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  101606. if (_this.webVROptions.defaultLightingOnControllers) {
  101607. if (!_this._lightOnControllers) {
  101608. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  101609. }
  101610. var activateLightOnSubMeshes_1 = function (mesh, light) {
  101611. var children = mesh.getChildren();
  101612. if (children && children.length !== 0) {
  101613. children.forEach(function (mesh) {
  101614. light.includedOnlyMeshes.push(mesh);
  101615. activateLightOnSubMeshes_1(mesh, light);
  101616. });
  101617. }
  101618. };
  101619. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  101620. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  101621. }
  101622. });
  101623. }
  101624. }
  101625. webVrController_1.attachToPoseControlledCamera(_this);
  101626. // since this is async - sanity check. Is the controller already stored?
  101627. if (_this.controllers.indexOf(webVrController_1) === -1) {
  101628. //add to the controllers array
  101629. _this.controllers.push(webVrController_1);
  101630. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  101631. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  101632. // So we're overriding setting left & right manually to be sure
  101633. var firstViveWandDetected = false;
  101634. for (var i = 0; i < _this.controllers.length; i++) {
  101635. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  101636. if (!firstViveWandDetected) {
  101637. firstViveWandDetected = true;
  101638. _this.controllers[i].hand = "left";
  101639. }
  101640. else {
  101641. _this.controllers[i].hand = "right";
  101642. }
  101643. }
  101644. }
  101645. //did we find enough controllers? Great! let the developer know.
  101646. if (_this.controllers.length >= 2) {
  101647. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  101648. }
  101649. }
  101650. }
  101651. });
  101652. };
  101653. return WebVRFreeCamera;
  101654. }(BABYLON.FreeCamera));
  101655. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  101656. })(BABYLON || (BABYLON = {}));
  101657. //# sourceMappingURL=babylon.webVRCamera.js.map
  101658. var BABYLON;
  101659. (function (BABYLON) {
  101660. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  101661. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  101662. });
  101663. // We're mainly based on the logic defined into the FreeCamera code
  101664. /**
  101665. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  101666. * being tilted forward or back and left or right.
  101667. */
  101668. var DeviceOrientationCamera = /** @class */ (function (_super) {
  101669. __extends(DeviceOrientationCamera, _super);
  101670. /**
  101671. * Creates a new device orientation camera
  101672. * @param name The name of the camera
  101673. * @param position The start position camera
  101674. * @param scene The scene the camera belongs to
  101675. */
  101676. function DeviceOrientationCamera(name, position, scene) {
  101677. var _this = _super.call(this, name, position, scene) || this;
  101678. _this._quaternionCache = new BABYLON.Quaternion();
  101679. _this.inputs.addDeviceOrientation();
  101680. return _this;
  101681. }
  101682. /**
  101683. * Gets the current instance class name ("DeviceOrientationCamera").
  101684. * This helps avoiding instanceof at run time.
  101685. * @returns the class name
  101686. */
  101687. DeviceOrientationCamera.prototype.getClassName = function () {
  101688. return "DeviceOrientationCamera";
  101689. };
  101690. /**
  101691. * @hidden
  101692. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  101693. */
  101694. DeviceOrientationCamera.prototype._checkInputs = function () {
  101695. _super.prototype._checkInputs.call(this);
  101696. this._quaternionCache.copyFrom(this.rotationQuaternion);
  101697. if (this._initialQuaternion) {
  101698. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  101699. }
  101700. };
  101701. /**
  101702. * Reset the camera to its default orientation on the specified axis only.
  101703. * @param axis The axis to reset
  101704. */
  101705. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  101706. var _this = this;
  101707. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  101708. //can only work if this camera has a rotation quaternion already.
  101709. if (!this.rotationQuaternion)
  101710. return;
  101711. if (!this._initialQuaternion) {
  101712. this._initialQuaternion = new BABYLON.Quaternion();
  101713. }
  101714. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  101715. ['x', 'y', 'z'].forEach(function (axisName) {
  101716. if (!axis[axisName]) {
  101717. _this._initialQuaternion[axisName] = 0;
  101718. }
  101719. else {
  101720. _this._initialQuaternion[axisName] *= -1;
  101721. }
  101722. });
  101723. this._initialQuaternion.normalize();
  101724. //force rotation update
  101725. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  101726. };
  101727. return DeviceOrientationCamera;
  101728. }(BABYLON.FreeCamera));
  101729. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  101730. })(BABYLON || (BABYLON = {}));
  101731. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  101732. var BABYLON;
  101733. (function (BABYLON) {
  101734. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  101735. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101736. });
  101737. /**
  101738. * Camera used to simulate VR rendering (based on FreeCamera)
  101739. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101740. */
  101741. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  101742. __extends(VRDeviceOrientationFreeCamera, _super);
  101743. /**
  101744. * Creates a new VRDeviceOrientationFreeCamera
  101745. * @param name defines camera name
  101746. * @param position defines the start position of the camera
  101747. * @param scene defines the scene the camera belongs to
  101748. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101749. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101750. */
  101751. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  101752. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101753. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101754. var _this = _super.call(this, name, position, scene) || this;
  101755. vrCameraMetrics.compensateDistortion = compensateDistortion;
  101756. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  101757. return _this;
  101758. }
  101759. /**
  101760. * Gets camera class name
  101761. * @returns VRDeviceOrientationFreeCamera
  101762. */
  101763. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  101764. return "VRDeviceOrientationFreeCamera";
  101765. };
  101766. return VRDeviceOrientationFreeCamera;
  101767. }(BABYLON.DeviceOrientationCamera));
  101768. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  101769. })(BABYLON || (BABYLON = {}));
  101770. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  101771. var BABYLON;
  101772. (function (BABYLON) {
  101773. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  101774. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  101775. });
  101776. /**
  101777. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  101778. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101779. */
  101780. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  101781. __extends(VRDeviceOrientationArcRotateCamera, _super);
  101782. /**
  101783. * Creates a new VRDeviceOrientationArcRotateCamera
  101784. * @param name defines camera name
  101785. * @param alpha defines the camera rotation along the logitudinal axis
  101786. * @param beta defines the camera rotation along the latitudinal axis
  101787. * @param radius defines the camera distance from its target
  101788. * @param target defines the camera target
  101789. * @param scene defines the scene the camera belongs to
  101790. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101791. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101792. */
  101793. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  101794. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101795. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101796. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101797. vrCameraMetrics.compensateDistortion = compensateDistortion;
  101798. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  101799. _this.inputs.addVRDeviceOrientation();
  101800. return _this;
  101801. }
  101802. /**
  101803. * Gets camera class name
  101804. * @returns VRDeviceOrientationArcRotateCamera
  101805. */
  101806. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  101807. return "VRDeviceOrientationArcRotateCamera";
  101808. };
  101809. return VRDeviceOrientationArcRotateCamera;
  101810. }(BABYLON.ArcRotateCamera));
  101811. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  101812. })(BABYLON || (BABYLON = {}));
  101813. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  101814. var BABYLON;
  101815. (function (BABYLON) {
  101816. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  101817. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  101818. });
  101819. /**
  101820. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  101821. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101822. */
  101823. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  101824. __extends(VRDeviceOrientationGamepadCamera, _super);
  101825. /**
  101826. * Creates a new VRDeviceOrientationGamepadCamera
  101827. * @param name defines camera name
  101828. * @param position defines the start position of the camera
  101829. * @param scene defines the scene the camera belongs to
  101830. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101831. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101832. */
  101833. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  101834. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101835. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101836. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  101837. _this.inputs.addGamepad();
  101838. return _this;
  101839. }
  101840. /**
  101841. * Gets camera class name
  101842. * @returns VRDeviceOrientationGamepadCamera
  101843. */
  101844. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  101845. return "VRDeviceOrientationGamepadCamera";
  101846. };
  101847. return VRDeviceOrientationGamepadCamera;
  101848. }(BABYLON.VRDeviceOrientationFreeCamera));
  101849. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  101850. })(BABYLON || (BABYLON = {}));
  101851. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  101852. var BABYLON;
  101853. (function (BABYLON) {
  101854. var VRExperienceHelperGazer = /** @class */ (function () {
  101855. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  101856. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  101857. this.scene = scene;
  101858. /** @hidden */
  101859. this._pointerDownOnMeshAsked = false;
  101860. /** @hidden */
  101861. this._isActionableMesh = false;
  101862. /** @hidden */
  101863. this._teleportationRequestInitiated = false;
  101864. /** @hidden */
  101865. this._teleportationBackRequestInitiated = false;
  101866. /** @hidden */
  101867. this._rotationRightAsked = false;
  101868. /** @hidden */
  101869. this._rotationLeftAsked = false;
  101870. /** @hidden */
  101871. this._dpadPressed = true;
  101872. /** @hidden */
  101873. this._activePointer = false;
  101874. this._id = VRExperienceHelperGazer._idCounter++;
  101875. // Gaze tracker
  101876. if (!gazeTrackerToClone) {
  101877. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  101878. this._gazeTracker.bakeCurrentTransformIntoVertices();
  101879. this._gazeTracker.isPickable = false;
  101880. this._gazeTracker.isVisible = false;
  101881. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  101882. targetMat.specularColor = BABYLON.Color3.Black();
  101883. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101884. targetMat.backFaceCulling = false;
  101885. this._gazeTracker.material = targetMat;
  101886. }
  101887. else {
  101888. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  101889. }
  101890. }
  101891. /** @hidden */
  101892. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  101893. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  101894. };
  101895. /** @hidden */
  101896. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  101897. this._pointerDownOnMeshAsked = true;
  101898. if (this._currentHit) {
  101899. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  101900. }
  101901. };
  101902. /** @hidden */
  101903. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  101904. if (this._currentHit) {
  101905. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  101906. }
  101907. this._pointerDownOnMeshAsked = false;
  101908. };
  101909. /** @hidden */
  101910. VRExperienceHelperGazer.prototype._activatePointer = function () {
  101911. this._activePointer = true;
  101912. };
  101913. /** @hidden */
  101914. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  101915. this._activePointer = false;
  101916. };
  101917. /** @hidden */
  101918. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  101919. if (distance === void 0) { distance = 100; }
  101920. };
  101921. VRExperienceHelperGazer.prototype.dispose = function () {
  101922. this._interactionsEnabled = false;
  101923. this._teleportationEnabled = false;
  101924. if (this._gazeTracker) {
  101925. this._gazeTracker.dispose();
  101926. }
  101927. };
  101928. VRExperienceHelperGazer._idCounter = 0;
  101929. return VRExperienceHelperGazer;
  101930. }());
  101931. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  101932. __extends(VRExperienceHelperControllerGazer, _super);
  101933. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  101934. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  101935. _this.webVRController = webVRController;
  101936. // Laser pointer
  101937. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  101938. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  101939. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101940. laserPointerMaterial.alpha = 0.6;
  101941. _this._laserPointer.material = laserPointerMaterial;
  101942. _this._laserPointer.rotation.x = Math.PI / 2;
  101943. _this._laserPointer.position.z = -0.5;
  101944. _this._laserPointer.isVisible = false;
  101945. _this._laserPointer.isPickable = false;
  101946. if (!webVRController.mesh) {
  101947. // Create an empty mesh that is used prior to loading the high quality model
  101948. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  101949. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  101950. preloadPointerPose.rotation.x = -0.7;
  101951. preloadMesh.addChild(preloadPointerPose);
  101952. webVRController.attachToMesh(preloadMesh);
  101953. }
  101954. _this._setLaserPointerParent(webVRController.mesh);
  101955. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  101956. _this._setLaserPointerParent(mesh);
  101957. });
  101958. return _this;
  101959. }
  101960. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  101961. return this.webVRController.getForwardRay(length);
  101962. };
  101963. /** @hidden */
  101964. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  101965. _super.prototype._activatePointer.call(this);
  101966. this._laserPointer.isVisible = true;
  101967. };
  101968. /** @hidden */
  101969. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  101970. _super.prototype._deactivatePointer.call(this);
  101971. this._laserPointer.isVisible = false;
  101972. };
  101973. /** @hidden */
  101974. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  101975. this._laserPointer.material.emissiveColor = color;
  101976. };
  101977. /** @hidden */
  101978. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  101979. var makeNotPick = function (root) {
  101980. root.isPickable = false;
  101981. root.getChildMeshes().forEach(function (c) {
  101982. makeNotPick(c);
  101983. });
  101984. };
  101985. makeNotPick(mesh);
  101986. var childMeshes = mesh.getChildMeshes();
  101987. this.webVRController._pointingPoseNode = null;
  101988. for (var i = 0; i < childMeshes.length; i++) {
  101989. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  101990. mesh = childMeshes[i];
  101991. this.webVRController._pointingPoseNode = mesh;
  101992. break;
  101993. }
  101994. }
  101995. this._laserPointer.parent = mesh;
  101996. };
  101997. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  101998. if (distance === void 0) { distance = 100; }
  101999. this._laserPointer.scaling.y = distance;
  102000. this._laserPointer.position.z = -distance / 2;
  102001. };
  102002. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  102003. _super.prototype.dispose.call(this);
  102004. this._laserPointer.dispose();
  102005. if (this._meshAttachedObserver) {
  102006. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  102007. }
  102008. };
  102009. return VRExperienceHelperControllerGazer;
  102010. }(VRExperienceHelperGazer));
  102011. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  102012. __extends(VRExperienceHelperCameraGazer, _super);
  102013. function VRExperienceHelperCameraGazer(getCamera, scene) {
  102014. var _this = _super.call(this, scene) || this;
  102015. _this.getCamera = getCamera;
  102016. return _this;
  102017. }
  102018. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  102019. var camera = this.getCamera();
  102020. if (camera) {
  102021. return camera.getForwardRay(length);
  102022. }
  102023. else {
  102024. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  102025. }
  102026. };
  102027. return VRExperienceHelperCameraGazer;
  102028. }(VRExperienceHelperGazer));
  102029. /**
  102030. * Helps to quickly add VR support to an existing scene.
  102031. * See http://doc.babylonjs.com/how_to/webvr_helper
  102032. */
  102033. var VRExperienceHelper = /** @class */ (function () {
  102034. /**
  102035. * Instantiates a VRExperienceHelper.
  102036. * Helps to quickly add VR support to an existing scene.
  102037. * @param scene The scene the VRExperienceHelper belongs to.
  102038. * @param webVROptions Options to modify the vr experience helper's behavior.
  102039. */
  102040. function VRExperienceHelper(scene,
  102041. /** Options to modify the vr experience helper's behavior. */
  102042. webVROptions) {
  102043. if (webVROptions === void 0) { webVROptions = {}; }
  102044. var _this = this;
  102045. this.webVROptions = webVROptions;
  102046. // Can the system support WebVR, even if a headset isn't plugged in?
  102047. this._webVRsupported = false;
  102048. // If WebVR is supported, is a headset plugged in and are we ready to present?
  102049. this._webVRready = false;
  102050. // Are we waiting for the requestPresent callback to complete?
  102051. this._webVRrequesting = false;
  102052. // Are we presenting to the headset right now? (this is the vrDevice state)
  102053. this._webVRpresenting = false;
  102054. // Are we presenting in the fullscreen fallback?
  102055. this._fullscreenVRpresenting = false;
  102056. /**
  102057. * Observable raised when entering VR.
  102058. */
  102059. this.onEnteringVRObservable = new BABYLON.Observable();
  102060. /**
  102061. * Observable raised when exiting VR.
  102062. */
  102063. this.onExitingVRObservable = new BABYLON.Observable();
  102064. /**
  102065. * Observable raised when controller mesh is loaded.
  102066. */
  102067. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  102068. this._useCustomVRButton = false;
  102069. this._teleportationRequested = false;
  102070. this._teleportActive = false;
  102071. this._floorMeshesCollection = [];
  102072. this._rotationAllowed = true;
  102073. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  102074. this._isDefaultTeleportationTarget = true;
  102075. this._teleportationFillColor = "#444444";
  102076. this._teleportationBorderColor = "#FFFFFF";
  102077. this._rotationAngle = 0;
  102078. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  102079. this._padSensibilityUp = 0.65;
  102080. this._padSensibilityDown = 0.35;
  102081. this._leftController = null;
  102082. this._rightController = null;
  102083. /**
  102084. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  102085. */
  102086. this.onNewMeshSelected = new BABYLON.Observable();
  102087. /**
  102088. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  102089. */
  102090. this.onNewMeshPicked = new BABYLON.Observable();
  102091. /**
  102092. * Observable raised before camera teleportation
  102093. */
  102094. this.onBeforeCameraTeleport = new BABYLON.Observable();
  102095. /**
  102096. * Observable raised after camera teleportation
  102097. */
  102098. this.onAfterCameraTeleport = new BABYLON.Observable();
  102099. /**
  102100. * Observable raised when current selected mesh gets unselected
  102101. */
  102102. this.onSelectedMeshUnselected = new BABYLON.Observable();
  102103. /**
  102104. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  102105. */
  102106. this.teleportationEnabled = true;
  102107. this._teleportationInitialized = false;
  102108. this._interactionsEnabled = false;
  102109. this._interactionsRequested = false;
  102110. this._displayGaze = true;
  102111. this._displayLaserPointer = true;
  102112. /**
  102113. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  102114. */
  102115. this.updateGazeTrackerScale = true;
  102116. this._onResize = function () {
  102117. _this.moveButtonToBottomRight();
  102118. if (_this._fullscreenVRpresenting && _this._webVRready) {
  102119. _this.exitVR();
  102120. }
  102121. };
  102122. this._onFullscreenChange = function () {
  102123. if (document.fullscreen !== undefined) {
  102124. _this._fullscreenVRpresenting = document.fullscreen;
  102125. }
  102126. else if (document.mozFullScreen !== undefined) {
  102127. _this._fullscreenVRpresenting = document.mozFullScreen;
  102128. }
  102129. else if (document.webkitIsFullScreen !== undefined) {
  102130. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  102131. }
  102132. else if (document.msIsFullScreen !== undefined) {
  102133. _this._fullscreenVRpresenting = document.msIsFullScreen;
  102134. }
  102135. else if (document.msFullscreenElement !== undefined) {
  102136. _this._fullscreenVRpresenting = document.msFullscreenElement;
  102137. }
  102138. if (!_this._fullscreenVRpresenting && _this._canvas) {
  102139. _this.exitVR();
  102140. if (!_this._useCustomVRButton) {
  102141. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  102142. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  102143. }
  102144. }
  102145. };
  102146. this.beforeRender = function () {
  102147. if (_this._leftController && _this._leftController._activePointer) {
  102148. _this._castRayAndSelectObject(_this._leftController);
  102149. }
  102150. if (_this._rightController && _this._rightController._activePointer) {
  102151. _this._castRayAndSelectObject(_this._rightController);
  102152. }
  102153. if (_this._noControllerIsActive) {
  102154. _this._castRayAndSelectObject(_this._cameraGazer);
  102155. }
  102156. else {
  102157. _this._cameraGazer._gazeTracker.isVisible = false;
  102158. }
  102159. };
  102160. this._onNewGamepadConnected = function (gamepad) {
  102161. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  102162. if (gamepad.leftStick) {
  102163. gamepad.onleftstickchanged(function (stickValues) {
  102164. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  102165. // Listening to classic/xbox gamepad only if no VR controller is active
  102166. if ((!_this._leftController && !_this._rightController) ||
  102167. ((_this._leftController && !_this._leftController._activePointer) &&
  102168. (_this._rightController && !_this._rightController._activePointer))) {
  102169. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  102170. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  102171. }
  102172. }
  102173. });
  102174. }
  102175. if (gamepad.rightStick) {
  102176. gamepad.onrightstickchanged(function (stickValues) {
  102177. if (_this._teleportationInitialized) {
  102178. _this._checkRotate(stickValues, _this._cameraGazer);
  102179. }
  102180. });
  102181. }
  102182. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  102183. gamepad.onbuttondown(function (buttonPressed) {
  102184. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  102185. _this._cameraGazer._selectionPointerDown();
  102186. }
  102187. });
  102188. gamepad.onbuttonup(function (buttonPressed) {
  102189. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  102190. _this._cameraGazer._selectionPointerUp();
  102191. }
  102192. });
  102193. }
  102194. }
  102195. else {
  102196. var webVRController = gamepad;
  102197. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  102198. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  102199. _this._rightController = controller;
  102200. }
  102201. else {
  102202. _this._leftController = controller;
  102203. }
  102204. _this._tryEnableInteractionOnController(controller);
  102205. }
  102206. };
  102207. // 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
  102208. this._tryEnableInteractionOnController = function (controller) {
  102209. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  102210. _this._enableInteractionOnController(controller);
  102211. }
  102212. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  102213. _this._enableTeleportationOnController(controller);
  102214. }
  102215. };
  102216. this._onNewGamepadDisconnected = function (gamepad) {
  102217. if (gamepad instanceof BABYLON.WebVRController) {
  102218. if (gamepad.hand === "left" && _this._leftController != null) {
  102219. _this._leftController.dispose();
  102220. _this._leftController = null;
  102221. }
  102222. if (gamepad.hand === "right" && _this._rightController != null) {
  102223. _this._rightController.dispose();
  102224. _this._rightController = null;
  102225. }
  102226. }
  102227. };
  102228. this._workingVector = BABYLON.Vector3.Zero();
  102229. this._workingQuaternion = BABYLON.Quaternion.Identity();
  102230. this._workingMatrix = BABYLON.Matrix.Identity();
  102231. this._scene = scene;
  102232. this._canvas = scene.getEngine().getRenderingCanvas();
  102233. // Parse options
  102234. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  102235. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  102236. }
  102237. if (webVROptions.createDeviceOrientationCamera === undefined) {
  102238. webVROptions.createDeviceOrientationCamera = true;
  102239. }
  102240. if (webVROptions.laserToggle === undefined) {
  102241. webVROptions.laserToggle = true;
  102242. }
  102243. if (webVROptions.defaultHeight === undefined) {
  102244. webVROptions.defaultHeight = 1.7;
  102245. }
  102246. if (webVROptions.useCustomVRButton) {
  102247. this._useCustomVRButton = true;
  102248. if (webVROptions.customVRButton) {
  102249. this._btnVR = webVROptions.customVRButton;
  102250. }
  102251. }
  102252. if (webVROptions.rayLength) {
  102253. this._rayLength = webVROptions.rayLength;
  102254. }
  102255. this._defaultHeight = webVROptions.defaultHeight;
  102256. if (webVROptions.positionScale) {
  102257. this._rayLength *= webVROptions.positionScale;
  102258. this._defaultHeight *= webVROptions.positionScale;
  102259. }
  102260. this._hasEnteredVR = false;
  102261. // Set position
  102262. if (this._scene.activeCamera) {
  102263. this._position = this._scene.activeCamera.position.clone();
  102264. }
  102265. else {
  102266. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  102267. }
  102268. // Set non-vr camera
  102269. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  102270. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  102271. // Copy data from existing camera
  102272. if (this._scene.activeCamera) {
  102273. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  102274. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  102275. // Set rotation from previous camera
  102276. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  102277. var targetCamera = this._scene.activeCamera;
  102278. if (targetCamera.rotationQuaternion) {
  102279. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  102280. }
  102281. else {
  102282. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  102283. }
  102284. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  102285. }
  102286. }
  102287. this._scene.activeCamera = this._deviceOrientationCamera;
  102288. if (this._canvas) {
  102289. this._scene.activeCamera.attachControl(this._canvas);
  102290. }
  102291. }
  102292. else {
  102293. this._existingCamera = this._scene.activeCamera;
  102294. }
  102295. // Create VR cameras
  102296. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  102297. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  102298. }
  102299. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  102300. this._webVRCamera.useStandingMatrix();
  102301. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  102302. // Create default button
  102303. if (!this._useCustomVRButton) {
  102304. this._btnVR = document.createElement("BUTTON");
  102305. this._btnVR.className = "babylonVRicon";
  102306. this._btnVR.id = "babylonVRiconbtn";
  102307. this._btnVR.title = "Click to switch to VR";
  102308. 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) }";
  102309. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  102310. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  102311. // css += ".babylonVRicon.vrdisplaysupported { }";
  102312. // css += ".babylonVRicon.vrdisplayready { }";
  102313. // css += ".babylonVRicon.vrdisplayrequesting { }";
  102314. var style = document.createElement('style');
  102315. style.appendChild(document.createTextNode(css));
  102316. document.getElementsByTagName('head')[0].appendChild(style);
  102317. this.moveButtonToBottomRight();
  102318. }
  102319. // VR button click event
  102320. if (this._btnVR) {
  102321. this._btnVR.addEventListener("click", function () {
  102322. if (!_this.isInVRMode) {
  102323. _this.enterVR();
  102324. }
  102325. else {
  102326. _this.exitVR();
  102327. }
  102328. });
  102329. }
  102330. // Window events
  102331. window.addEventListener("resize", this._onResize);
  102332. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  102333. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  102334. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  102335. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  102336. document.onmsfullscreenchange = this._onFullscreenChange;
  102337. // Display vr button when headset is connected
  102338. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  102339. this.displayVRButton();
  102340. }
  102341. else {
  102342. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  102343. if (e.vrDisplay) {
  102344. _this.displayVRButton();
  102345. }
  102346. });
  102347. }
  102348. // Exiting VR mode using 'ESC' key on desktop
  102349. this._onKeyDown = function (event) {
  102350. if (event.keyCode === 27 && _this.isInVRMode) {
  102351. _this.exitVR();
  102352. }
  102353. };
  102354. document.addEventListener("keydown", this._onKeyDown);
  102355. // Exiting VR mode double tapping the touch screen
  102356. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  102357. if (_this.isInVRMode) {
  102358. _this.exitVR();
  102359. if (_this._fullscreenVRpresenting) {
  102360. _this._scene.getEngine().switchFullscreen(true);
  102361. }
  102362. }
  102363. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  102364. // Listen for WebVR display changes
  102365. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  102366. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  102367. this._onVRRequestPresentStart = function () {
  102368. _this._webVRrequesting = true;
  102369. _this.updateButtonVisibility();
  102370. };
  102371. this._onVRRequestPresentComplete = function (success) {
  102372. _this._webVRrequesting = false;
  102373. _this.updateButtonVisibility();
  102374. };
  102375. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  102376. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  102377. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  102378. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102379. scene.onDisposeObservable.add(function () {
  102380. _this.dispose();
  102381. });
  102382. // Gamepad connection events
  102383. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  102384. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  102385. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  102386. this.updateButtonVisibility();
  102387. //create easing functions
  102388. this._circleEase = new BABYLON.CircleEase();
  102389. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  102390. if (this.webVROptions.floorMeshes) {
  102391. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  102392. }
  102393. }
  102394. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  102395. /** Return this.onEnteringVRObservable
  102396. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  102397. */
  102398. get: function () {
  102399. return this.onEnteringVRObservable;
  102400. },
  102401. enumerable: true,
  102402. configurable: true
  102403. });
  102404. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  102405. /** Return this.onExitingVRObservable
  102406. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  102407. */
  102408. get: function () {
  102409. return this.onExitingVRObservable;
  102410. },
  102411. enumerable: true,
  102412. configurable: true
  102413. });
  102414. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  102415. /** Return this.onControllerMeshLoadedObservable
  102416. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  102417. */
  102418. get: function () {
  102419. return this.onControllerMeshLoadedObservable;
  102420. },
  102421. enumerable: true,
  102422. configurable: true
  102423. });
  102424. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  102425. /**
  102426. * The mesh used to display where the user is going to teleport.
  102427. */
  102428. get: function () {
  102429. return this._teleportationTarget;
  102430. },
  102431. /**
  102432. * Sets the mesh to be used to display where the user is going to teleport.
  102433. */
  102434. set: function (value) {
  102435. if (value) {
  102436. value.name = "teleportationTarget";
  102437. this._isDefaultTeleportationTarget = false;
  102438. this._teleportationTarget = value;
  102439. }
  102440. },
  102441. enumerable: true,
  102442. configurable: true
  102443. });
  102444. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  102445. /**
  102446. * 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
  102447. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  102448. * See http://doc.babylonjs.com/resources/baking_transformations
  102449. */
  102450. get: function () {
  102451. return this._cameraGazer._gazeTracker;
  102452. },
  102453. set: function (value) {
  102454. if (value) {
  102455. // Dispose of existing meshes
  102456. if (this._cameraGazer._gazeTracker) {
  102457. this._cameraGazer._gazeTracker.dispose();
  102458. }
  102459. if (this._leftController && this._leftController._gazeTracker) {
  102460. this._leftController._gazeTracker.dispose();
  102461. }
  102462. if (this._rightController && this._rightController._gazeTracker) {
  102463. this._rightController._gazeTracker.dispose();
  102464. }
  102465. // Set and create gaze trackers on head and controllers
  102466. this._cameraGazer._gazeTracker = value;
  102467. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  102468. this._cameraGazer._gazeTracker.isPickable = false;
  102469. this._cameraGazer._gazeTracker.isVisible = false;
  102470. this._cameraGazer._gazeTracker.name = "gazeTracker";
  102471. if (this._leftController) {
  102472. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  102473. }
  102474. if (this._rightController) {
  102475. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  102476. }
  102477. }
  102478. },
  102479. enumerable: true,
  102480. configurable: true
  102481. });
  102482. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  102483. /**
  102484. * The gaze tracking mesh corresponding to the left controller
  102485. */
  102486. get: function () {
  102487. if (this._leftController) {
  102488. return this._leftController._gazeTracker;
  102489. }
  102490. return null;
  102491. },
  102492. enumerable: true,
  102493. configurable: true
  102494. });
  102495. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  102496. /**
  102497. * The gaze tracking mesh corresponding to the right controller
  102498. */
  102499. get: function () {
  102500. if (this._rightController) {
  102501. return this._rightController._gazeTracker;
  102502. }
  102503. return null;
  102504. },
  102505. enumerable: true,
  102506. configurable: true
  102507. });
  102508. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  102509. /**
  102510. * If the ray of the gaze should be displayed.
  102511. */
  102512. get: function () {
  102513. return this._displayGaze;
  102514. },
  102515. /**
  102516. * Sets if the ray of the gaze should be displayed.
  102517. */
  102518. set: function (value) {
  102519. this._displayGaze = value;
  102520. if (!value) {
  102521. this._cameraGazer._gazeTracker.isVisible = false;
  102522. if (this._leftController) {
  102523. this._leftController._gazeTracker.isVisible = false;
  102524. }
  102525. if (this._rightController) {
  102526. this._rightController._gazeTracker.isVisible = false;
  102527. }
  102528. }
  102529. },
  102530. enumerable: true,
  102531. configurable: true
  102532. });
  102533. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  102534. /**
  102535. * If the ray of the LaserPointer should be displayed.
  102536. */
  102537. get: function () {
  102538. return this._displayLaserPointer;
  102539. },
  102540. /**
  102541. * Sets if the ray of the LaserPointer should be displayed.
  102542. */
  102543. set: function (value) {
  102544. this._displayLaserPointer = value;
  102545. if (!value) {
  102546. if (this._rightController) {
  102547. this._rightController._deactivatePointer();
  102548. this._rightController._gazeTracker.isVisible = false;
  102549. }
  102550. if (this._leftController) {
  102551. this._leftController._deactivatePointer();
  102552. this._leftController._gazeTracker.isVisible = false;
  102553. }
  102554. }
  102555. else {
  102556. if (this._rightController) {
  102557. this._rightController._activatePointer();
  102558. }
  102559. if (this._leftController) {
  102560. this._leftController._activatePointer();
  102561. }
  102562. }
  102563. },
  102564. enumerable: true,
  102565. configurable: true
  102566. });
  102567. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  102568. /**
  102569. * The deviceOrientationCamera used as the camera when not in VR.
  102570. */
  102571. get: function () {
  102572. return this._deviceOrientationCamera;
  102573. },
  102574. enumerable: true,
  102575. configurable: true
  102576. });
  102577. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  102578. /**
  102579. * Based on the current WebVR support, returns the current VR camera used.
  102580. */
  102581. get: function () {
  102582. if (this._webVRready) {
  102583. return this._webVRCamera;
  102584. }
  102585. else {
  102586. return this._scene.activeCamera;
  102587. }
  102588. },
  102589. enumerable: true,
  102590. configurable: true
  102591. });
  102592. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  102593. /**
  102594. * The webVRCamera which is used when in VR.
  102595. */
  102596. get: function () {
  102597. return this._webVRCamera;
  102598. },
  102599. enumerable: true,
  102600. configurable: true
  102601. });
  102602. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  102603. /**
  102604. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  102605. */
  102606. get: function () {
  102607. return this._vrDeviceOrientationCamera;
  102608. },
  102609. enumerable: true,
  102610. configurable: true
  102611. });
  102612. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  102613. get: function () {
  102614. var result = this._cameraGazer._teleportationRequestInitiated
  102615. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  102616. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  102617. return result;
  102618. },
  102619. enumerable: true,
  102620. configurable: true
  102621. });
  102622. // Raised when one of the controller has loaded successfully its associated default mesh
  102623. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  102624. if (this._leftController && this._leftController.webVRController == webVRController) {
  102625. if (webVRController.mesh) {
  102626. this._leftController._setLaserPointerParent(webVRController.mesh);
  102627. }
  102628. }
  102629. if (this._rightController && this._rightController.webVRController == webVRController) {
  102630. if (webVRController.mesh) {
  102631. this._rightController._setLaserPointerParent(webVRController.mesh);
  102632. }
  102633. }
  102634. try {
  102635. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  102636. }
  102637. catch (err) {
  102638. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  102639. }
  102640. };
  102641. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  102642. /**
  102643. * Gets a value indicating if we are currently in VR mode.
  102644. */
  102645. get: function () {
  102646. return this._webVRpresenting || this._fullscreenVRpresenting;
  102647. },
  102648. enumerable: true,
  102649. configurable: true
  102650. });
  102651. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  102652. var vrDisplay = this._scene.getEngine().getVRDevice();
  102653. if (vrDisplay) {
  102654. var wasPresenting = this._webVRpresenting;
  102655. this._webVRpresenting = vrDisplay.isPresenting;
  102656. if (wasPresenting && !this._webVRpresenting)
  102657. this.exitVR();
  102658. }
  102659. else {
  102660. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  102661. }
  102662. this.updateButtonVisibility();
  102663. };
  102664. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  102665. this._webVRsupported = eventArgs.vrSupported;
  102666. this._webVRready = !!eventArgs.vrDisplay;
  102667. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  102668. this.updateButtonVisibility();
  102669. };
  102670. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  102671. if (this._canvas && !this._useCustomVRButton) {
  102672. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  102673. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  102674. }
  102675. };
  102676. VRExperienceHelper.prototype.displayVRButton = function () {
  102677. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  102678. document.body.appendChild(this._btnVR);
  102679. this._btnVRDisplayed = true;
  102680. }
  102681. };
  102682. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  102683. if (!this._btnVR || this._useCustomVRButton) {
  102684. return;
  102685. }
  102686. this._btnVR.className = "babylonVRicon";
  102687. if (this.isInVRMode) {
  102688. this._btnVR.className += " vrdisplaypresenting";
  102689. }
  102690. else {
  102691. if (this._webVRready)
  102692. this._btnVR.className += " vrdisplayready";
  102693. if (this._webVRsupported)
  102694. this._btnVR.className += " vrdisplaysupported";
  102695. if (this._webVRrequesting)
  102696. this._btnVR.className += " vrdisplayrequesting";
  102697. }
  102698. };
  102699. /**
  102700. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  102701. * Otherwise, will use the fullscreen API.
  102702. */
  102703. VRExperienceHelper.prototype.enterVR = function () {
  102704. if (this.onEnteringVRObservable) {
  102705. try {
  102706. this.onEnteringVRObservable.notifyObservers(this);
  102707. }
  102708. catch (err) {
  102709. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  102710. }
  102711. }
  102712. if (this._scene.activeCamera) {
  102713. this._position = this._scene.activeCamera.position.clone();
  102714. // make sure that we return to the last active camera
  102715. this._existingCamera = this._scene.activeCamera;
  102716. }
  102717. if (this._webVRrequesting)
  102718. return;
  102719. // If WebVR is supported and a headset is connected
  102720. if (this._webVRready) {
  102721. if (!this._webVRpresenting) {
  102722. this._webVRCamera.position = this._position;
  102723. this._scene.activeCamera = this._webVRCamera;
  102724. }
  102725. }
  102726. else if (this._vrDeviceOrientationCamera) {
  102727. this._vrDeviceOrientationCamera.position = this._position;
  102728. if (this._scene.activeCamera) {
  102729. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  102730. }
  102731. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  102732. this._scene.getEngine().switchFullscreen(true);
  102733. this.updateButtonVisibility();
  102734. }
  102735. if (this._scene.activeCamera && this._canvas) {
  102736. this._scene.activeCamera.attachControl(this._canvas);
  102737. }
  102738. if (this._interactionsEnabled) {
  102739. this._scene.registerBeforeRender(this.beforeRender);
  102740. }
  102741. this._hasEnteredVR = true;
  102742. };
  102743. /**
  102744. * Attempt to exit VR, or fullscreen.
  102745. */
  102746. VRExperienceHelper.prototype.exitVR = function () {
  102747. if (this._hasEnteredVR) {
  102748. if (this.onExitingVRObservable) {
  102749. try {
  102750. this.onExitingVRObservable.notifyObservers(this);
  102751. }
  102752. catch (err) {
  102753. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  102754. }
  102755. }
  102756. if (this._webVRpresenting) {
  102757. this._scene.getEngine().disableVR();
  102758. }
  102759. if (this._scene.activeCamera) {
  102760. this._position = this._scene.activeCamera.position.clone();
  102761. }
  102762. if (this._deviceOrientationCamera) {
  102763. this._deviceOrientationCamera.position = this._position;
  102764. this._scene.activeCamera = this._deviceOrientationCamera;
  102765. if (this._canvas) {
  102766. this._scene.activeCamera.attachControl(this._canvas);
  102767. }
  102768. }
  102769. else if (this._existingCamera) {
  102770. this._existingCamera.position = this._position;
  102771. this._scene.activeCamera = this._existingCamera;
  102772. }
  102773. this.updateButtonVisibility();
  102774. if (this._interactionsEnabled) {
  102775. this._scene.unregisterBeforeRender(this.beforeRender);
  102776. this._cameraGazer._gazeTracker.isVisible = false;
  102777. if (this._leftController) {
  102778. this._leftController._gazeTracker.isVisible = false;
  102779. }
  102780. if (this._rightController) {
  102781. this._rightController._gazeTracker.isVisible = false;
  102782. }
  102783. }
  102784. // resize to update width and height when exiting vr exits fullscreen
  102785. this._scene.getEngine().resize();
  102786. this._hasEnteredVR = false;
  102787. }
  102788. };
  102789. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  102790. /**
  102791. * The position of the vr experience helper.
  102792. */
  102793. get: function () {
  102794. return this._position;
  102795. },
  102796. /**
  102797. * Sets the position of the vr experience helper.
  102798. */
  102799. set: function (value) {
  102800. this._position = value;
  102801. if (this._scene.activeCamera) {
  102802. this._scene.activeCamera.position = value;
  102803. }
  102804. },
  102805. enumerable: true,
  102806. configurable: true
  102807. });
  102808. /**
  102809. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  102810. */
  102811. VRExperienceHelper.prototype.enableInteractions = function () {
  102812. var _this = this;
  102813. if (!this._interactionsEnabled) {
  102814. this._interactionsRequested = true;
  102815. if (this._leftController) {
  102816. this._enableInteractionOnController(this._leftController);
  102817. }
  102818. if (this._rightController) {
  102819. this._enableInteractionOnController(this._rightController);
  102820. }
  102821. this.raySelectionPredicate = function (mesh) {
  102822. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  102823. };
  102824. this.meshSelectionPredicate = function (mesh) {
  102825. return true;
  102826. };
  102827. this._raySelectionPredicate = function (mesh) {
  102828. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  102829. && mesh.name.indexOf("teleportationTarget") === -1
  102830. && mesh.name.indexOf("torusTeleportation") === -1)) {
  102831. return _this.raySelectionPredicate(mesh);
  102832. }
  102833. return false;
  102834. };
  102835. this._interactionsEnabled = true;
  102836. }
  102837. };
  102838. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  102839. get: function () {
  102840. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  102841. },
  102842. enumerable: true,
  102843. configurable: true
  102844. });
  102845. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  102846. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  102847. if (this._floorMeshesCollection[i].id === mesh.id) {
  102848. return true;
  102849. }
  102850. }
  102851. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  102852. return true;
  102853. }
  102854. return false;
  102855. };
  102856. /**
  102857. * Adds a floor mesh to be used for teleportation.
  102858. * @param floorMesh the mesh to be used for teleportation.
  102859. */
  102860. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  102861. if (!this._floorMeshesCollection) {
  102862. return;
  102863. }
  102864. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  102865. return;
  102866. }
  102867. this._floorMeshesCollection.push(floorMesh);
  102868. };
  102869. /**
  102870. * Removes a floor mesh from being used for teleportation.
  102871. * @param floorMesh the mesh to be removed.
  102872. */
  102873. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  102874. if (!this._floorMeshesCollection) {
  102875. return;
  102876. }
  102877. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  102878. if (meshIndex !== -1) {
  102879. this._floorMeshesCollection.splice(meshIndex, 1);
  102880. }
  102881. };
  102882. /**
  102883. * Enables interactions and teleportation using the VR controllers and gaze.
  102884. * @param vrTeleportationOptions options to modify teleportation behavior.
  102885. */
  102886. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  102887. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  102888. if (!this._teleportationInitialized) {
  102889. this._teleportationRequested = true;
  102890. this.enableInteractions();
  102891. if (vrTeleportationOptions.floorMeshName) {
  102892. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  102893. }
  102894. if (vrTeleportationOptions.floorMeshes) {
  102895. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  102896. }
  102897. if (this._leftController != null) {
  102898. this._enableTeleportationOnController(this._leftController);
  102899. }
  102900. if (this._rightController != null) {
  102901. this._enableTeleportationOnController(this._rightController);
  102902. }
  102903. // Creates an image processing post process for the vignette not relying
  102904. // on the main scene configuration for image processing to reduce setup and spaces
  102905. // (gamma/linear) conflicts.
  102906. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  102907. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  102908. imageProcessingConfiguration.vignetteEnabled = true;
  102909. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  102910. this._webVRCamera.detachPostProcess(this._postProcessMove);
  102911. this._teleportationInitialized = true;
  102912. if (this._isDefaultTeleportationTarget) {
  102913. this._createTeleportationCircles();
  102914. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  102915. }
  102916. }
  102917. };
  102918. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  102919. var _this = this;
  102920. var controllerMesh = controller.webVRController.mesh;
  102921. if (controllerMesh) {
  102922. controller._interactionsEnabled = true;
  102923. controller._activatePointer();
  102924. if (this.webVROptions.laserToggle) {
  102925. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  102926. // Enabling / disabling laserPointer
  102927. if (_this._displayLaserPointer && stateObject.value === 1) {
  102928. if (controller._activePointer) {
  102929. controller._deactivatePointer();
  102930. }
  102931. else {
  102932. controller._activatePointer();
  102933. }
  102934. if (_this.displayGaze) {
  102935. controller._gazeTracker.isVisible = controller._activePointer;
  102936. }
  102937. }
  102938. });
  102939. }
  102940. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  102941. var gazer = controller;
  102942. if (_this._noControllerIsActive) {
  102943. gazer = _this._cameraGazer;
  102944. }
  102945. if (!gazer._pointerDownOnMeshAsked) {
  102946. if (stateObject.value > _this._padSensibilityUp) {
  102947. gazer._selectionPointerDown();
  102948. }
  102949. }
  102950. else if (stateObject.value < _this._padSensibilityDown) {
  102951. gazer._selectionPointerUp();
  102952. }
  102953. });
  102954. }
  102955. };
  102956. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  102957. // Dont teleport if another gaze already requested teleportation
  102958. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  102959. return;
  102960. }
  102961. if (!gazer._teleportationRequestInitiated) {
  102962. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  102963. gazer._activatePointer();
  102964. gazer._teleportationRequestInitiated = true;
  102965. }
  102966. }
  102967. else {
  102968. // Listening to the proper controller values changes to confirm teleportation
  102969. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  102970. if (this._teleportActive) {
  102971. this.teleportCamera(this._haloCenter);
  102972. }
  102973. gazer._teleportationRequestInitiated = false;
  102974. }
  102975. }
  102976. };
  102977. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  102978. // Only rotate when user is not currently selecting a teleportation location
  102979. if (gazer._teleportationRequestInitiated) {
  102980. return;
  102981. }
  102982. if (!gazer._rotationLeftAsked) {
  102983. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  102984. gazer._rotationLeftAsked = true;
  102985. if (this._rotationAllowed) {
  102986. this._rotateCamera(false);
  102987. }
  102988. }
  102989. }
  102990. else {
  102991. if (stateObject.x > -this._padSensibilityDown) {
  102992. gazer._rotationLeftAsked = false;
  102993. }
  102994. }
  102995. if (!gazer._rotationRightAsked) {
  102996. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  102997. gazer._rotationRightAsked = true;
  102998. if (this._rotationAllowed) {
  102999. this._rotateCamera(true);
  103000. }
  103001. }
  103002. }
  103003. else {
  103004. if (stateObject.x < this._padSensibilityDown) {
  103005. gazer._rotationRightAsked = false;
  103006. }
  103007. }
  103008. };
  103009. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  103010. // Only teleport backwards when user is not currently selecting a teleportation location
  103011. if (gazer._teleportationRequestInitiated) {
  103012. return;
  103013. }
  103014. // Teleport backwards
  103015. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  103016. if (!gazer._teleportationBackRequestInitiated) {
  103017. if (!this.currentVRCamera) {
  103018. return;
  103019. }
  103020. // Get rotation and position of the current camera
  103021. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  103022. var position = this.currentVRCamera.position;
  103023. // If the camera has device position, use that instead
  103024. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  103025. rotation = this.currentVRCamera.deviceRotationQuaternion;
  103026. position = this.currentVRCamera.devicePosition;
  103027. }
  103028. // Get matrix with only the y rotation of the device rotation
  103029. rotation.toEulerAnglesToRef(this._workingVector);
  103030. this._workingVector.z = 0;
  103031. this._workingVector.x = 0;
  103032. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  103033. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  103034. // Rotate backwards ray by device rotation to cast at the ground behind the user
  103035. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  103036. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  103037. var ray = new BABYLON.Ray(position, this._workingVector);
  103038. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103039. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  103040. this.teleportCamera(hit.pickedPoint);
  103041. }
  103042. gazer._teleportationBackRequestInitiated = true;
  103043. }
  103044. }
  103045. else {
  103046. gazer._teleportationBackRequestInitiated = false;
  103047. }
  103048. };
  103049. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  103050. var _this = this;
  103051. var controllerMesh = controller.webVRController.mesh;
  103052. if (controllerMesh) {
  103053. if (!controller._interactionsEnabled) {
  103054. this._enableInteractionOnController(controller);
  103055. }
  103056. controller._interactionsEnabled = true;
  103057. controller._teleportationEnabled = true;
  103058. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103059. controller._dpadPressed = false;
  103060. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  103061. controller._dpadPressed = stateObject.pressed;
  103062. if (!controller._dpadPressed) {
  103063. controller._rotationLeftAsked = false;
  103064. controller._rotationRightAsked = false;
  103065. controller._teleportationBackRequestInitiated = false;
  103066. }
  103067. });
  103068. }
  103069. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  103070. if (_this.teleportationEnabled) {
  103071. _this._checkTeleportBackwards(stateObject, controller);
  103072. _this._checkTeleportWithRay(stateObject, controller);
  103073. }
  103074. _this._checkRotate(stateObject, controller);
  103075. });
  103076. }
  103077. };
  103078. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  103079. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  103080. this._teleportationTarget.isPickable = false;
  103081. var length = 512;
  103082. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  103083. dynamicTexture.hasAlpha = true;
  103084. var context = dynamicTexture.getContext();
  103085. var centerX = length / 2;
  103086. var centerY = length / 2;
  103087. var radius = 200;
  103088. context.beginPath();
  103089. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  103090. context.fillStyle = this._teleportationFillColor;
  103091. context.fill();
  103092. context.lineWidth = 10;
  103093. context.strokeStyle = this._teleportationBorderColor;
  103094. context.stroke();
  103095. context.closePath();
  103096. dynamicTexture.update();
  103097. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  103098. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  103099. this._teleportationTarget.material = teleportationCircleMaterial;
  103100. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  103101. torus.isPickable = false;
  103102. torus.parent = this._teleportationTarget;
  103103. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  103104. var keys = [];
  103105. keys.push({
  103106. frame: 0,
  103107. value: 0
  103108. });
  103109. keys.push({
  103110. frame: 30,
  103111. value: 0.4
  103112. });
  103113. keys.push({
  103114. frame: 60,
  103115. value: 0
  103116. });
  103117. animationInnerCircle.setKeys(keys);
  103118. var easingFunction = new BABYLON.SineEase();
  103119. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  103120. animationInnerCircle.setEasingFunction(easingFunction);
  103121. torus.animations = [];
  103122. torus.animations.push(animationInnerCircle);
  103123. this._scene.beginAnimation(torus, 0, 60, true);
  103124. this._hideTeleportationTarget();
  103125. };
  103126. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  103127. this._teleportActive = true;
  103128. if (this._teleportationInitialized) {
  103129. this._teleportationTarget.isVisible = true;
  103130. if (this._isDefaultTeleportationTarget) {
  103131. this._teleportationTarget.getChildren()[0].isVisible = true;
  103132. }
  103133. }
  103134. };
  103135. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  103136. this._teleportActive = false;
  103137. if (this._teleportationInitialized) {
  103138. this._teleportationTarget.isVisible = false;
  103139. if (this._isDefaultTeleportationTarget) {
  103140. this._teleportationTarget.getChildren()[0].isVisible = false;
  103141. }
  103142. }
  103143. };
  103144. VRExperienceHelper.prototype._rotateCamera = function (right) {
  103145. var _this = this;
  103146. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  103147. return;
  103148. }
  103149. if (right) {
  103150. this._rotationAngle++;
  103151. }
  103152. else {
  103153. this._rotationAngle--;
  103154. }
  103155. this.currentVRCamera.animations = [];
  103156. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  103157. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103158. var animationRotationKeys = [];
  103159. animationRotationKeys.push({
  103160. frame: 0,
  103161. value: this.currentVRCamera.rotationQuaternion
  103162. });
  103163. animationRotationKeys.push({
  103164. frame: 6,
  103165. value: target
  103166. });
  103167. animationRotation.setKeys(animationRotationKeys);
  103168. animationRotation.setEasingFunction(this._circleEase);
  103169. this.currentVRCamera.animations.push(animationRotation);
  103170. this._postProcessMove.animations = [];
  103171. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103172. var vignetteWeightKeys = [];
  103173. vignetteWeightKeys.push({
  103174. frame: 0,
  103175. value: 0
  103176. });
  103177. vignetteWeightKeys.push({
  103178. frame: 3,
  103179. value: 4
  103180. });
  103181. vignetteWeightKeys.push({
  103182. frame: 6,
  103183. value: 0
  103184. });
  103185. animationPP.setKeys(vignetteWeightKeys);
  103186. animationPP.setEasingFunction(this._circleEase);
  103187. this._postProcessMove.animations.push(animationPP);
  103188. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103189. var vignetteStretchKeys = [];
  103190. vignetteStretchKeys.push({
  103191. frame: 0,
  103192. value: 0
  103193. });
  103194. vignetteStretchKeys.push({
  103195. frame: 3,
  103196. value: 10
  103197. });
  103198. vignetteStretchKeys.push({
  103199. frame: 6,
  103200. value: 0
  103201. });
  103202. animationPP2.setKeys(vignetteStretchKeys);
  103203. animationPP2.setEasingFunction(this._circleEase);
  103204. this._postProcessMove.animations.push(animationPP2);
  103205. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  103206. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  103207. this._postProcessMove.samples = 4;
  103208. this._webVRCamera.attachPostProcess(this._postProcessMove);
  103209. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  103210. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  103211. });
  103212. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  103213. };
  103214. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  103215. if (hit.pickedPoint) {
  103216. if (gazer._teleportationRequestInitiated) {
  103217. this._displayTeleportationTarget();
  103218. this._haloCenter.copyFrom(hit.pickedPoint);
  103219. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  103220. }
  103221. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  103222. if (pickNormal) {
  103223. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  103224. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  103225. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  103226. }
  103227. this._teleportationTarget.position.y += 0.1;
  103228. }
  103229. };
  103230. /**
  103231. * Teleports the users feet to the desired location
  103232. * @param location The location where the user's feet should be placed
  103233. */
  103234. VRExperienceHelper.prototype.teleportCamera = function (location) {
  103235. var _this = this;
  103236. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  103237. return;
  103238. }
  103239. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  103240. // offset of the headset from the anchor.
  103241. if (this.webVRCamera.leftCamera) {
  103242. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  103243. this._workingVector.subtractInPlace(this.webVRCamera.position);
  103244. location.subtractToRef(this._workingVector, this._workingVector);
  103245. }
  103246. else {
  103247. this._workingVector.copyFrom(location);
  103248. }
  103249. // Add height to account for user's height offset
  103250. if (this.isInVRMode) {
  103251. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  103252. }
  103253. else {
  103254. this._workingVector.y += this._defaultHeight;
  103255. }
  103256. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  103257. // Create animation from the camera's position to the new location
  103258. this.currentVRCamera.animations = [];
  103259. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103260. var animationCameraTeleportationKeys = [{
  103261. frame: 0,
  103262. value: this.currentVRCamera.position
  103263. },
  103264. {
  103265. frame: 11,
  103266. value: this._workingVector
  103267. }
  103268. ];
  103269. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  103270. animationCameraTeleportation.setEasingFunction(this._circleEase);
  103271. this.currentVRCamera.animations.push(animationCameraTeleportation);
  103272. this._postProcessMove.animations = [];
  103273. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103274. var vignetteWeightKeys = [];
  103275. vignetteWeightKeys.push({
  103276. frame: 0,
  103277. value: 0
  103278. });
  103279. vignetteWeightKeys.push({
  103280. frame: 5,
  103281. value: 8
  103282. });
  103283. vignetteWeightKeys.push({
  103284. frame: 11,
  103285. value: 0
  103286. });
  103287. animationPP.setKeys(vignetteWeightKeys);
  103288. this._postProcessMove.animations.push(animationPP);
  103289. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103290. var vignetteStretchKeys = [];
  103291. vignetteStretchKeys.push({
  103292. frame: 0,
  103293. value: 0
  103294. });
  103295. vignetteStretchKeys.push({
  103296. frame: 5,
  103297. value: 10
  103298. });
  103299. vignetteStretchKeys.push({
  103300. frame: 11,
  103301. value: 0
  103302. });
  103303. animationPP2.setKeys(vignetteStretchKeys);
  103304. this._postProcessMove.animations.push(animationPP2);
  103305. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  103306. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  103307. this._webVRCamera.attachPostProcess(this._postProcessMove);
  103308. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  103309. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  103310. });
  103311. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  103312. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  103313. });
  103314. this._hideTeleportationTarget();
  103315. };
  103316. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  103317. if (normal) {
  103318. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  103319. if (angle < Math.PI / 2) {
  103320. normal.scaleInPlace(-1);
  103321. }
  103322. }
  103323. return normal;
  103324. };
  103325. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  103326. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  103327. return;
  103328. }
  103329. var ray = gazer._getForwardRay(this._rayLength);
  103330. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103331. if (hit) {
  103332. // Populate the contrllers mesh that can be used for drag/drop
  103333. if (gazer._laserPointer) {
  103334. hit.originMesh = gazer._laserPointer.parent;
  103335. }
  103336. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  103337. }
  103338. gazer._currentHit = hit;
  103339. // Moving the gazeTracker on the mesh face targetted
  103340. if (hit && hit.pickedPoint) {
  103341. if (this._displayGaze) {
  103342. var multiplier = 1;
  103343. gazer._gazeTracker.isVisible = true;
  103344. if (gazer._isActionableMesh) {
  103345. multiplier = 3;
  103346. }
  103347. if (this.updateGazeTrackerScale) {
  103348. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  103349. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  103350. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  103351. }
  103352. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  103353. // To avoid z-fighting
  103354. var deltaFighting = 0.002;
  103355. if (pickNormal) {
  103356. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  103357. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  103358. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  103359. }
  103360. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  103361. if (gazer._gazeTracker.position.x < 0) {
  103362. gazer._gazeTracker.position.x += deltaFighting;
  103363. }
  103364. else {
  103365. gazer._gazeTracker.position.x -= deltaFighting;
  103366. }
  103367. if (gazer._gazeTracker.position.y < 0) {
  103368. gazer._gazeTracker.position.y += deltaFighting;
  103369. }
  103370. else {
  103371. gazer._gazeTracker.position.y -= deltaFighting;
  103372. }
  103373. if (gazer._gazeTracker.position.z < 0) {
  103374. gazer._gazeTracker.position.z += deltaFighting;
  103375. }
  103376. else {
  103377. gazer._gazeTracker.position.z -= deltaFighting;
  103378. }
  103379. }
  103380. // Changing the size of the laser pointer based on the distance from the targetted point
  103381. gazer._updatePointerDistance(hit.distance);
  103382. }
  103383. else {
  103384. gazer._updatePointerDistance();
  103385. gazer._gazeTracker.isVisible = false;
  103386. }
  103387. if (hit && hit.pickedMesh) {
  103388. // The object selected is the floor, we're in a teleportation scenario
  103389. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  103390. // Moving the teleportation area to this targetted point
  103391. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  103392. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  103393. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  103394. }
  103395. gazer._currentMeshSelected = null;
  103396. if (gazer._teleportationRequestInitiated) {
  103397. this._moveTeleportationSelectorTo(hit, gazer, ray);
  103398. }
  103399. return;
  103400. }
  103401. // If not, we're in a selection scenario
  103402. //this._teleportationAllowed = false;
  103403. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  103404. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  103405. this.onNewMeshPicked.notifyObservers(hit);
  103406. gazer._currentMeshSelected = hit.pickedMesh;
  103407. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  103408. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  103409. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  103410. gazer._isActionableMesh = true;
  103411. }
  103412. else {
  103413. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103414. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103415. gazer._isActionableMesh = false;
  103416. }
  103417. try {
  103418. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  103419. }
  103420. catch (err) {
  103421. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  103422. }
  103423. }
  103424. else {
  103425. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  103426. gazer._currentMeshSelected = null;
  103427. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103428. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103429. }
  103430. }
  103431. }
  103432. else {
  103433. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  103434. gazer._currentMeshSelected = null;
  103435. //this._teleportationAllowed = false;
  103436. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103437. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103438. }
  103439. };
  103440. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  103441. if (mesh) {
  103442. this.onSelectedMeshUnselected.notifyObservers(mesh);
  103443. }
  103444. };
  103445. /**
  103446. * Sets the color of the laser ray from the vr controllers.
  103447. * @param color new color for the ray.
  103448. */
  103449. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  103450. if (this._leftController) {
  103451. this._leftController._setLaserPointerColor(color);
  103452. }
  103453. if (this._rightController) {
  103454. this._rightController._setLaserPointerColor(color);
  103455. }
  103456. };
  103457. /**
  103458. * Sets the color of the ray from the vr headsets gaze.
  103459. * @param color new color for the ray.
  103460. */
  103461. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  103462. if (!this._cameraGazer._gazeTracker.material) {
  103463. return;
  103464. }
  103465. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  103466. if (this._leftController) {
  103467. this._leftController._gazeTracker.material.emissiveColor = color;
  103468. }
  103469. if (this._rightController) {
  103470. this._rightController._gazeTracker.material.emissiveColor = color;
  103471. }
  103472. };
  103473. /**
  103474. * Exits VR and disposes of the vr experience helper
  103475. */
  103476. VRExperienceHelper.prototype.dispose = function () {
  103477. if (this.isInVRMode) {
  103478. this.exitVR();
  103479. }
  103480. if (this._postProcessMove) {
  103481. this._postProcessMove.dispose();
  103482. }
  103483. if (this._webVRCamera) {
  103484. this._webVRCamera.dispose();
  103485. }
  103486. if (this._vrDeviceOrientationCamera) {
  103487. this._vrDeviceOrientationCamera.dispose();
  103488. }
  103489. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  103490. document.body.removeChild(this._btnVR);
  103491. }
  103492. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  103493. this._deviceOrientationCamera.dispose();
  103494. }
  103495. if (this._cameraGazer) {
  103496. this._cameraGazer.dispose();
  103497. }
  103498. if (this._leftController) {
  103499. this._leftController.dispose();
  103500. }
  103501. if (this._rightController) {
  103502. this._rightController.dispose();
  103503. }
  103504. if (this._teleportationTarget) {
  103505. this._teleportationTarget.dispose();
  103506. }
  103507. this._floorMeshesCollection = [];
  103508. document.removeEventListener("keydown", this._onKeyDown);
  103509. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103510. window.removeEventListener("resize", this._onResize);
  103511. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  103512. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  103513. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  103514. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  103515. document.onmsfullscreenchange = null;
  103516. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  103517. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  103518. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  103519. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103520. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  103521. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  103522. this._scene.unregisterBeforeRender(this.beforeRender);
  103523. };
  103524. /**
  103525. * Gets the name of the VRExperienceHelper class
  103526. * @returns "VRExperienceHelper"
  103527. */
  103528. VRExperienceHelper.prototype.getClassName = function () {
  103529. return "VRExperienceHelper";
  103530. };
  103531. return VRExperienceHelper;
  103532. }());
  103533. BABYLON.VRExperienceHelper = VRExperienceHelper;
  103534. })(BABYLON || (BABYLON = {}));
  103535. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  103536. // Mainly based on these 2 articles :
  103537. // 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
  103538. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  103539. var BABYLON;
  103540. (function (BABYLON) {
  103541. /**
  103542. * Defines the potential axis of a Joystick
  103543. */
  103544. var JoystickAxis;
  103545. (function (JoystickAxis) {
  103546. /** X axis */
  103547. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  103548. /** Y axis */
  103549. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  103550. /** Z axis */
  103551. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  103552. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  103553. /**
  103554. * Class used to define virtual joystick (used in touch mode)
  103555. */
  103556. var VirtualJoystick = /** @class */ (function () {
  103557. /**
  103558. * Creates a new virtual joystick
  103559. * @param leftJoystick defines that the joystick is for left hand (false by default)
  103560. */
  103561. function VirtualJoystick(leftJoystick) {
  103562. var _this = this;
  103563. if (leftJoystick) {
  103564. this._leftJoystick = true;
  103565. }
  103566. else {
  103567. this._leftJoystick = false;
  103568. }
  103569. VirtualJoystick._globalJoystickIndex++;
  103570. // By default left & right arrow keys are moving the X
  103571. // and up & down keys are moving the Y
  103572. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  103573. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  103574. this.reverseLeftRight = false;
  103575. this.reverseUpDown = false;
  103576. // collections of pointers
  103577. this._touches = new BABYLON.StringDictionary();
  103578. this.deltaPosition = BABYLON.Vector3.Zero();
  103579. this._joystickSensibility = 25;
  103580. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  103581. this._onResize = function (evt) {
  103582. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  103583. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  103584. if (VirtualJoystick.vjCanvas) {
  103585. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  103586. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  103587. }
  103588. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  103589. };
  103590. // injecting a canvas element on top of the canvas 3D game
  103591. if (!VirtualJoystick.vjCanvas) {
  103592. window.addEventListener("resize", this._onResize, false);
  103593. VirtualJoystick.vjCanvas = document.createElement("canvas");
  103594. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  103595. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  103596. VirtualJoystick.vjCanvas.width = window.innerWidth;
  103597. VirtualJoystick.vjCanvas.height = window.innerHeight;
  103598. VirtualJoystick.vjCanvas.style.width = "100%";
  103599. VirtualJoystick.vjCanvas.style.height = "100%";
  103600. VirtualJoystick.vjCanvas.style.position = "absolute";
  103601. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  103602. VirtualJoystick.vjCanvas.style.top = "0px";
  103603. VirtualJoystick.vjCanvas.style.left = "0px";
  103604. VirtualJoystick.vjCanvas.style.zIndex = "5";
  103605. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  103606. // Support for jQuery PEP polyfill
  103607. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  103608. var context = VirtualJoystick.vjCanvas.getContext('2d');
  103609. if (!context) {
  103610. throw new Error("Unable to create canvas for virtual joystick");
  103611. }
  103612. VirtualJoystick.vjCanvasContext = context;
  103613. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  103614. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  103615. document.body.appendChild(VirtualJoystick.vjCanvas);
  103616. }
  103617. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  103618. this.pressed = false;
  103619. // default joystick color
  103620. this._joystickColor = "cyan";
  103621. this._joystickPointerID = -1;
  103622. // current joystick position
  103623. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  103624. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  103625. // origin joystick position
  103626. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  103627. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  103628. this._onPointerDownHandlerRef = function (evt) {
  103629. _this._onPointerDown(evt);
  103630. };
  103631. this._onPointerMoveHandlerRef = function (evt) {
  103632. _this._onPointerMove(evt);
  103633. };
  103634. this._onPointerUpHandlerRef = function (evt) {
  103635. _this._onPointerUp(evt);
  103636. };
  103637. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  103638. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  103639. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  103640. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  103641. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  103642. evt.preventDefault(); // Disables system menu
  103643. }, false);
  103644. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  103645. }
  103646. /**
  103647. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  103648. * @param newJoystickSensibility defines the new sensibility
  103649. */
  103650. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  103651. this._joystickSensibility = newJoystickSensibility;
  103652. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  103653. };
  103654. VirtualJoystick.prototype._onPointerDown = function (e) {
  103655. var positionOnScreenCondition;
  103656. e.preventDefault();
  103657. if (this._leftJoystick === true) {
  103658. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  103659. }
  103660. else {
  103661. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  103662. }
  103663. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  103664. // First contact will be dedicated to the virtual joystick
  103665. this._joystickPointerID = e.pointerId;
  103666. this._joystickPointerStartPos.x = e.clientX;
  103667. this._joystickPointerStartPos.y = e.clientY;
  103668. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  103669. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  103670. this._deltaJoystickVector.x = 0;
  103671. this._deltaJoystickVector.y = 0;
  103672. this.pressed = true;
  103673. this._touches.add(e.pointerId.toString(), e);
  103674. }
  103675. else {
  103676. // You can only trigger the action buttons with a joystick declared
  103677. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  103678. this._action();
  103679. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  103680. }
  103681. }
  103682. };
  103683. VirtualJoystick.prototype._onPointerMove = function (e) {
  103684. // If the current pointer is the one associated to the joystick (first touch contact)
  103685. if (this._joystickPointerID == e.pointerId) {
  103686. this._joystickPointerPos.x = e.clientX;
  103687. this._joystickPointerPos.y = e.clientY;
  103688. this._deltaJoystickVector = this._joystickPointerPos.clone();
  103689. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  103690. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  103691. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  103692. switch (this._axisTargetedByLeftAndRight) {
  103693. case JoystickAxis.X:
  103694. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  103695. break;
  103696. case JoystickAxis.Y:
  103697. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  103698. break;
  103699. case JoystickAxis.Z:
  103700. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  103701. break;
  103702. }
  103703. var directionUpDown = this.reverseUpDown ? 1 : -1;
  103704. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  103705. switch (this._axisTargetedByUpAndDown) {
  103706. case JoystickAxis.X:
  103707. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  103708. break;
  103709. case JoystickAxis.Y:
  103710. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  103711. break;
  103712. case JoystickAxis.Z:
  103713. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  103714. break;
  103715. }
  103716. }
  103717. else {
  103718. var data = this._touches.get(e.pointerId.toString());
  103719. if (data) {
  103720. data.x = e.clientX;
  103721. data.y = e.clientY;
  103722. }
  103723. }
  103724. };
  103725. VirtualJoystick.prototype._onPointerUp = function (e) {
  103726. if (this._joystickPointerID == e.pointerId) {
  103727. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  103728. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  103729. this._joystickPointerID = -1;
  103730. this.pressed = false;
  103731. }
  103732. else {
  103733. var touch = this._touches.get(e.pointerId.toString());
  103734. if (touch) {
  103735. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  103736. }
  103737. }
  103738. this._deltaJoystickVector.x = 0;
  103739. this._deltaJoystickVector.y = 0;
  103740. this._touches.remove(e.pointerId.toString());
  103741. };
  103742. /**
  103743. * Change the color of the virtual joystick
  103744. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  103745. */
  103746. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  103747. this._joystickColor = newColor;
  103748. };
  103749. /**
  103750. * Defines a callback to call when the joystick is touched
  103751. * @param action defines the callback
  103752. */
  103753. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  103754. this._action = action;
  103755. };
  103756. /**
  103757. * Defines which axis you'd like to control for left & right
  103758. * @param axis defines the axis to use
  103759. */
  103760. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  103761. switch (axis) {
  103762. case JoystickAxis.X:
  103763. case JoystickAxis.Y:
  103764. case JoystickAxis.Z:
  103765. this._axisTargetedByLeftAndRight = axis;
  103766. break;
  103767. default:
  103768. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  103769. break;
  103770. }
  103771. };
  103772. /**
  103773. * Defines which axis you'd like to control for up & down
  103774. * @param axis defines the axis to use
  103775. */
  103776. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  103777. switch (axis) {
  103778. case JoystickAxis.X:
  103779. case JoystickAxis.Y:
  103780. case JoystickAxis.Z:
  103781. this._axisTargetedByUpAndDown = axis;
  103782. break;
  103783. default:
  103784. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  103785. break;
  103786. }
  103787. };
  103788. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  103789. var _this = this;
  103790. if (this.pressed) {
  103791. this._touches.forEach(function (key, touch) {
  103792. if (touch.pointerId === _this._joystickPointerID) {
  103793. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  103794. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  103795. VirtualJoystick.vjCanvasContext.beginPath();
  103796. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  103797. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103798. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  103799. VirtualJoystick.vjCanvasContext.stroke();
  103800. VirtualJoystick.vjCanvasContext.closePath();
  103801. VirtualJoystick.vjCanvasContext.beginPath();
  103802. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103803. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  103804. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  103805. VirtualJoystick.vjCanvasContext.stroke();
  103806. VirtualJoystick.vjCanvasContext.closePath();
  103807. VirtualJoystick.vjCanvasContext.beginPath();
  103808. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103809. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  103810. VirtualJoystick.vjCanvasContext.stroke();
  103811. VirtualJoystick.vjCanvasContext.closePath();
  103812. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  103813. }
  103814. else {
  103815. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  103816. VirtualJoystick.vjCanvasContext.beginPath();
  103817. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  103818. VirtualJoystick.vjCanvasContext.beginPath();
  103819. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  103820. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  103821. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  103822. VirtualJoystick.vjCanvasContext.stroke();
  103823. VirtualJoystick.vjCanvasContext.closePath();
  103824. touch.prevX = touch.x;
  103825. touch.prevY = touch.y;
  103826. }
  103827. ;
  103828. });
  103829. }
  103830. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  103831. };
  103832. /**
  103833. * Release internal HTML canvas
  103834. */
  103835. VirtualJoystick.prototype.releaseCanvas = function () {
  103836. if (VirtualJoystick.vjCanvas) {
  103837. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  103838. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  103839. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  103840. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  103841. window.removeEventListener("resize", this._onResize);
  103842. document.body.removeChild(VirtualJoystick.vjCanvas);
  103843. VirtualJoystick.vjCanvas = null;
  103844. }
  103845. };
  103846. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  103847. VirtualJoystick._globalJoystickIndex = 0;
  103848. return VirtualJoystick;
  103849. }());
  103850. BABYLON.VirtualJoystick = VirtualJoystick;
  103851. })(BABYLON || (BABYLON = {}));
  103852. //# sourceMappingURL=babylon.virtualJoystick.js.map
  103853. var BABYLON;
  103854. (function (BABYLON) {
  103855. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  103856. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  103857. });
  103858. /**
  103859. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  103860. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103861. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103862. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103863. */
  103864. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  103865. __extends(VirtualJoysticksCamera, _super);
  103866. /**
  103867. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  103868. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103869. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103870. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103871. * @param name Define the name of the camera in the scene
  103872. * @param position Define the start position of the camera in the scene
  103873. * @param scene Define the scene the camera belongs to
  103874. */
  103875. function VirtualJoysticksCamera(name, position, scene) {
  103876. var _this = _super.call(this, name, position, scene) || this;
  103877. _this.inputs.addVirtualJoystick();
  103878. return _this;
  103879. }
  103880. /**
  103881. * Gets the current object class name.
  103882. * @return the class name
  103883. */
  103884. VirtualJoysticksCamera.prototype.getClassName = function () {
  103885. return "VirtualJoysticksCamera";
  103886. };
  103887. return VirtualJoysticksCamera;
  103888. }(BABYLON.FreeCamera));
  103889. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  103890. })(BABYLON || (BABYLON = {}));
  103891. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  103892. var BABYLON;
  103893. (function (BABYLON) {
  103894. /**
  103895. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  103896. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103897. */
  103898. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  103899. function FreeCameraVirtualJoystickInput() {
  103900. }
  103901. /**
  103902. * Gets the left stick of the virtual joystick.
  103903. * @returns The virtual Joystick
  103904. */
  103905. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  103906. return this._leftjoystick;
  103907. };
  103908. /**
  103909. * Gets the right stick of the virtual joystick.
  103910. * @returns The virtual Joystick
  103911. */
  103912. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  103913. return this._rightjoystick;
  103914. };
  103915. /**
  103916. * Update the current camera state depending on the inputs that have been used this frame.
  103917. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103918. */
  103919. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  103920. if (this._leftjoystick) {
  103921. var camera = this.camera;
  103922. var speed = camera._computeLocalCameraSpeed() * 50;
  103923. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  103924. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  103925. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  103926. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  103927. if (!this._leftjoystick.pressed) {
  103928. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  103929. }
  103930. if (!this._rightjoystick.pressed) {
  103931. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  103932. }
  103933. }
  103934. };
  103935. /**
  103936. * Attach the input controls to a specific dom element to get the input from.
  103937. * @param element Defines the element the controls should be listened from
  103938. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103939. */
  103940. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  103941. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  103942. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  103943. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  103944. this._leftjoystick.setJoystickSensibility(0.15);
  103945. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  103946. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  103947. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  103948. this._rightjoystick.reverseUpDown = true;
  103949. this._rightjoystick.setJoystickSensibility(0.05);
  103950. this._rightjoystick.setJoystickColor("yellow");
  103951. };
  103952. /**
  103953. * Detach the current controls from the specified dom element.
  103954. * @param element Defines the element to stop listening the inputs from
  103955. */
  103956. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  103957. this._leftjoystick.releaseCanvas();
  103958. this._rightjoystick.releaseCanvas();
  103959. };
  103960. /**
  103961. * Gets the class name of the current intput.
  103962. * @returns the class name
  103963. */
  103964. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  103965. return "FreeCameraVirtualJoystickInput";
  103966. };
  103967. /**
  103968. * Get the friendly name associated with the input class.
  103969. * @returns the input friendly name
  103970. */
  103971. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  103972. return "virtualJoystick";
  103973. };
  103974. return FreeCameraVirtualJoystickInput;
  103975. }());
  103976. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  103977. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  103978. })(BABYLON || (BABYLON = {}));
  103979. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  103980. var BABYLON;
  103981. (function (BABYLON) {
  103982. /**
  103983. * Class used to specify simplification options
  103984. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103985. */
  103986. var SimplificationSettings = /** @class */ (function () {
  103987. /**
  103988. * Creates a SimplificationSettings
  103989. * @param quality expected quality
  103990. * @param distance distance when this optimized version should be used
  103991. * @param optimizeMesh already optimized mesh
  103992. */
  103993. function SimplificationSettings(
  103994. /** expected quality */
  103995. quality,
  103996. /** distance when this optimized version should be used */
  103997. distance,
  103998. /** already optimized mesh */
  103999. optimizeMesh) {
  104000. this.quality = quality;
  104001. this.distance = distance;
  104002. this.optimizeMesh = optimizeMesh;
  104003. }
  104004. return SimplificationSettings;
  104005. }());
  104006. BABYLON.SimplificationSettings = SimplificationSettings;
  104007. /**
  104008. * Queue used to order the simplification tasks
  104009. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104010. */
  104011. var SimplificationQueue = /** @class */ (function () {
  104012. /**
  104013. * Creates a new queue
  104014. */
  104015. function SimplificationQueue() {
  104016. this.running = false;
  104017. this._simplificationArray = [];
  104018. }
  104019. /**
  104020. * Adds a new simplification task
  104021. * @param task defines a task to add
  104022. */
  104023. SimplificationQueue.prototype.addTask = function (task) {
  104024. this._simplificationArray.push(task);
  104025. };
  104026. /**
  104027. * Execute next task
  104028. */
  104029. SimplificationQueue.prototype.executeNext = function () {
  104030. var task = this._simplificationArray.pop();
  104031. if (task) {
  104032. this.running = true;
  104033. this.runSimplification(task);
  104034. }
  104035. else {
  104036. this.running = false;
  104037. }
  104038. };
  104039. /**
  104040. * Execute a simplification task
  104041. * @param task defines the task to run
  104042. */
  104043. SimplificationQueue.prototype.runSimplification = function (task) {
  104044. var _this = this;
  104045. if (task.parallelProcessing) {
  104046. //parallel simplifier
  104047. task.settings.forEach(function (setting) {
  104048. var simplifier = _this.getSimplifier(task);
  104049. simplifier.simplify(setting, function (newMesh) {
  104050. task.mesh.addLODLevel(setting.distance, newMesh);
  104051. newMesh.isVisible = true;
  104052. //check if it is the last
  104053. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  104054. //all done, run the success callback.
  104055. task.successCallback();
  104056. }
  104057. _this.executeNext();
  104058. });
  104059. });
  104060. }
  104061. else {
  104062. //single simplifier.
  104063. var simplifier = this.getSimplifier(task);
  104064. var runDecimation = function (setting, callback) {
  104065. simplifier.simplify(setting, function (newMesh) {
  104066. task.mesh.addLODLevel(setting.distance, newMesh);
  104067. newMesh.isVisible = true;
  104068. //run the next quality level
  104069. callback();
  104070. });
  104071. };
  104072. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  104073. runDecimation(task.settings[loop.index], function () {
  104074. loop.executeNext();
  104075. });
  104076. }, function () {
  104077. //execution ended, run the success callback.
  104078. if (task.successCallback) {
  104079. task.successCallback();
  104080. }
  104081. _this.executeNext();
  104082. });
  104083. }
  104084. };
  104085. SimplificationQueue.prototype.getSimplifier = function (task) {
  104086. switch (task.simplificationType) {
  104087. case SimplificationType.QUADRATIC:
  104088. default:
  104089. return new QuadraticErrorSimplification(task.mesh);
  104090. }
  104091. };
  104092. return SimplificationQueue;
  104093. }());
  104094. BABYLON.SimplificationQueue = SimplificationQueue;
  104095. /**
  104096. * The implemented types of simplification
  104097. * At the moment only Quadratic Error Decimation is implemented
  104098. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104099. */
  104100. var SimplificationType;
  104101. (function (SimplificationType) {
  104102. /** Quadratic error decimation */
  104103. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  104104. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  104105. var DecimationTriangle = /** @class */ (function () {
  104106. function DecimationTriangle(vertices) {
  104107. this.vertices = vertices;
  104108. this.error = new Array(4);
  104109. this.deleted = false;
  104110. this.isDirty = false;
  104111. this.deletePending = false;
  104112. this.borderFactor = 0;
  104113. }
  104114. return DecimationTriangle;
  104115. }());
  104116. var DecimationVertex = /** @class */ (function () {
  104117. function DecimationVertex(position, id) {
  104118. this.position = position;
  104119. this.id = id;
  104120. this.isBorder = true;
  104121. this.q = new QuadraticMatrix();
  104122. this.triangleCount = 0;
  104123. this.triangleStart = 0;
  104124. this.originalOffsets = [];
  104125. }
  104126. DecimationVertex.prototype.updatePosition = function (newPosition) {
  104127. this.position.copyFrom(newPosition);
  104128. };
  104129. return DecimationVertex;
  104130. }());
  104131. var QuadraticMatrix = /** @class */ (function () {
  104132. function QuadraticMatrix(data) {
  104133. this.data = new Array(10);
  104134. for (var i = 0; i < 10; ++i) {
  104135. if (data && data[i]) {
  104136. this.data[i] = data[i];
  104137. }
  104138. else {
  104139. this.data[i] = 0;
  104140. }
  104141. }
  104142. }
  104143. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  104144. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  104145. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  104146. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  104147. return det;
  104148. };
  104149. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  104150. for (var i = 0; i < 10; ++i) {
  104151. this.data[i] += matrix.data[i];
  104152. }
  104153. };
  104154. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  104155. for (var i = 0; i < 10; ++i) {
  104156. this.data[i] += data[i];
  104157. }
  104158. };
  104159. QuadraticMatrix.prototype.add = function (matrix) {
  104160. var m = new QuadraticMatrix();
  104161. for (var i = 0; i < 10; ++i) {
  104162. m.data[i] = this.data[i] + matrix.data[i];
  104163. }
  104164. return m;
  104165. };
  104166. QuadraticMatrix.FromData = function (a, b, c, d) {
  104167. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  104168. };
  104169. //returning an array to avoid garbage collection
  104170. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  104171. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  104172. };
  104173. return QuadraticMatrix;
  104174. }());
  104175. var Reference = /** @class */ (function () {
  104176. function Reference(vertexId, triangleId) {
  104177. this.vertexId = vertexId;
  104178. this.triangleId = triangleId;
  104179. }
  104180. return Reference;
  104181. }());
  104182. /**
  104183. * An implementation of the Quadratic Error simplification algorithm.
  104184. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  104185. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  104186. * @author RaananW
  104187. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104188. */
  104189. var QuadraticErrorSimplification = /** @class */ (function () {
  104190. function QuadraticErrorSimplification(_mesh) {
  104191. this._mesh = _mesh;
  104192. this.syncIterations = 5000;
  104193. this.aggressiveness = 7;
  104194. this.decimationIterations = 100;
  104195. this.boundingBoxEpsilon = BABYLON.Epsilon;
  104196. }
  104197. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  104198. var _this = this;
  104199. this.initDecimatedMesh();
  104200. //iterating through the submeshes array, one after the other.
  104201. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  104202. _this.initWithMesh(loop.index, function () {
  104203. _this.runDecimation(settings, loop.index, function () {
  104204. loop.executeNext();
  104205. });
  104206. }, settings.optimizeMesh);
  104207. }, function () {
  104208. setTimeout(function () {
  104209. successCallback(_this._reconstructedMesh);
  104210. }, 0);
  104211. });
  104212. };
  104213. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  104214. var _this = this;
  104215. var targetCount = ~~(this.triangles.length * settings.quality);
  104216. var deletedTriangles = 0;
  104217. var triangleCount = this.triangles.length;
  104218. var iterationFunction = function (iteration, callback) {
  104219. setTimeout(function () {
  104220. if (iteration % 5 === 0) {
  104221. _this.updateMesh(iteration === 0);
  104222. }
  104223. for (var i = 0; i < _this.triangles.length; ++i) {
  104224. _this.triangles[i].isDirty = false;
  104225. }
  104226. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  104227. var trianglesIterator = function (i) {
  104228. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  104229. var t = _this.triangles[tIdx];
  104230. if (!t)
  104231. return;
  104232. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  104233. return;
  104234. }
  104235. for (var j = 0; j < 3; ++j) {
  104236. if (t.error[j] < threshold) {
  104237. var deleted0 = [];
  104238. var deleted1 = [];
  104239. var v0 = t.vertices[j];
  104240. var v1 = t.vertices[(j + 1) % 3];
  104241. if (v0.isBorder || v1.isBorder)
  104242. continue;
  104243. var p = BABYLON.Vector3.Zero();
  104244. var n = BABYLON.Vector3.Zero();
  104245. var uv = BABYLON.Vector2.Zero();
  104246. var color = new BABYLON.Color4(0, 0, 0, 1);
  104247. _this.calculateError(v0, v1, p, n, uv, color);
  104248. var delTr = new Array();
  104249. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  104250. continue;
  104251. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  104252. continue;
  104253. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  104254. continue;
  104255. var uniqueArray = new Array();
  104256. delTr.forEach(function (deletedT) {
  104257. if (uniqueArray.indexOf(deletedT) === -1) {
  104258. deletedT.deletePending = true;
  104259. uniqueArray.push(deletedT);
  104260. }
  104261. });
  104262. if (uniqueArray.length % 2 !== 0) {
  104263. continue;
  104264. }
  104265. v0.q = v1.q.add(v0.q);
  104266. v0.updatePosition(p);
  104267. var tStart = _this.references.length;
  104268. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  104269. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  104270. var tCount = _this.references.length - tStart;
  104271. if (tCount <= v0.triangleCount) {
  104272. if (tCount) {
  104273. for (var c = 0; c < tCount; c++) {
  104274. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  104275. }
  104276. }
  104277. }
  104278. else {
  104279. v0.triangleStart = tStart;
  104280. }
  104281. v0.triangleCount = tCount;
  104282. break;
  104283. }
  104284. }
  104285. };
  104286. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  104287. }, 0);
  104288. };
  104289. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  104290. if (triangleCount - deletedTriangles <= targetCount)
  104291. loop.breakLoop();
  104292. else {
  104293. iterationFunction(loop.index, function () {
  104294. loop.executeNext();
  104295. });
  104296. }
  104297. }, function () {
  104298. setTimeout(function () {
  104299. //reconstruct this part of the mesh
  104300. _this.reconstructMesh(submeshIndex);
  104301. successCallback();
  104302. }, 0);
  104303. });
  104304. };
  104305. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  104306. var _this = this;
  104307. this.vertices = [];
  104308. this.triangles = [];
  104309. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104310. var indices = this._mesh.getIndices();
  104311. var submesh = this._mesh.subMeshes[submeshIndex];
  104312. var findInVertices = function (positionToSearch) {
  104313. if (optimizeMesh) {
  104314. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  104315. if (_this.vertices[ii].position.equals(positionToSearch)) {
  104316. return _this.vertices[ii];
  104317. }
  104318. }
  104319. }
  104320. return null;
  104321. };
  104322. var vertexReferences = [];
  104323. var vertexInit = function (i) {
  104324. if (!positionData) {
  104325. return;
  104326. }
  104327. var offset = i + submesh.verticesStart;
  104328. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  104329. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  104330. vertex.originalOffsets.push(offset);
  104331. if (vertex.id === _this.vertices.length) {
  104332. _this.vertices.push(vertex);
  104333. }
  104334. vertexReferences.push(vertex.id);
  104335. };
  104336. //var totalVertices = mesh.getTotalVertices();
  104337. var totalVertices = submesh.verticesCount;
  104338. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  104339. var indicesInit = function (i) {
  104340. if (!indices) {
  104341. return;
  104342. }
  104343. var offset = (submesh.indexStart / 3) + i;
  104344. var pos = (offset * 3);
  104345. var i0 = indices[pos + 0];
  104346. var i1 = indices[pos + 1];
  104347. var i2 = indices[pos + 2];
  104348. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  104349. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  104350. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  104351. var triangle = new DecimationTriangle([v0, v1, v2]);
  104352. triangle.originalOffset = pos;
  104353. _this.triangles.push(triangle);
  104354. };
  104355. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  104356. _this.init(callback);
  104357. });
  104358. });
  104359. };
  104360. QuadraticErrorSimplification.prototype.init = function (callback) {
  104361. var _this = this;
  104362. var triangleInit1 = function (i) {
  104363. var t = _this.triangles[i];
  104364. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  104365. for (var j = 0; j < 3; j++) {
  104366. 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))));
  104367. }
  104368. };
  104369. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  104370. var triangleInit2 = function (i) {
  104371. var t = _this.triangles[i];
  104372. for (var j = 0; j < 3; ++j) {
  104373. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  104374. }
  104375. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  104376. };
  104377. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  104378. callback();
  104379. });
  104380. });
  104381. };
  104382. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  104383. var newTriangles = [];
  104384. var i;
  104385. for (i = 0; i < this.vertices.length; ++i) {
  104386. this.vertices[i].triangleCount = 0;
  104387. }
  104388. var t;
  104389. var j;
  104390. for (i = 0; i < this.triangles.length; ++i) {
  104391. if (!this.triangles[i].deleted) {
  104392. t = this.triangles[i];
  104393. for (j = 0; j < 3; ++j) {
  104394. t.vertices[j].triangleCount = 1;
  104395. }
  104396. newTriangles.push(t);
  104397. }
  104398. }
  104399. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  104400. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  104401. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  104402. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  104403. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  104404. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  104405. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  104406. var vertexCount = 0;
  104407. for (i = 0; i < this.vertices.length; ++i) {
  104408. var vertex = this.vertices[i];
  104409. vertex.id = vertexCount;
  104410. if (vertex.triangleCount) {
  104411. vertex.originalOffsets.forEach(function (originalOffset) {
  104412. if (!normalData) {
  104413. return;
  104414. }
  104415. newPositionData.push(vertex.position.x);
  104416. newPositionData.push(vertex.position.y);
  104417. newPositionData.push(vertex.position.z);
  104418. newNormalData.push(normalData[originalOffset * 3]);
  104419. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  104420. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  104421. if (uvs && uvs.length) {
  104422. newUVsData.push(uvs[(originalOffset * 2)]);
  104423. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  104424. }
  104425. else if (colorsData && colorsData.length) {
  104426. newColorsData.push(colorsData[(originalOffset * 4)]);
  104427. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  104428. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  104429. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  104430. }
  104431. ++vertexCount;
  104432. });
  104433. }
  104434. }
  104435. var startingIndex = this._reconstructedMesh.getTotalIndices();
  104436. var startingVertex = this._reconstructedMesh.getTotalVertices();
  104437. var submeshesArray = this._reconstructedMesh.subMeshes;
  104438. this._reconstructedMesh.subMeshes = [];
  104439. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  104440. var originalIndices = this._mesh.getIndices();
  104441. for (i = 0; i < newTriangles.length; ++i) {
  104442. t = newTriangles[i]; //now get the new referencing point for each vertex
  104443. [0, 1, 2].forEach(function (idx) {
  104444. var id = originalIndices[t.originalOffset + idx];
  104445. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  104446. if (offset < 0)
  104447. offset = 0;
  104448. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  104449. });
  104450. }
  104451. //overwriting the old vertex buffers and indices.
  104452. this._reconstructedMesh.setIndices(newIndicesArray);
  104453. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  104454. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  104455. if (newUVsData.length > 0)
  104456. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  104457. if (newColorsData.length > 0)
  104458. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  104459. //create submesh
  104460. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  104461. if (submeshIndex > 0) {
  104462. this._reconstructedMesh.subMeshes = [];
  104463. submeshesArray.forEach(function (submesh) {
  104464. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  104465. });
  104466. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  104467. }
  104468. };
  104469. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  104470. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  104471. this._reconstructedMesh.material = this._mesh.material;
  104472. this._reconstructedMesh.parent = this._mesh.parent;
  104473. this._reconstructedMesh.isVisible = false;
  104474. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  104475. };
  104476. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  104477. for (var i = 0; i < vertex1.triangleCount; ++i) {
  104478. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  104479. if (t.deleted)
  104480. continue;
  104481. var s = this.references[vertex1.triangleStart + i].vertexId;
  104482. var v1 = t.vertices[(s + 1) % 3];
  104483. var v2 = t.vertices[(s + 2) % 3];
  104484. if ((v1 === vertex2 || v2 === vertex2)) {
  104485. deletedArray[i] = true;
  104486. delTr.push(t);
  104487. continue;
  104488. }
  104489. var d1 = v1.position.subtract(point);
  104490. d1 = d1.normalize();
  104491. var d2 = v2.position.subtract(point);
  104492. d2 = d2.normalize();
  104493. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  104494. return true;
  104495. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  104496. deletedArray[i] = false;
  104497. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  104498. return true;
  104499. }
  104500. return false;
  104501. };
  104502. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  104503. var newDeleted = deletedTriangles;
  104504. for (var i = 0; i < vertex.triangleCount; ++i) {
  104505. var ref = this.references[vertex.triangleStart + i];
  104506. var t = this.triangles[ref.triangleId];
  104507. if (t.deleted)
  104508. continue;
  104509. if (deletedArray[i] && t.deletePending) {
  104510. t.deleted = true;
  104511. newDeleted++;
  104512. continue;
  104513. }
  104514. t.vertices[ref.vertexId] = origVertex;
  104515. t.isDirty = true;
  104516. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  104517. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  104518. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  104519. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  104520. this.references.push(ref);
  104521. }
  104522. return newDeleted;
  104523. };
  104524. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  104525. for (var i = 0; i < this.vertices.length; ++i) {
  104526. var vCount = [];
  104527. var vId = [];
  104528. var v = this.vertices[i];
  104529. var j;
  104530. for (j = 0; j < v.triangleCount; ++j) {
  104531. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  104532. for (var ii = 0; ii < 3; ii++) {
  104533. var ofs = 0;
  104534. var vv = triangle.vertices[ii];
  104535. while (ofs < vCount.length) {
  104536. if (vId[ofs] === vv.id)
  104537. break;
  104538. ++ofs;
  104539. }
  104540. if (ofs === vCount.length) {
  104541. vCount.push(1);
  104542. vId.push(vv.id);
  104543. }
  104544. else {
  104545. vCount[ofs]++;
  104546. }
  104547. }
  104548. }
  104549. for (j = 0; j < vCount.length; ++j) {
  104550. if (vCount[j] === 1) {
  104551. this.vertices[vId[j]].isBorder = true;
  104552. }
  104553. else {
  104554. this.vertices[vId[j]].isBorder = false;
  104555. }
  104556. }
  104557. }
  104558. };
  104559. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  104560. if (identifyBorders === void 0) { identifyBorders = false; }
  104561. var i;
  104562. if (!identifyBorders) {
  104563. var newTrianglesVector = [];
  104564. for (i = 0; i < this.triangles.length; ++i) {
  104565. if (!this.triangles[i].deleted) {
  104566. newTrianglesVector.push(this.triangles[i]);
  104567. }
  104568. }
  104569. this.triangles = newTrianglesVector;
  104570. }
  104571. for (i = 0; i < this.vertices.length; ++i) {
  104572. this.vertices[i].triangleCount = 0;
  104573. this.vertices[i].triangleStart = 0;
  104574. }
  104575. var t;
  104576. var j;
  104577. var v;
  104578. for (i = 0; i < this.triangles.length; ++i) {
  104579. t = this.triangles[i];
  104580. for (j = 0; j < 3; ++j) {
  104581. v = t.vertices[j];
  104582. v.triangleCount++;
  104583. }
  104584. }
  104585. var tStart = 0;
  104586. for (i = 0; i < this.vertices.length; ++i) {
  104587. this.vertices[i].triangleStart = tStart;
  104588. tStart += this.vertices[i].triangleCount;
  104589. this.vertices[i].triangleCount = 0;
  104590. }
  104591. var newReferences = new Array(this.triangles.length * 3);
  104592. for (i = 0; i < this.triangles.length; ++i) {
  104593. t = this.triangles[i];
  104594. for (j = 0; j < 3; ++j) {
  104595. v = t.vertices[j];
  104596. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  104597. v.triangleCount++;
  104598. }
  104599. }
  104600. this.references = newReferences;
  104601. if (identifyBorders) {
  104602. this.identifyBorder();
  104603. }
  104604. };
  104605. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  104606. var x = point.x;
  104607. var y = point.y;
  104608. var z = point.z;
  104609. 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
  104610. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  104611. };
  104612. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  104613. var q = vertex1.q.add(vertex2.q);
  104614. var border = vertex1.isBorder && vertex2.isBorder;
  104615. var error = 0;
  104616. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  104617. if (qDet !== 0 && !border) {
  104618. if (!pointResult) {
  104619. pointResult = BABYLON.Vector3.Zero();
  104620. }
  104621. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  104622. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  104623. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  104624. error = this.vertexError(q, pointResult);
  104625. }
  104626. else {
  104627. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  104628. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  104629. var error1 = this.vertexError(q, vertex1.position);
  104630. var error2 = this.vertexError(q, vertex2.position);
  104631. var error3 = this.vertexError(q, p3);
  104632. error = Math.min(error1, error2, error3);
  104633. if (error === error1) {
  104634. if (pointResult) {
  104635. pointResult.copyFrom(vertex1.position);
  104636. }
  104637. }
  104638. else if (error === error2) {
  104639. if (pointResult) {
  104640. pointResult.copyFrom(vertex2.position);
  104641. }
  104642. }
  104643. else {
  104644. if (pointResult) {
  104645. pointResult.copyFrom(p3);
  104646. }
  104647. }
  104648. }
  104649. return error;
  104650. };
  104651. return QuadraticErrorSimplification;
  104652. }());
  104653. })(BABYLON || (BABYLON = {}));
  104654. //# sourceMappingURL=babylon.meshSimplification.js.map
  104655. var BABYLON;
  104656. (function (BABYLON) {
  104657. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  104658. get: function () {
  104659. if (!this._simplificationQueue) {
  104660. this._simplificationQueue = new BABYLON.SimplificationQueue();
  104661. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  104662. if (!component) {
  104663. component = new SimplicationQueueSceneComponent(this);
  104664. this._addComponent(component);
  104665. }
  104666. }
  104667. return this._simplificationQueue;
  104668. },
  104669. set: function (value) {
  104670. this._simplificationQueue = value;
  104671. },
  104672. enumerable: true,
  104673. configurable: true
  104674. });
  104675. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  104676. if (parallelProcessing === void 0) { parallelProcessing = true; }
  104677. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  104678. this.getScene().simplificationQueue.addTask({
  104679. settings: settings,
  104680. parallelProcessing: parallelProcessing,
  104681. mesh: this,
  104682. simplificationType: simplificationType,
  104683. successCallback: successCallback
  104684. });
  104685. return this;
  104686. };
  104687. /**
  104688. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  104689. * created in a scene
  104690. */
  104691. var SimplicationQueueSceneComponent = /** @class */ (function () {
  104692. /**
  104693. * Creates a new instance of the component for the given scene
  104694. * @param scene Defines the scene to register the component in
  104695. */
  104696. function SimplicationQueueSceneComponent(scene) {
  104697. /**
  104698. * The component name helpfull to identify the component in the list of scene components.
  104699. */
  104700. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  104701. this.scene = scene;
  104702. }
  104703. /**
  104704. * Registers the component in a given scene
  104705. */
  104706. SimplicationQueueSceneComponent.prototype.register = function () {
  104707. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  104708. };
  104709. /**
  104710. * Rebuilds the elements related to this component in case of
  104711. * context lost for instance.
  104712. */
  104713. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  104714. // Nothing to do for this component
  104715. };
  104716. /**
  104717. * Disposes the component and the associated ressources
  104718. */
  104719. SimplicationQueueSceneComponent.prototype.dispose = function () {
  104720. // Nothing to do for this component
  104721. };
  104722. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  104723. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  104724. this.scene._simplificationQueue.executeNext();
  104725. }
  104726. };
  104727. return SimplicationQueueSceneComponent;
  104728. }());
  104729. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  104730. })(BABYLON || (BABYLON = {}));
  104731. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  104732. var BABYLON;
  104733. (function (BABYLON) {
  104734. /**
  104735. * Class used to represent a specific level of detail of a mesh
  104736. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  104737. */
  104738. var MeshLODLevel = /** @class */ (function () {
  104739. /**
  104740. * Creates a new LOD level
  104741. * @param distance defines the distance where this level should star being displayed
  104742. * @param mesh defines the mesh to use to render this level
  104743. */
  104744. function MeshLODLevel(
  104745. /** Defines the distance where this level should star being displayed */
  104746. distance,
  104747. /** Defines the mesh to use to render this level */
  104748. mesh) {
  104749. this.distance = distance;
  104750. this.mesh = mesh;
  104751. }
  104752. return MeshLODLevel;
  104753. }());
  104754. BABYLON.MeshLODLevel = MeshLODLevel;
  104755. })(BABYLON || (BABYLON = {}));
  104756. //# sourceMappingURL=babylon.meshLODLevel.js.map
  104757. var BABYLON;
  104758. (function (BABYLON) {
  104759. /**
  104760. * Defines the root class used to create scene optimization to use with SceneOptimizer
  104761. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104762. */
  104763. var SceneOptimization = /** @class */ (function () {
  104764. /**
  104765. * Creates the SceneOptimization object
  104766. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104767. * @param desc defines the description associated with the optimization
  104768. */
  104769. function SceneOptimization(
  104770. /**
  104771. * Defines the priority of this optimization (0 by default which means first in the list)
  104772. */
  104773. priority) {
  104774. if (priority === void 0) { priority = 0; }
  104775. this.priority = priority;
  104776. }
  104777. /**
  104778. * Gets a string describing the action executed by the current optimization
  104779. * @returns description string
  104780. */
  104781. SceneOptimization.prototype.getDescription = function () {
  104782. return "";
  104783. };
  104784. /**
  104785. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104786. * @param scene defines the current scene where to apply this optimization
  104787. * @param optimizer defines the current optimizer
  104788. * @returns true if everything that can be done was applied
  104789. */
  104790. SceneOptimization.prototype.apply = function (scene, optimizer) {
  104791. return true;
  104792. };
  104793. ;
  104794. return SceneOptimization;
  104795. }());
  104796. BABYLON.SceneOptimization = SceneOptimization;
  104797. /**
  104798. * Defines an optimization used to reduce the size of render target textures
  104799. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104800. */
  104801. var TextureOptimization = /** @class */ (function (_super) {
  104802. __extends(TextureOptimization, _super);
  104803. /**
  104804. * Creates the TextureOptimization object
  104805. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104806. * @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
  104807. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104808. */
  104809. function TextureOptimization(
  104810. /**
  104811. * Defines the priority of this optimization (0 by default which means first in the list)
  104812. */
  104813. priority,
  104814. /**
  104815. * 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
  104816. */
  104817. maximumSize,
  104818. /**
  104819. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104820. */
  104821. step) {
  104822. if (priority === void 0) { priority = 0; }
  104823. if (maximumSize === void 0) { maximumSize = 1024; }
  104824. if (step === void 0) { step = 0.5; }
  104825. var _this = _super.call(this, priority) || this;
  104826. _this.priority = priority;
  104827. _this.maximumSize = maximumSize;
  104828. _this.step = step;
  104829. return _this;
  104830. }
  104831. /**
  104832. * Gets a string describing the action executed by the current optimization
  104833. * @returns description string
  104834. */
  104835. TextureOptimization.prototype.getDescription = function () {
  104836. return "Reducing render target texture size to " + this.maximumSize;
  104837. };
  104838. /**
  104839. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104840. * @param scene defines the current scene where to apply this optimization
  104841. * @param optimizer defines the current optimizer
  104842. * @returns true if everything that can be done was applied
  104843. */
  104844. TextureOptimization.prototype.apply = function (scene, optimizer) {
  104845. var allDone = true;
  104846. for (var index = 0; index < scene.textures.length; index++) {
  104847. var texture = scene.textures[index];
  104848. if (!texture.canRescale || texture.getContext) {
  104849. continue;
  104850. }
  104851. var currentSize = texture.getSize();
  104852. var maxDimension = Math.max(currentSize.width, currentSize.height);
  104853. if (maxDimension > this.maximumSize) {
  104854. texture.scale(this.step);
  104855. allDone = false;
  104856. }
  104857. }
  104858. return allDone;
  104859. };
  104860. return TextureOptimization;
  104861. }(SceneOptimization));
  104862. BABYLON.TextureOptimization = TextureOptimization;
  104863. /**
  104864. * Defines an optimization used to increase or decrease the rendering resolution
  104865. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104866. */
  104867. var HardwareScalingOptimization = /** @class */ (function (_super) {
  104868. __extends(HardwareScalingOptimization, _super);
  104869. /**
  104870. * Creates the HardwareScalingOptimization object
  104871. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104872. * @param maximumScale defines the maximum scale to use (2 by default)
  104873. * @param step defines the step to use between two passes (0.5 by default)
  104874. */
  104875. function HardwareScalingOptimization(
  104876. /**
  104877. * Defines the priority of this optimization (0 by default which means first in the list)
  104878. */
  104879. priority,
  104880. /**
  104881. * Defines the maximum scale to use (2 by default)
  104882. */
  104883. maximumScale,
  104884. /**
  104885. * Defines the step to use between two passes (0.5 by default)
  104886. */
  104887. step) {
  104888. if (priority === void 0) { priority = 0; }
  104889. if (maximumScale === void 0) { maximumScale = 2; }
  104890. if (step === void 0) { step = 0.25; }
  104891. var _this = _super.call(this, priority) || this;
  104892. _this.priority = priority;
  104893. _this.maximumScale = maximumScale;
  104894. _this.step = step;
  104895. _this._currentScale = -1;
  104896. _this._directionOffset = 1;
  104897. return _this;
  104898. }
  104899. /**
  104900. * Gets a string describing the action executed by the current optimization
  104901. * @return description string
  104902. */
  104903. HardwareScalingOptimization.prototype.getDescription = function () {
  104904. return "Setting hardware scaling level to " + this._currentScale;
  104905. };
  104906. /**
  104907. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104908. * @param scene defines the current scene where to apply this optimization
  104909. * @param optimizer defines the current optimizer
  104910. * @returns true if everything that can be done was applied
  104911. */
  104912. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  104913. if (this._currentScale === -1) {
  104914. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  104915. if (this._currentScale > this.maximumScale) {
  104916. this._directionOffset = -1;
  104917. }
  104918. }
  104919. this._currentScale += this._directionOffset * this.step;
  104920. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  104921. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  104922. };
  104923. ;
  104924. return HardwareScalingOptimization;
  104925. }(SceneOptimization));
  104926. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  104927. /**
  104928. * Defines an optimization used to remove shadows
  104929. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104930. */
  104931. var ShadowsOptimization = /** @class */ (function (_super) {
  104932. __extends(ShadowsOptimization, _super);
  104933. function ShadowsOptimization() {
  104934. return _super !== null && _super.apply(this, arguments) || this;
  104935. }
  104936. /**
  104937. * Gets a string describing the action executed by the current optimization
  104938. * @return description string
  104939. */
  104940. ShadowsOptimization.prototype.getDescription = function () {
  104941. return "Turning shadows on/off";
  104942. };
  104943. /**
  104944. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104945. * @param scene defines the current scene where to apply this optimization
  104946. * @param optimizer defines the current optimizer
  104947. * @returns true if everything that can be done was applied
  104948. */
  104949. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  104950. scene.shadowsEnabled = optimizer.isInImprovementMode;
  104951. return true;
  104952. };
  104953. ;
  104954. return ShadowsOptimization;
  104955. }(SceneOptimization));
  104956. BABYLON.ShadowsOptimization = ShadowsOptimization;
  104957. /**
  104958. * Defines an optimization used to turn post-processes off
  104959. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104960. */
  104961. var PostProcessesOptimization = /** @class */ (function (_super) {
  104962. __extends(PostProcessesOptimization, _super);
  104963. function PostProcessesOptimization() {
  104964. return _super !== null && _super.apply(this, arguments) || this;
  104965. }
  104966. /**
  104967. * Gets a string describing the action executed by the current optimization
  104968. * @return description string
  104969. */
  104970. PostProcessesOptimization.prototype.getDescription = function () {
  104971. return "Turning post-processes on/off";
  104972. };
  104973. /**
  104974. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104975. * @param scene defines the current scene where to apply this optimization
  104976. * @param optimizer defines the current optimizer
  104977. * @returns true if everything that can be done was applied
  104978. */
  104979. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  104980. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  104981. return true;
  104982. };
  104983. ;
  104984. return PostProcessesOptimization;
  104985. }(SceneOptimization));
  104986. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  104987. /**
  104988. * Defines an optimization used to turn lens flares off
  104989. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104990. */
  104991. var LensFlaresOptimization = /** @class */ (function (_super) {
  104992. __extends(LensFlaresOptimization, _super);
  104993. function LensFlaresOptimization() {
  104994. return _super !== null && _super.apply(this, arguments) || this;
  104995. }
  104996. /**
  104997. * Gets a string describing the action executed by the current optimization
  104998. * @return description string
  104999. */
  105000. LensFlaresOptimization.prototype.getDescription = function () {
  105001. return "Turning lens flares on/off";
  105002. };
  105003. /**
  105004. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105005. * @param scene defines the current scene where to apply this optimization
  105006. * @param optimizer defines the current optimizer
  105007. * @returns true if everything that can be done was applied
  105008. */
  105009. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  105010. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  105011. return true;
  105012. };
  105013. ;
  105014. return LensFlaresOptimization;
  105015. }(SceneOptimization));
  105016. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  105017. /**
  105018. * Defines an optimization based on user defined callback.
  105019. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105020. */
  105021. var CustomOptimization = /** @class */ (function (_super) {
  105022. __extends(CustomOptimization, _super);
  105023. function CustomOptimization() {
  105024. return _super !== null && _super.apply(this, arguments) || this;
  105025. }
  105026. /**
  105027. * Gets a string describing the action executed by the current optimization
  105028. * @returns description string
  105029. */
  105030. CustomOptimization.prototype.getDescription = function () {
  105031. if (this.onGetDescription) {
  105032. return this.onGetDescription();
  105033. }
  105034. return "Running user defined callback";
  105035. };
  105036. /**
  105037. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105038. * @param scene defines the current scene where to apply this optimization
  105039. * @param optimizer defines the current optimizer
  105040. * @returns true if everything that can be done was applied
  105041. */
  105042. CustomOptimization.prototype.apply = function (scene, optimizer) {
  105043. if (this.onApply) {
  105044. return this.onApply(scene, optimizer);
  105045. }
  105046. return true;
  105047. };
  105048. ;
  105049. return CustomOptimization;
  105050. }(SceneOptimization));
  105051. BABYLON.CustomOptimization = CustomOptimization;
  105052. /**
  105053. * Defines an optimization used to turn particles off
  105054. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105055. */
  105056. var ParticlesOptimization = /** @class */ (function (_super) {
  105057. __extends(ParticlesOptimization, _super);
  105058. function ParticlesOptimization() {
  105059. return _super !== null && _super.apply(this, arguments) || this;
  105060. }
  105061. /**
  105062. * Gets a string describing the action executed by the current optimization
  105063. * @return description string
  105064. */
  105065. ParticlesOptimization.prototype.getDescription = function () {
  105066. return "Turning particles on/off";
  105067. };
  105068. /**
  105069. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105070. * @param scene defines the current scene where to apply this optimization
  105071. * @param optimizer defines the current optimizer
  105072. * @returns true if everything that can be done was applied
  105073. */
  105074. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  105075. scene.particlesEnabled = optimizer.isInImprovementMode;
  105076. return true;
  105077. };
  105078. ;
  105079. return ParticlesOptimization;
  105080. }(SceneOptimization));
  105081. BABYLON.ParticlesOptimization = ParticlesOptimization;
  105082. /**
  105083. * Defines an optimization used to turn render targets off
  105084. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105085. */
  105086. var RenderTargetsOptimization = /** @class */ (function (_super) {
  105087. __extends(RenderTargetsOptimization, _super);
  105088. function RenderTargetsOptimization() {
  105089. return _super !== null && _super.apply(this, arguments) || this;
  105090. }
  105091. /**
  105092. * Gets a string describing the action executed by the current optimization
  105093. * @return description string
  105094. */
  105095. RenderTargetsOptimization.prototype.getDescription = function () {
  105096. return "Turning render targets off";
  105097. };
  105098. /**
  105099. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105100. * @param scene defines the current scene where to apply this optimization
  105101. * @param optimizer defines the current optimizer
  105102. * @returns true if everything that can be done was applied
  105103. */
  105104. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  105105. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  105106. return true;
  105107. };
  105108. ;
  105109. return RenderTargetsOptimization;
  105110. }(SceneOptimization));
  105111. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  105112. /**
  105113. * Defines an optimization used to merge meshes with compatible materials
  105114. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105115. */
  105116. var MergeMeshesOptimization = /** @class */ (function (_super) {
  105117. __extends(MergeMeshesOptimization, _super);
  105118. function MergeMeshesOptimization() {
  105119. var _this = _super !== null && _super.apply(this, arguments) || this;
  105120. _this._canBeMerged = function (abstractMesh) {
  105121. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  105122. return false;
  105123. }
  105124. var mesh = abstractMesh;
  105125. if (mesh.isDisposed()) {
  105126. return false;
  105127. }
  105128. if (!mesh.isVisible || !mesh.isEnabled()) {
  105129. return false;
  105130. }
  105131. if (mesh.instances.length > 0) {
  105132. return false;
  105133. }
  105134. if (mesh.skeleton || mesh.hasLODLevels) {
  105135. return false;
  105136. }
  105137. return true;
  105138. };
  105139. return _this;
  105140. }
  105141. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  105142. /**
  105143. * Gets or sets a boolean which defines if optimization octree has to be updated
  105144. */
  105145. get: function () {
  105146. return MergeMeshesOptimization._UpdateSelectionTree;
  105147. },
  105148. /**
  105149. * Gets or sets a boolean which defines if optimization octree has to be updated
  105150. */
  105151. set: function (value) {
  105152. MergeMeshesOptimization._UpdateSelectionTree = value;
  105153. },
  105154. enumerable: true,
  105155. configurable: true
  105156. });
  105157. /**
  105158. * Gets a string describing the action executed by the current optimization
  105159. * @return description string
  105160. */
  105161. MergeMeshesOptimization.prototype.getDescription = function () {
  105162. return "Merging similar meshes together";
  105163. };
  105164. /**
  105165. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105166. * @param scene defines the current scene where to apply this optimization
  105167. * @param optimizer defines the current optimizer
  105168. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  105169. * @returns true if everything that can be done was applied
  105170. */
  105171. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  105172. var globalPool = scene.meshes.slice(0);
  105173. var globalLength = globalPool.length;
  105174. for (var index = 0; index < globalLength; index++) {
  105175. var currentPool = new Array();
  105176. var current = globalPool[index];
  105177. // Checks
  105178. if (!this._canBeMerged(current)) {
  105179. continue;
  105180. }
  105181. currentPool.push(current);
  105182. // Find compatible meshes
  105183. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  105184. var otherMesh = globalPool[subIndex];
  105185. if (!this._canBeMerged(otherMesh)) {
  105186. continue;
  105187. }
  105188. if (otherMesh.material !== current.material) {
  105189. continue;
  105190. }
  105191. if (otherMesh.checkCollisions !== current.checkCollisions) {
  105192. continue;
  105193. }
  105194. currentPool.push(otherMesh);
  105195. globalLength--;
  105196. globalPool.splice(subIndex, 1);
  105197. subIndex--;
  105198. }
  105199. if (currentPool.length < 2) {
  105200. continue;
  105201. }
  105202. // Merge meshes
  105203. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  105204. }
  105205. // Call the octree system optimization if it is defined.
  105206. var sceneAsAny = scene;
  105207. if (sceneAsAny.createOrUpdateSelectionOctree) {
  105208. if (updateSelectionTree != undefined) {
  105209. if (updateSelectionTree) {
  105210. sceneAsAny.createOrUpdateSelectionOctree();
  105211. }
  105212. }
  105213. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  105214. sceneAsAny.createOrUpdateSelectionOctree();
  105215. }
  105216. }
  105217. return true;
  105218. };
  105219. ;
  105220. MergeMeshesOptimization._UpdateSelectionTree = false;
  105221. return MergeMeshesOptimization;
  105222. }(SceneOptimization));
  105223. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  105224. /**
  105225. * Defines a list of options used by SceneOptimizer
  105226. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105227. */
  105228. var SceneOptimizerOptions = /** @class */ (function () {
  105229. /**
  105230. * Creates a new list of options used by SceneOptimizer
  105231. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  105232. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  105233. */
  105234. function SceneOptimizerOptions(
  105235. /**
  105236. * Defines the target frame rate to reach (60 by default)
  105237. */
  105238. targetFrameRate,
  105239. /**
  105240. * Defines the interval between two checkes (2000ms by default)
  105241. */
  105242. trackerDuration) {
  105243. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  105244. if (trackerDuration === void 0) { trackerDuration = 2000; }
  105245. this.targetFrameRate = targetFrameRate;
  105246. this.trackerDuration = trackerDuration;
  105247. /**
  105248. * Gets the list of optimizations to apply
  105249. */
  105250. this.optimizations = new Array();
  105251. }
  105252. /**
  105253. * Add a new optimization
  105254. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  105255. * @returns the current SceneOptimizerOptions
  105256. */
  105257. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  105258. this.optimizations.push(optimization);
  105259. return this;
  105260. };
  105261. /**
  105262. * Add a new custom optimization
  105263. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  105264. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  105265. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105266. * @returns the current SceneOptimizerOptions
  105267. */
  105268. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  105269. if (priority === void 0) { priority = 0; }
  105270. var optimization = new CustomOptimization(priority);
  105271. optimization.onApply = onApply;
  105272. optimization.onGetDescription = onGetDescription;
  105273. this.optimizations.push(optimization);
  105274. return this;
  105275. };
  105276. /**
  105277. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  105278. * @param targetFrameRate defines the target frame rate (60 by default)
  105279. * @returns a SceneOptimizerOptions object
  105280. */
  105281. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  105282. var result = new SceneOptimizerOptions(targetFrameRate);
  105283. var priority = 0;
  105284. result.addOptimization(new MergeMeshesOptimization(priority));
  105285. result.addOptimization(new ShadowsOptimization(priority));
  105286. result.addOptimization(new LensFlaresOptimization(priority));
  105287. // Next priority
  105288. priority++;
  105289. result.addOptimization(new PostProcessesOptimization(priority));
  105290. result.addOptimization(new ParticlesOptimization(priority));
  105291. // Next priority
  105292. priority++;
  105293. result.addOptimization(new TextureOptimization(priority, 1024));
  105294. return result;
  105295. };
  105296. /**
  105297. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  105298. * @param targetFrameRate defines the target frame rate (60 by default)
  105299. * @returns a SceneOptimizerOptions object
  105300. */
  105301. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  105302. var result = new SceneOptimizerOptions(targetFrameRate);
  105303. var priority = 0;
  105304. result.addOptimization(new MergeMeshesOptimization(priority));
  105305. result.addOptimization(new ShadowsOptimization(priority));
  105306. result.addOptimization(new LensFlaresOptimization(priority));
  105307. // Next priority
  105308. priority++;
  105309. result.addOptimization(new PostProcessesOptimization(priority));
  105310. result.addOptimization(new ParticlesOptimization(priority));
  105311. // Next priority
  105312. priority++;
  105313. result.addOptimization(new TextureOptimization(priority, 512));
  105314. // Next priority
  105315. priority++;
  105316. result.addOptimization(new RenderTargetsOptimization(priority));
  105317. // Next priority
  105318. priority++;
  105319. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  105320. return result;
  105321. };
  105322. /**
  105323. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  105324. * @param targetFrameRate defines the target frame rate (60 by default)
  105325. * @returns a SceneOptimizerOptions object
  105326. */
  105327. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  105328. var result = new SceneOptimizerOptions(targetFrameRate);
  105329. var priority = 0;
  105330. result.addOptimization(new MergeMeshesOptimization(priority));
  105331. result.addOptimization(new ShadowsOptimization(priority));
  105332. result.addOptimization(new LensFlaresOptimization(priority));
  105333. // Next priority
  105334. priority++;
  105335. result.addOptimization(new PostProcessesOptimization(priority));
  105336. result.addOptimization(new ParticlesOptimization(priority));
  105337. // Next priority
  105338. priority++;
  105339. result.addOptimization(new TextureOptimization(priority, 256));
  105340. // Next priority
  105341. priority++;
  105342. result.addOptimization(new RenderTargetsOptimization(priority));
  105343. // Next priority
  105344. priority++;
  105345. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  105346. return result;
  105347. };
  105348. return SceneOptimizerOptions;
  105349. }());
  105350. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  105351. /**
  105352. * Class used to run optimizations in order to reach a target frame rate
  105353. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105354. */
  105355. var SceneOptimizer = /** @class */ (function () {
  105356. /**
  105357. * Creates a new SceneOptimizer
  105358. * @param scene defines the scene to work on
  105359. * @param options defines the options to use with the SceneOptimizer
  105360. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  105361. * @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)
  105362. */
  105363. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  105364. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  105365. if (improvementMode === void 0) { improvementMode = false; }
  105366. var _this = this;
  105367. this._isRunning = false;
  105368. this._currentPriorityLevel = 0;
  105369. this._targetFrameRate = 60;
  105370. this._trackerDuration = 2000;
  105371. this._currentFrameRate = 0;
  105372. this._improvementMode = false;
  105373. /**
  105374. * Defines an observable called when the optimizer reaches the target frame rate
  105375. */
  105376. this.onSuccessObservable = new BABYLON.Observable();
  105377. /**
  105378. * Defines an observable called when the optimizer enables an optimization
  105379. */
  105380. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  105381. /**
  105382. * Defines an observable called when the optimizer is not able to reach the target frame rate
  105383. */
  105384. this.onFailureObservable = new BABYLON.Observable();
  105385. if (!options) {
  105386. this._options = new SceneOptimizerOptions();
  105387. }
  105388. else {
  105389. this._options = options;
  105390. }
  105391. if (this._options.targetFrameRate) {
  105392. this._targetFrameRate = this._options.targetFrameRate;
  105393. }
  105394. if (this._options.trackerDuration) {
  105395. this._trackerDuration = this._options.trackerDuration;
  105396. }
  105397. if (autoGeneratePriorities) {
  105398. var priority = 0;
  105399. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  105400. var optim = _a[_i];
  105401. optim.priority = priority++;
  105402. }
  105403. }
  105404. this._improvementMode = improvementMode;
  105405. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105406. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  105407. _this._sceneDisposeObserver = null;
  105408. _this.dispose();
  105409. });
  105410. }
  105411. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  105412. /**
  105413. * Gets a boolean indicating if the optimizer is in improvement mode
  105414. */
  105415. get: function () {
  105416. return this._improvementMode;
  105417. },
  105418. enumerable: true,
  105419. configurable: true
  105420. });
  105421. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  105422. /**
  105423. * Gets the current priority level (0 at start)
  105424. */
  105425. get: function () {
  105426. return this._currentPriorityLevel;
  105427. },
  105428. enumerable: true,
  105429. configurable: true
  105430. });
  105431. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  105432. /**
  105433. * Gets the current frame rate checked by the SceneOptimizer
  105434. */
  105435. get: function () {
  105436. return this._currentFrameRate;
  105437. },
  105438. enumerable: true,
  105439. configurable: true
  105440. });
  105441. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  105442. /**
  105443. * Gets or sets the current target frame rate (60 by default)
  105444. */
  105445. get: function () {
  105446. return this._targetFrameRate;
  105447. },
  105448. /**
  105449. * Gets or sets the current target frame rate (60 by default)
  105450. */
  105451. set: function (value) {
  105452. this._targetFrameRate = value;
  105453. },
  105454. enumerable: true,
  105455. configurable: true
  105456. });
  105457. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  105458. /**
  105459. * Gets or sets the current interval between two checks (every 2000ms by default)
  105460. */
  105461. get: function () {
  105462. return this._trackerDuration;
  105463. },
  105464. /**
  105465. * Gets or sets the current interval between two checks (every 2000ms by default)
  105466. */
  105467. set: function (value) {
  105468. this._trackerDuration = value;
  105469. },
  105470. enumerable: true,
  105471. configurable: true
  105472. });
  105473. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  105474. /**
  105475. * Gets the list of active optimizations
  105476. */
  105477. get: function () {
  105478. return this._options.optimizations;
  105479. },
  105480. enumerable: true,
  105481. configurable: true
  105482. });
  105483. /**
  105484. * Stops the current optimizer
  105485. */
  105486. SceneOptimizer.prototype.stop = function () {
  105487. this._isRunning = false;
  105488. };
  105489. /**
  105490. * Reset the optimizer to initial step (current priority level = 0)
  105491. */
  105492. SceneOptimizer.prototype.reset = function () {
  105493. this._currentPriorityLevel = 0;
  105494. };
  105495. /**
  105496. * Start the optimizer. By default it will try to reach a specific framerate
  105497. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  105498. */
  105499. SceneOptimizer.prototype.start = function () {
  105500. var _this = this;
  105501. if (this._isRunning) {
  105502. return;
  105503. }
  105504. this._isRunning = true;
  105505. // Let's wait for the scene to be ready before running our check
  105506. this._scene.executeWhenReady(function () {
  105507. setTimeout(function () {
  105508. _this._checkCurrentState();
  105509. }, _this._trackerDuration);
  105510. });
  105511. };
  105512. SceneOptimizer.prototype._checkCurrentState = function () {
  105513. var _this = this;
  105514. if (!this._isRunning) {
  105515. return;
  105516. }
  105517. var scene = this._scene;
  105518. var options = this._options;
  105519. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  105520. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  105521. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  105522. this._isRunning = false;
  105523. this.onSuccessObservable.notifyObservers(this);
  105524. return;
  105525. }
  105526. // Apply current level of optimizations
  105527. var allDone = true;
  105528. var noOptimizationApplied = true;
  105529. for (var index = 0; index < options.optimizations.length; index++) {
  105530. var optimization = options.optimizations[index];
  105531. if (optimization.priority === this._currentPriorityLevel) {
  105532. noOptimizationApplied = false;
  105533. allDone = allDone && optimization.apply(scene, this);
  105534. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  105535. }
  105536. }
  105537. // If no optimization was applied, this is a failure :(
  105538. if (noOptimizationApplied) {
  105539. this._isRunning = false;
  105540. this.onFailureObservable.notifyObservers(this);
  105541. return;
  105542. }
  105543. // If all optimizations were done, move to next level
  105544. if (allDone) {
  105545. this._currentPriorityLevel++;
  105546. }
  105547. // Let's the system running for a specific amount of time before checking FPS
  105548. scene.executeWhenReady(function () {
  105549. setTimeout(function () {
  105550. _this._checkCurrentState();
  105551. }, _this._trackerDuration);
  105552. });
  105553. };
  105554. /**
  105555. * Release all resources
  105556. */
  105557. SceneOptimizer.prototype.dispose = function () {
  105558. this.stop();
  105559. this.onSuccessObservable.clear();
  105560. this.onFailureObservable.clear();
  105561. this.onNewOptimizationAppliedObservable.clear();
  105562. if (this._sceneDisposeObserver) {
  105563. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  105564. }
  105565. };
  105566. /**
  105567. * Helper function to create a SceneOptimizer with one single line of code
  105568. * @param scene defines the scene to work on
  105569. * @param options defines the options to use with the SceneOptimizer
  105570. * @param onSuccess defines a callback to call on success
  105571. * @param onFailure defines a callback to call on failure
  105572. * @returns the new SceneOptimizer object
  105573. */
  105574. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  105575. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  105576. if (onSuccess) {
  105577. optimizer.onSuccessObservable.add(function () {
  105578. onSuccess();
  105579. });
  105580. }
  105581. if (onFailure) {
  105582. optimizer.onFailureObservable.add(function () {
  105583. onFailure();
  105584. });
  105585. }
  105586. optimizer.start();
  105587. return optimizer;
  105588. };
  105589. return SceneOptimizer;
  105590. }());
  105591. BABYLON.SceneOptimizer = SceneOptimizer;
  105592. })(BABYLON || (BABYLON = {}));
  105593. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  105594. var BABYLON;
  105595. (function (BABYLON) {
  105596. /**
  105597. * Gets the outline renderer associated with the scene
  105598. * @returns a OutlineRenderer
  105599. */
  105600. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  105601. if (!this._outlineRenderer) {
  105602. this._outlineRenderer = new OutlineRenderer(this);
  105603. }
  105604. return this._outlineRenderer;
  105605. };
  105606. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  105607. get: function () {
  105608. return this._renderOutline;
  105609. },
  105610. set: function (value) {
  105611. if (value) {
  105612. // Lazy Load the component.
  105613. this.getScene().getOutlineRenderer();
  105614. }
  105615. this._renderOutline = value;
  105616. },
  105617. enumerable: true,
  105618. configurable: true
  105619. });
  105620. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  105621. get: function () {
  105622. return this._renderOverlay;
  105623. },
  105624. set: function (value) {
  105625. if (value) {
  105626. // Lazy Load the component.
  105627. this.getScene().getOutlineRenderer();
  105628. }
  105629. this._renderOverlay = value;
  105630. },
  105631. enumerable: true,
  105632. configurable: true
  105633. });
  105634. /**
  105635. * This class is responsible to draw bothe outline/overlay of meshes.
  105636. * It should not be used directly but through the available method on mesh.
  105637. */
  105638. var OutlineRenderer = /** @class */ (function () {
  105639. /**
  105640. * Instantiates a new outline renderer. (There could be only one per scene).
  105641. * @param scene Defines the scene it belongs to
  105642. */
  105643. function OutlineRenderer(scene) {
  105644. /**
  105645. * The name of the component. Each component must have a unique name.
  105646. */
  105647. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  105648. /**
  105649. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  105650. */
  105651. this.zOffset = 1;
  105652. this.scene = scene;
  105653. this._engine = scene.getEngine();
  105654. this.scene._addComponent(this);
  105655. }
  105656. /**
  105657. * Register the component to one instance of a scene.
  105658. */
  105659. OutlineRenderer.prototype.register = function () {
  105660. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  105661. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  105662. };
  105663. /**
  105664. * Rebuilds the elements related to this component in case of
  105665. * context lost for instance.
  105666. */
  105667. OutlineRenderer.prototype.rebuild = function () {
  105668. // Nothing to do here.
  105669. };
  105670. /**
  105671. * Disposes the component and the associated ressources.
  105672. */
  105673. OutlineRenderer.prototype.dispose = function () {
  105674. // Nothing to do here.
  105675. };
  105676. /**
  105677. * Renders the outline in the canvas.
  105678. * @param subMesh Defines the sumesh to render
  105679. * @param batch Defines the batch of meshes in case of instances
  105680. * @param useOverlay Defines if the rendering is for the overlay or the outline
  105681. */
  105682. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  105683. var _this = this;
  105684. if (useOverlay === void 0) { useOverlay = false; }
  105685. var scene = this.scene;
  105686. var engine = scene.getEngine();
  105687. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  105688. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  105689. return;
  105690. }
  105691. var mesh = subMesh.getRenderingMesh();
  105692. var material = subMesh.getMaterial();
  105693. if (!material || !scene.activeCamera) {
  105694. return;
  105695. }
  105696. engine.enableEffect(this._effect);
  105697. // Logarithmic depth
  105698. if (material.useLogarithmicDepth) {
  105699. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  105700. }
  105701. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  105702. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  105703. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  105704. // Bones
  105705. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  105706. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  105707. }
  105708. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  105709. // Alpha test
  105710. if (material && material.needAlphaTesting()) {
  105711. var alphaTexture = material.getAlphaTestTexture();
  105712. if (alphaTexture) {
  105713. this._effect.setTexture("diffuseSampler", alphaTexture);
  105714. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  105715. }
  105716. }
  105717. engine.setZOffset(-this.zOffset);
  105718. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  105719. engine.setZOffset(0);
  105720. };
  105721. /**
  105722. * Returns whether or not the outline renderer is ready for a given submesh.
  105723. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  105724. * @param subMesh Defines the submesh to check readyness for
  105725. * @param useInstances Defines wheter wee are trying to render instances or not
  105726. * @returns true if ready otherwise false
  105727. */
  105728. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  105729. var defines = [];
  105730. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  105731. var mesh = subMesh.getMesh();
  105732. var material = subMesh.getMaterial();
  105733. if (material) {
  105734. // Alpha test
  105735. if (material.needAlphaTesting()) {
  105736. defines.push("#define ALPHATEST");
  105737. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105738. attribs.push(BABYLON.VertexBuffer.UVKind);
  105739. defines.push("#define UV1");
  105740. }
  105741. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  105742. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105743. defines.push("#define UV2");
  105744. }
  105745. }
  105746. //Logarithmic depth
  105747. if (material.useLogarithmicDepth) {
  105748. defines.push("#define LOGARITHMICDEPTH");
  105749. }
  105750. }
  105751. // Bones
  105752. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105753. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105754. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105755. if (mesh.numBoneInfluencers > 4) {
  105756. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105757. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105758. }
  105759. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105760. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  105761. }
  105762. else {
  105763. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105764. }
  105765. // Instances
  105766. if (useInstances) {
  105767. defines.push("#define INSTANCES");
  105768. attribs.push("world0");
  105769. attribs.push("world1");
  105770. attribs.push("world2");
  105771. attribs.push("world3");
  105772. }
  105773. // Get correct effect
  105774. var join = defines.join("\n");
  105775. if (this._cachedDefines !== join) {
  105776. this._cachedDefines = join;
  105777. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  105778. }
  105779. return this._effect.isReady();
  105780. };
  105781. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  105782. // Outline - step 1
  105783. this._savedDepthWrite = this._engine.getDepthWrite();
  105784. if (mesh.renderOutline) {
  105785. this._engine.setDepthWrite(false);
  105786. this.render(subMesh, batch);
  105787. this._engine.setDepthWrite(this._savedDepthWrite);
  105788. }
  105789. };
  105790. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  105791. // Outline - step 2
  105792. if (mesh.renderOutline && this._savedDepthWrite) {
  105793. this._engine.setDepthWrite(true);
  105794. this._engine.setColorWrite(false);
  105795. this.render(subMesh, batch);
  105796. this._engine.setColorWrite(true);
  105797. }
  105798. // Overlay
  105799. if (mesh.renderOverlay) {
  105800. var currentMode = this._engine.getAlphaMode();
  105801. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  105802. this.render(subMesh, batch, true);
  105803. this._engine.setAlphaMode(currentMode);
  105804. }
  105805. };
  105806. return OutlineRenderer;
  105807. }());
  105808. BABYLON.OutlineRenderer = OutlineRenderer;
  105809. })(BABYLON || (BABYLON = {}));
  105810. //# sourceMappingURL=babylon.outlineRenderer.js.map
  105811. var BABYLON;
  105812. (function (BABYLON) {
  105813. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  105814. if (this._edgesRenderer) {
  105815. this._edgesRenderer.dispose();
  105816. this._edgesRenderer = null;
  105817. }
  105818. return this;
  105819. };
  105820. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105821. if (epsilon === void 0) { epsilon = 0.95; }
  105822. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105823. this.disableEdgesRendering();
  105824. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105825. return this;
  105826. };
  105827. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  105828. get: function () {
  105829. return this._edgesRenderer;
  105830. },
  105831. enumerable: true,
  105832. configurable: true
  105833. });
  105834. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105835. if (epsilon === void 0) { epsilon = 0.95; }
  105836. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105837. this.disableEdgesRendering();
  105838. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105839. return this;
  105840. };
  105841. /**
  105842. * FaceAdjacencies Helper class to generate edges
  105843. */
  105844. var FaceAdjacencies = /** @class */ (function () {
  105845. function FaceAdjacencies() {
  105846. this.edges = new Array();
  105847. this.edgesConnectedCount = 0;
  105848. }
  105849. return FaceAdjacencies;
  105850. }());
  105851. /**
  105852. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  105853. */
  105854. var EdgesRenderer = /** @class */ (function () {
  105855. /**
  105856. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  105857. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  105858. * @param source Mesh used to create edges
  105859. * @param epsilon sum of angles in adjacency to check for edge
  105860. * @param checkVerticesInsteadOfIndices
  105861. * @param generateEdgesLines - should generate Lines or only prepare resources.
  105862. */
  105863. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  105864. if (epsilon === void 0) { epsilon = 0.95; }
  105865. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105866. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  105867. var _this = this;
  105868. /**
  105869. * Define the size of the edges with an orthographic camera
  105870. */
  105871. this.edgesWidthScalerForOrthographic = 1000.0;
  105872. /**
  105873. * Define the size of the edges with a perspective camera
  105874. */
  105875. this.edgesWidthScalerForPerspective = 50.0;
  105876. this._linesPositions = new Array();
  105877. this._linesNormals = new Array();
  105878. this._linesIndices = new Array();
  105879. this._buffers = {};
  105880. this._checkVerticesInsteadOfIndices = false;
  105881. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  105882. this.isEnabled = true;
  105883. this._source = source;
  105884. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  105885. this._epsilon = epsilon;
  105886. this._prepareRessources();
  105887. if (generateEdgesLines) {
  105888. this._generateEdgesLines();
  105889. }
  105890. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  105891. _this._rebuild();
  105892. });
  105893. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  105894. _this.dispose();
  105895. });
  105896. }
  105897. EdgesRenderer.prototype._prepareRessources = function () {
  105898. if (this._lineShader) {
  105899. return;
  105900. }
  105901. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  105902. attributes: ["position", "normal"],
  105903. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  105904. });
  105905. this._lineShader.disableDepthWrite = true;
  105906. this._lineShader.backFaceCulling = false;
  105907. };
  105908. /** @hidden */
  105909. EdgesRenderer.prototype._rebuild = function () {
  105910. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105911. if (buffer) {
  105912. buffer._rebuild();
  105913. }
  105914. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105915. if (buffer) {
  105916. buffer._rebuild();
  105917. }
  105918. var scene = this._source.getScene();
  105919. var engine = scene.getEngine();
  105920. this._ib = engine.createIndexBuffer(this._linesIndices);
  105921. };
  105922. /**
  105923. * Releases the required resources for the edges renderer
  105924. */
  105925. EdgesRenderer.prototype.dispose = function () {
  105926. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  105927. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  105928. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105929. if (buffer) {
  105930. buffer.dispose();
  105931. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  105932. }
  105933. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105934. if (buffer) {
  105935. buffer.dispose();
  105936. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  105937. }
  105938. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  105939. this._lineShader.dispose();
  105940. };
  105941. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  105942. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  105943. return 0;
  105944. }
  105945. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  105946. return 1;
  105947. }
  105948. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  105949. return 2;
  105950. }
  105951. return -1;
  105952. };
  105953. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  105954. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  105955. return 0;
  105956. }
  105957. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  105958. return 1;
  105959. }
  105960. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  105961. return 2;
  105962. }
  105963. return -1;
  105964. };
  105965. /**
  105966. * Checks if the pair of p0 and p1 is en edge
  105967. * @param faceIndex
  105968. * @param edge
  105969. * @param faceNormals
  105970. * @param p0
  105971. * @param p1
  105972. * @private
  105973. */
  105974. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  105975. var needToCreateLine;
  105976. if (edge === undefined) {
  105977. needToCreateLine = true;
  105978. }
  105979. else {
  105980. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  105981. needToCreateLine = dotProduct < this._epsilon;
  105982. }
  105983. if (needToCreateLine) {
  105984. var offset = this._linesPositions.length / 3;
  105985. var normal = p0.subtract(p1);
  105986. normal.normalize();
  105987. // Positions
  105988. this._linesPositions.push(p0.x);
  105989. this._linesPositions.push(p0.y);
  105990. this._linesPositions.push(p0.z);
  105991. this._linesPositions.push(p0.x);
  105992. this._linesPositions.push(p0.y);
  105993. this._linesPositions.push(p0.z);
  105994. this._linesPositions.push(p1.x);
  105995. this._linesPositions.push(p1.y);
  105996. this._linesPositions.push(p1.z);
  105997. this._linesPositions.push(p1.x);
  105998. this._linesPositions.push(p1.y);
  105999. this._linesPositions.push(p1.z);
  106000. // Normals
  106001. this._linesNormals.push(p1.x);
  106002. this._linesNormals.push(p1.y);
  106003. this._linesNormals.push(p1.z);
  106004. this._linesNormals.push(-1);
  106005. this._linesNormals.push(p1.x);
  106006. this._linesNormals.push(p1.y);
  106007. this._linesNormals.push(p1.z);
  106008. this._linesNormals.push(1);
  106009. this._linesNormals.push(p0.x);
  106010. this._linesNormals.push(p0.y);
  106011. this._linesNormals.push(p0.z);
  106012. this._linesNormals.push(-1);
  106013. this._linesNormals.push(p0.x);
  106014. this._linesNormals.push(p0.y);
  106015. this._linesNormals.push(p0.z);
  106016. this._linesNormals.push(1);
  106017. // Indices
  106018. this._linesIndices.push(offset);
  106019. this._linesIndices.push(offset + 1);
  106020. this._linesIndices.push(offset + 2);
  106021. this._linesIndices.push(offset);
  106022. this._linesIndices.push(offset + 2);
  106023. this._linesIndices.push(offset + 3);
  106024. }
  106025. };
  106026. /**
  106027. * Generates lines edges from adjacencjes
  106028. * @private
  106029. */
  106030. EdgesRenderer.prototype._generateEdgesLines = function () {
  106031. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106032. var indices = this._source.getIndices();
  106033. if (!indices || !positions) {
  106034. return;
  106035. }
  106036. // First let's find adjacencies
  106037. var adjacencies = new Array();
  106038. var faceNormals = new Array();
  106039. var index;
  106040. var faceAdjacencies;
  106041. // Prepare faces
  106042. for (index = 0; index < indices.length; index += 3) {
  106043. faceAdjacencies = new FaceAdjacencies();
  106044. var p0Index = indices[index];
  106045. var p1Index = indices[index + 1];
  106046. var p2Index = indices[index + 2];
  106047. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  106048. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  106049. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  106050. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  106051. faceNormal.normalize();
  106052. faceNormals.push(faceNormal);
  106053. adjacencies.push(faceAdjacencies);
  106054. }
  106055. // Scan
  106056. for (index = 0; index < adjacencies.length; index++) {
  106057. faceAdjacencies = adjacencies[index];
  106058. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  106059. var otherFaceAdjacencies = adjacencies[otherIndex];
  106060. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  106061. break;
  106062. }
  106063. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  106064. continue;
  106065. }
  106066. var otherP0 = indices[otherIndex * 3];
  106067. var otherP1 = indices[otherIndex * 3 + 1];
  106068. var otherP2 = indices[otherIndex * 3 + 2];
  106069. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  106070. var otherEdgeIndex = 0;
  106071. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  106072. continue;
  106073. }
  106074. switch (edgeIndex) {
  106075. case 0:
  106076. if (this._checkVerticesInsteadOfIndices) {
  106077. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106078. }
  106079. else {
  106080. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  106081. }
  106082. break;
  106083. case 1:
  106084. if (this._checkVerticesInsteadOfIndices) {
  106085. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106086. }
  106087. else {
  106088. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  106089. }
  106090. break;
  106091. case 2:
  106092. if (this._checkVerticesInsteadOfIndices) {
  106093. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106094. }
  106095. else {
  106096. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  106097. }
  106098. break;
  106099. }
  106100. if (otherEdgeIndex === -1) {
  106101. continue;
  106102. }
  106103. faceAdjacencies.edges[edgeIndex] = otherIndex;
  106104. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  106105. faceAdjacencies.edgesConnectedCount++;
  106106. otherFaceAdjacencies.edgesConnectedCount++;
  106107. if (faceAdjacencies.edgesConnectedCount === 3) {
  106108. break;
  106109. }
  106110. }
  106111. }
  106112. }
  106113. // Create lines
  106114. for (index = 0; index < adjacencies.length; index++) {
  106115. // 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
  106116. var current = adjacencies[index];
  106117. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  106118. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  106119. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  106120. }
  106121. // Merge into a single mesh
  106122. var engine = this._source.getScene().getEngine();
  106123. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  106124. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  106125. this._ib = engine.createIndexBuffer(this._linesIndices);
  106126. this._indicesCount = this._linesIndices.length;
  106127. };
  106128. /**
  106129. * Checks wether or not the edges renderer is ready to render.
  106130. * @return true if ready, otherwise false.
  106131. */
  106132. EdgesRenderer.prototype.isReady = function () {
  106133. return this._lineShader.isReady();
  106134. };
  106135. /**
  106136. * Renders the edges of the attached mesh,
  106137. */
  106138. EdgesRenderer.prototype.render = function () {
  106139. var scene = this._source.getScene();
  106140. if (!this.isReady() || !scene.activeCamera) {
  106141. return;
  106142. }
  106143. var engine = scene.getEngine();
  106144. this._lineShader._preBind();
  106145. if (this._source.edgesColor.a !== 1) {
  106146. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  106147. }
  106148. else {
  106149. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  106150. }
  106151. // VBOs
  106152. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  106153. scene.resetCachedMaterial();
  106154. this._lineShader.setColor4("color", this._source.edgesColor);
  106155. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  106156. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  106157. }
  106158. else {
  106159. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  106160. }
  106161. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  106162. this._lineShader.bind(this._source.getWorldMatrix());
  106163. // Draw order
  106164. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  106165. this._lineShader.unbind();
  106166. };
  106167. return EdgesRenderer;
  106168. }());
  106169. BABYLON.EdgesRenderer = EdgesRenderer;
  106170. })(BABYLON || (BABYLON = {}));
  106171. //# sourceMappingURL=babylon.edgesRenderer.js.map
  106172. var BABYLON;
  106173. (function (BABYLON) {
  106174. /**
  106175. * FaceAdjacencies Helper class to generate edges
  106176. */
  106177. var FaceAdjacencies = /** @class */ (function () {
  106178. function FaceAdjacencies() {
  106179. this.edges = new Array();
  106180. this.edgesConnectedCount = 0;
  106181. }
  106182. return FaceAdjacencies;
  106183. }());
  106184. /**
  106185. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  106186. */
  106187. var LineEdgesRenderer = /** @class */ (function (_super) {
  106188. __extends(LineEdgesRenderer, _super);
  106189. /**
  106190. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  106191. * @param source LineMesh used to generate edges
  106192. * @param epsilon not important (specified angle for edge detection)
  106193. * @param checkVerticesInsteadOfIndices not important for LineMesh
  106194. */
  106195. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  106196. if (epsilon === void 0) { epsilon = 0.95; }
  106197. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106198. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  106199. _this._generateEdgesLines();
  106200. return _this;
  106201. }
  106202. /**
  106203. * Always create the edge since its a line so only important things are p0 and p1
  106204. * @param faceIndex not important for LineMesh
  106205. * @param edge not important for LineMesh
  106206. * @param faceNormals not important for LineMesh
  106207. * @param p0 beginnig of line
  106208. * @param p1 end of line
  106209. */
  106210. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  106211. var offset = this._linesPositions.length / 3;
  106212. var normal = p0.subtract(p1);
  106213. normal.normalize();
  106214. // Positions
  106215. this._linesPositions.push(p0.x);
  106216. this._linesPositions.push(p0.y);
  106217. this._linesPositions.push(p0.z);
  106218. this._linesPositions.push(p0.x);
  106219. this._linesPositions.push(p0.y);
  106220. this._linesPositions.push(p0.z);
  106221. this._linesPositions.push(p1.x);
  106222. this._linesPositions.push(p1.y);
  106223. this._linesPositions.push(p1.z);
  106224. this._linesPositions.push(p1.x);
  106225. this._linesPositions.push(p1.y);
  106226. this._linesPositions.push(p1.z);
  106227. // Normals
  106228. this._linesNormals.push(p1.x);
  106229. this._linesNormals.push(p1.y);
  106230. this._linesNormals.push(p1.z);
  106231. this._linesNormals.push(-1);
  106232. this._linesNormals.push(p1.x);
  106233. this._linesNormals.push(p1.y);
  106234. this._linesNormals.push(p1.z);
  106235. this._linesNormals.push(1);
  106236. this._linesNormals.push(p0.x);
  106237. this._linesNormals.push(p0.y);
  106238. this._linesNormals.push(p0.z);
  106239. this._linesNormals.push(-1);
  106240. this._linesNormals.push(p0.x);
  106241. this._linesNormals.push(p0.y);
  106242. this._linesNormals.push(p0.z);
  106243. this._linesNormals.push(1);
  106244. // Indices
  106245. this._linesIndices.push(offset);
  106246. this._linesIndices.push(offset + 1);
  106247. this._linesIndices.push(offset + 2);
  106248. this._linesIndices.push(offset);
  106249. this._linesIndices.push(offset + 2);
  106250. this._linesIndices.push(offset + 3);
  106251. };
  106252. /**
  106253. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  106254. */
  106255. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  106256. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106257. var indices = this._source.getIndices();
  106258. if (!indices || !positions) {
  106259. return;
  106260. }
  106261. // First let's find adjacencies
  106262. var adjacencies = new Array();
  106263. var faceNormals = new Array();
  106264. var index;
  106265. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  106266. var currentAdjecancy = new FaceAdjacencies();
  106267. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  106268. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  106269. adjacencies.push(currentAdjecancy);
  106270. }
  106271. // Create lines
  106272. for (index = 0; index < adjacencies.length; index++) {
  106273. // 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
  106274. var current = adjacencies[index];
  106275. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  106276. }
  106277. // Merge into a single mesh
  106278. var engine = this._source.getScene().getEngine();
  106279. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  106280. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  106281. this._ib = engine.createIndexBuffer(this._linesIndices);
  106282. this._indicesCount = this._linesIndices.length;
  106283. };
  106284. return LineEdgesRenderer;
  106285. }(BABYLON.EdgesRenderer));
  106286. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  106287. })(BABYLON || (BABYLON = {}));
  106288. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  106289. var BABYLON;
  106290. (function (BABYLON) {
  106291. // Adds the parser to the scene parsers.
  106292. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  106293. if (parsedData.effectLayers) {
  106294. if (!container.effectLayers) {
  106295. container.effectLayers = new Array();
  106296. }
  106297. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  106298. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  106299. container.effectLayers.push(effectLayer);
  106300. }
  106301. }
  106302. });
  106303. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  106304. var index = this.effectLayers.indexOf(toRemove);
  106305. if (index !== -1) {
  106306. this.effectLayers.splice(index, 1);
  106307. }
  106308. return index;
  106309. };
  106310. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  106311. this.effectLayers.push(newEffectLayer);
  106312. };
  106313. /**
  106314. * Defines the layer scene component responsible to manage any effect layers
  106315. * in a given scene.
  106316. */
  106317. var EffectLayerSceneComponent = /** @class */ (function () {
  106318. /**
  106319. * Creates a new instance of the component for the given scene
  106320. * @param scene Defines the scene to register the component in
  106321. */
  106322. function EffectLayerSceneComponent(scene) {
  106323. /**
  106324. * The component name helpfull to identify the component in the list of scene components.
  106325. */
  106326. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  106327. this._renderEffects = false;
  106328. this._needStencil = false;
  106329. this._previousStencilState = false;
  106330. this.scene = scene;
  106331. this._engine = scene.getEngine();
  106332. scene.effectLayers = new Array();
  106333. }
  106334. /**
  106335. * Registers the component in a given scene
  106336. */
  106337. EffectLayerSceneComponent.prototype.register = function () {
  106338. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  106339. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  106340. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  106341. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  106342. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  106343. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  106344. };
  106345. /**
  106346. * Rebuilds the elements related to this component in case of
  106347. * context lost for instance.
  106348. */
  106349. EffectLayerSceneComponent.prototype.rebuild = function () {
  106350. var layers = this.scene.effectLayers;
  106351. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  106352. var effectLayer = layers_1[_i];
  106353. effectLayer._rebuild();
  106354. }
  106355. };
  106356. /**
  106357. * Serializes the component data to the specified json object
  106358. * @param serializationObject The object to serialize to
  106359. */
  106360. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  106361. // Effect layers
  106362. serializationObject.effectLayers = [];
  106363. var layers = this.scene.effectLayers;
  106364. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  106365. var effectLayer = layers_2[_i];
  106366. if (effectLayer.serialize) {
  106367. serializationObject.effectLayers.push(effectLayer.serialize());
  106368. }
  106369. }
  106370. };
  106371. /**
  106372. * Adds all the element from the container to the scene
  106373. * @param container the container holding the elements
  106374. */
  106375. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  106376. var _this = this;
  106377. if (!container.effectLayers) {
  106378. return;
  106379. }
  106380. container.effectLayers.forEach(function (o) {
  106381. _this.scene.addEffectLayer(o);
  106382. });
  106383. };
  106384. /**
  106385. * Removes all the elements in the container from the scene
  106386. * @param container contains the elements to remove
  106387. */
  106388. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  106389. var _this = this;
  106390. if (!container.effectLayers) {
  106391. return;
  106392. }
  106393. container.effectLayers.forEach(function (o) {
  106394. _this.scene.removeEffectLayer(o);
  106395. });
  106396. };
  106397. /**
  106398. * Disposes the component and the associated ressources.
  106399. */
  106400. EffectLayerSceneComponent.prototype.dispose = function () {
  106401. var layers = this.scene.effectLayers;
  106402. while (layers.length) {
  106403. layers[0].dispose();
  106404. }
  106405. };
  106406. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  106407. var layers = this.scene.effectLayers;
  106408. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  106409. var layer = layers_3[_i];
  106410. if (!layer.hasMesh(mesh)) {
  106411. continue;
  106412. }
  106413. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  106414. var subMesh = _b[_a];
  106415. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  106416. return false;
  106417. }
  106418. }
  106419. }
  106420. return true;
  106421. };
  106422. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  106423. this._renderEffects = false;
  106424. this._needStencil = false;
  106425. var layers = this.scene.effectLayers;
  106426. if (layers && layers.length > 0) {
  106427. this._previousStencilState = this._engine.getStencilBuffer();
  106428. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  106429. var effectLayer = layers_4[_i];
  106430. if (effectLayer.shouldRender() &&
  106431. (!effectLayer.camera ||
  106432. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  106433. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  106434. this._renderEffects = true;
  106435. this._needStencil = this._needStencil || effectLayer.needStencil();
  106436. var renderTarget = effectLayer._mainTexture;
  106437. if (renderTarget._shouldRender()) {
  106438. this.scene.incrementRenderId();
  106439. renderTarget.render(false, false);
  106440. }
  106441. }
  106442. }
  106443. this.scene.incrementRenderId();
  106444. }
  106445. };
  106446. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  106447. // Activate effect Layer stencil
  106448. if (this._needStencil) {
  106449. this._engine.setStencilBuffer(true);
  106450. }
  106451. };
  106452. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  106453. // Restore effect Layer stencil
  106454. if (this._needStencil) {
  106455. this._engine.setStencilBuffer(this._previousStencilState);
  106456. }
  106457. };
  106458. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  106459. if (this._renderEffects) {
  106460. this._engine.setDepthBuffer(false);
  106461. var layers = this.scene.effectLayers;
  106462. for (var i = 0; i < layers.length; i++) {
  106463. var effectLayer = layers[i];
  106464. if (effectLayer.renderingGroupId === renderingGroupId) {
  106465. if (effectLayer.shouldRender()) {
  106466. effectLayer.render();
  106467. }
  106468. }
  106469. }
  106470. this._engine.setDepthBuffer(true);
  106471. }
  106472. };
  106473. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  106474. if (this._renderEffects) {
  106475. this._draw(-1);
  106476. }
  106477. };
  106478. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  106479. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  106480. this._draw(index);
  106481. }
  106482. };
  106483. return EffectLayerSceneComponent;
  106484. }());
  106485. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  106486. })(BABYLON || (BABYLON = {}));
  106487. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  106488. var __assign = (this && this.__assign) || function () {
  106489. __assign = Object.assign || function(t) {
  106490. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106491. s = arguments[i];
  106492. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106493. t[p] = s[p];
  106494. }
  106495. return t;
  106496. };
  106497. return __assign.apply(this, arguments);
  106498. };
  106499. var BABYLON;
  106500. (function (BABYLON) {
  106501. /**
  106502. * The effect layer Helps adding post process effect blended with the main pass.
  106503. *
  106504. * This can be for instance use to generate glow or higlight effects on the scene.
  106505. *
  106506. * The effect layer class can not be used directly and is intented to inherited from to be
  106507. * customized per effects.
  106508. */
  106509. var EffectLayer = /** @class */ (function () {
  106510. /**
  106511. * Instantiates a new effect Layer and references it in the scene.
  106512. * @param name The name of the layer
  106513. * @param scene The scene to use the layer in
  106514. */
  106515. function EffectLayer(
  106516. /** The Friendly of the effect in the scene */
  106517. name, scene) {
  106518. this._vertexBuffers = {};
  106519. this._maxSize = 0;
  106520. this._mainTextureDesiredSize = { width: 0, height: 0 };
  106521. this._shouldRender = true;
  106522. this._postProcesses = [];
  106523. this._textures = [];
  106524. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  106525. /**
  106526. * The clear color of the texture used to generate the glow map.
  106527. */
  106528. this.neutralColor = new BABYLON.Color4();
  106529. /**
  106530. * Specifies wether the highlight layer is enabled or not.
  106531. */
  106532. this.isEnabled = true;
  106533. /**
  106534. * An event triggered when the effect layer has been disposed.
  106535. */
  106536. this.onDisposeObservable = new BABYLON.Observable();
  106537. /**
  106538. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  106539. */
  106540. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  106541. /**
  106542. * An event triggered when the generated texture is being merged in the scene.
  106543. */
  106544. this.onBeforeComposeObservable = new BABYLON.Observable();
  106545. /**
  106546. * An event triggered when the generated texture has been merged in the scene.
  106547. */
  106548. this.onAfterComposeObservable = new BABYLON.Observable();
  106549. /**
  106550. * An event triggered when the efffect layer changes its size.
  106551. */
  106552. this.onSizeChangedObservable = new BABYLON.Observable();
  106553. this.name = name;
  106554. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  106555. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  106556. if (!component) {
  106557. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  106558. this._scene._addComponent(component);
  106559. }
  106560. this._engine = this._scene.getEngine();
  106561. this._maxSize = this._engine.getCaps().maxTextureSize;
  106562. this._scene.effectLayers.push(this);
  106563. // Generate Buffers
  106564. this._generateIndexBuffer();
  106565. this._genrateVertexBuffer();
  106566. }
  106567. Object.defineProperty(EffectLayer.prototype, "camera", {
  106568. /**
  106569. * Gets the camera attached to the layer.
  106570. */
  106571. get: function () {
  106572. return this._effectLayerOptions.camera;
  106573. },
  106574. enumerable: true,
  106575. configurable: true
  106576. });
  106577. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  106578. /**
  106579. * Gets the rendering group id the layer should render in.
  106580. */
  106581. get: function () {
  106582. return this._effectLayerOptions.renderingGroupId;
  106583. },
  106584. enumerable: true,
  106585. configurable: true
  106586. });
  106587. /**
  106588. * Initializes the effect layer with the required options.
  106589. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  106590. */
  106591. EffectLayer.prototype._init = function (options) {
  106592. // Adapt options
  106593. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  106594. this._setMainTextureSize();
  106595. this._createMainTexture();
  106596. this._createTextureAndPostProcesses();
  106597. this._mergeEffect = this._createMergeEffect();
  106598. };
  106599. /**
  106600. * Generates the index buffer of the full screen quad blending to the main canvas.
  106601. */
  106602. EffectLayer.prototype._generateIndexBuffer = function () {
  106603. // Indices
  106604. var indices = [];
  106605. indices.push(0);
  106606. indices.push(1);
  106607. indices.push(2);
  106608. indices.push(0);
  106609. indices.push(2);
  106610. indices.push(3);
  106611. this._indexBuffer = this._engine.createIndexBuffer(indices);
  106612. };
  106613. /**
  106614. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  106615. */
  106616. EffectLayer.prototype._genrateVertexBuffer = function () {
  106617. // VBO
  106618. var vertices = [];
  106619. vertices.push(1, 1);
  106620. vertices.push(-1, 1);
  106621. vertices.push(-1, -1);
  106622. vertices.push(1, -1);
  106623. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  106624. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  106625. };
  106626. /**
  106627. * Sets the main texture desired size which is the closest power of two
  106628. * of the engine canvas size.
  106629. */
  106630. EffectLayer.prototype._setMainTextureSize = function () {
  106631. if (this._effectLayerOptions.mainTextureFixedSize) {
  106632. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  106633. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  106634. }
  106635. else {
  106636. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  106637. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  106638. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  106639. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  106640. }
  106641. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  106642. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  106643. };
  106644. /**
  106645. * Creates the main texture for the effect layer.
  106646. */
  106647. EffectLayer.prototype._createMainTexture = function () {
  106648. var _this = this;
  106649. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  106650. width: this._mainTextureDesiredSize.width,
  106651. height: this._mainTextureDesiredSize.height
  106652. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  106653. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  106654. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106655. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106656. this._mainTexture.anisotropicFilteringLevel = 1;
  106657. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106658. this._mainTexture.renderParticles = false;
  106659. this._mainTexture.renderList = null;
  106660. this._mainTexture.ignoreCameraViewport = true;
  106661. // Custom render function
  106662. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  106663. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  106664. var index;
  106665. var engine = _this._scene.getEngine();
  106666. if (depthOnlySubMeshes.length) {
  106667. engine.setColorWrite(false);
  106668. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  106669. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  106670. }
  106671. engine.setColorWrite(true);
  106672. }
  106673. for (index = 0; index < opaqueSubMeshes.length; index++) {
  106674. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  106675. }
  106676. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  106677. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  106678. }
  106679. for (index = 0; index < transparentSubMeshes.length; index++) {
  106680. _this._renderSubMesh(transparentSubMeshes.data[index]);
  106681. }
  106682. };
  106683. this._mainTexture.onClearObservable.add(function (engine) {
  106684. engine.clear(_this.neutralColor, true, true, true);
  106685. });
  106686. };
  106687. /**
  106688. * Checks for the readiness of the element composing the layer.
  106689. * @param subMesh the mesh to check for
  106690. * @param useInstances specify wether or not to use instances to render the mesh
  106691. * @param emissiveTexture the associated emissive texture used to generate the glow
  106692. * @return true if ready otherwise, false
  106693. */
  106694. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  106695. var material = subMesh.getMaterial();
  106696. if (!material) {
  106697. return false;
  106698. }
  106699. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  106700. return false;
  106701. }
  106702. var defines = [];
  106703. var attribs = [BABYLON.VertexBuffer.PositionKind];
  106704. var mesh = subMesh.getMesh();
  106705. var uv1 = false;
  106706. var uv2 = false;
  106707. // Alpha test
  106708. if (material && material.needAlphaTesting()) {
  106709. var alphaTexture = material.getAlphaTestTexture();
  106710. if (alphaTexture) {
  106711. defines.push("#define ALPHATEST");
  106712. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  106713. alphaTexture.coordinatesIndex === 1) {
  106714. defines.push("#define DIFFUSEUV2");
  106715. uv2 = true;
  106716. }
  106717. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106718. defines.push("#define DIFFUSEUV1");
  106719. uv1 = true;
  106720. }
  106721. }
  106722. }
  106723. // Emissive
  106724. if (emissiveTexture) {
  106725. defines.push("#define EMISSIVE");
  106726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  106727. emissiveTexture.coordinatesIndex === 1) {
  106728. defines.push("#define EMISSIVEUV2");
  106729. uv2 = true;
  106730. }
  106731. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106732. defines.push("#define EMISSIVEUV1");
  106733. uv1 = true;
  106734. }
  106735. }
  106736. if (uv1) {
  106737. attribs.push(BABYLON.VertexBuffer.UVKind);
  106738. defines.push("#define UV1");
  106739. }
  106740. if (uv2) {
  106741. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106742. defines.push("#define UV2");
  106743. }
  106744. // Bones
  106745. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  106746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  106747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  106748. if (mesh.numBoneInfluencers > 4) {
  106749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  106750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  106751. }
  106752. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  106753. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  106754. }
  106755. else {
  106756. defines.push("#define NUM_BONE_INFLUENCERS 0");
  106757. }
  106758. // Morph targets
  106759. var manager = mesh.morphTargetManager;
  106760. var morphInfluencers = 0;
  106761. if (manager) {
  106762. if (manager.numInfluencers > 0) {
  106763. defines.push("#define MORPHTARGETS");
  106764. morphInfluencers = manager.numInfluencers;
  106765. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  106766. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  106767. }
  106768. }
  106769. // Instances
  106770. if (useInstances) {
  106771. defines.push("#define INSTANCES");
  106772. attribs.push("world0");
  106773. attribs.push("world1");
  106774. attribs.push("world2");
  106775. attribs.push("world3");
  106776. }
  106777. // Get correct effect
  106778. var join = defines.join("\n");
  106779. if (this._cachedDefines !== join) {
  106780. this._cachedDefines = join;
  106781. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  106782. }
  106783. return this._effectLayerMapGenerationEffect.isReady();
  106784. };
  106785. /**
  106786. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  106787. */
  106788. EffectLayer.prototype.render = function () {
  106789. var currentEffect = this._mergeEffect;
  106790. // Check
  106791. if (!currentEffect.isReady())
  106792. return;
  106793. for (var i = 0; i < this._postProcesses.length; i++) {
  106794. if (!this._postProcesses[i].isReady()) {
  106795. return;
  106796. }
  106797. }
  106798. var engine = this._scene.getEngine();
  106799. this.onBeforeComposeObservable.notifyObservers(this);
  106800. // Render
  106801. engine.enableEffect(currentEffect);
  106802. engine.setState(false);
  106803. // VBOs
  106804. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  106805. // Cache
  106806. var previousAlphaMode = engine.getAlphaMode();
  106807. // Go Blend.
  106808. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  106809. // Blends the map on the main canvas.
  106810. this._internalRender(currentEffect);
  106811. // Restore Alpha
  106812. engine.setAlphaMode(previousAlphaMode);
  106813. this.onAfterComposeObservable.notifyObservers(this);
  106814. // Handle size changes.
  106815. var size = this._mainTexture.getSize();
  106816. this._setMainTextureSize();
  106817. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  106818. // Recreate RTT and post processes on size change.
  106819. this.onSizeChangedObservable.notifyObservers(this);
  106820. this._disposeTextureAndPostProcesses();
  106821. this._createMainTexture();
  106822. this._createTextureAndPostProcesses();
  106823. }
  106824. };
  106825. /**
  106826. * Determine if a given mesh will be used in the current effect.
  106827. * @param mesh mesh to test
  106828. * @returns true if the mesh will be used
  106829. */
  106830. EffectLayer.prototype.hasMesh = function (mesh) {
  106831. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  106832. return true;
  106833. }
  106834. return false;
  106835. };
  106836. /**
  106837. * Returns true if the layer contains information to display, otherwise false.
  106838. * @returns true if the glow layer should be rendered
  106839. */
  106840. EffectLayer.prototype.shouldRender = function () {
  106841. return this.isEnabled && this._shouldRender;
  106842. };
  106843. /**
  106844. * Returns true if the mesh should render, otherwise false.
  106845. * @param mesh The mesh to render
  106846. * @returns true if it should render otherwise false
  106847. */
  106848. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  106849. return true;
  106850. };
  106851. /**
  106852. * Returns true if the mesh should render, otherwise false.
  106853. * @param mesh The mesh to render
  106854. * @returns true if it should render otherwise false
  106855. */
  106856. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  106857. return true;
  106858. };
  106859. /**
  106860. * Renders the submesh passed in parameter to the generation map.
  106861. */
  106862. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  106863. var _this = this;
  106864. if (!this.shouldRender()) {
  106865. return;
  106866. }
  106867. var material = subMesh.getMaterial();
  106868. var mesh = subMesh.getRenderingMesh();
  106869. var scene = this._scene;
  106870. var engine = scene.getEngine();
  106871. if (!material) {
  106872. return;
  106873. }
  106874. // Do not block in blend mode.
  106875. if (material.needAlphaBlendingForMesh(mesh)) {
  106876. return;
  106877. }
  106878. // Culling
  106879. engine.setState(material.backFaceCulling);
  106880. // Managing instances
  106881. var batch = mesh._getInstancesRenderList(subMesh._id);
  106882. if (batch.mustReturn) {
  106883. return;
  106884. }
  106885. // Early Exit per mesh
  106886. if (!this._shouldRenderMesh(mesh)) {
  106887. return;
  106888. }
  106889. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106890. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  106891. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  106892. engine.enableEffect(this._effectLayerMapGenerationEffect);
  106893. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  106894. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  106895. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  106896. // Alpha test
  106897. if (material && material.needAlphaTesting()) {
  106898. var alphaTexture = material.getAlphaTestTexture();
  106899. if (alphaTexture) {
  106900. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  106901. var textureMatrix = alphaTexture.getTextureMatrix();
  106902. if (textureMatrix) {
  106903. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  106904. }
  106905. }
  106906. }
  106907. // Glow emissive only
  106908. if (this._emissiveTextureAndColor.texture) {
  106909. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  106910. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  106911. }
  106912. // Bones
  106913. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106914. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106915. }
  106916. // Morph targets
  106917. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  106918. // Draw
  106919. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  106920. }
  106921. else {
  106922. // Need to reset refresh rate of the main map
  106923. this._mainTexture.resetRefreshCounter();
  106924. }
  106925. };
  106926. /**
  106927. * Rebuild the required buffers.
  106928. * @hidden Internal use only.
  106929. */
  106930. EffectLayer.prototype._rebuild = function () {
  106931. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106932. if (vb) {
  106933. vb._rebuild();
  106934. }
  106935. this._generateIndexBuffer();
  106936. };
  106937. /**
  106938. * Dispose only the render target textures and post process.
  106939. */
  106940. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  106941. this._mainTexture.dispose();
  106942. for (var i = 0; i < this._postProcesses.length; i++) {
  106943. if (this._postProcesses[i]) {
  106944. this._postProcesses[i].dispose();
  106945. }
  106946. }
  106947. this._postProcesses = [];
  106948. for (var i = 0; i < this._textures.length; i++) {
  106949. if (this._textures[i]) {
  106950. this._textures[i].dispose();
  106951. }
  106952. }
  106953. this._textures = [];
  106954. };
  106955. /**
  106956. * Dispose the highlight layer and free resources.
  106957. */
  106958. EffectLayer.prototype.dispose = function () {
  106959. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106960. if (vertexBuffer) {
  106961. vertexBuffer.dispose();
  106962. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  106963. }
  106964. if (this._indexBuffer) {
  106965. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  106966. this._indexBuffer = null;
  106967. }
  106968. // Clean textures and post processes
  106969. this._disposeTextureAndPostProcesses();
  106970. // Remove from scene
  106971. var index = this._scene.effectLayers.indexOf(this, 0);
  106972. if (index > -1) {
  106973. this._scene.effectLayers.splice(index, 1);
  106974. }
  106975. // Callback
  106976. this.onDisposeObservable.notifyObservers(this);
  106977. this.onDisposeObservable.clear();
  106978. this.onBeforeRenderMainTextureObservable.clear();
  106979. this.onBeforeComposeObservable.clear();
  106980. this.onAfterComposeObservable.clear();
  106981. this.onSizeChangedObservable.clear();
  106982. };
  106983. /**
  106984. * Gets the class name of the effect layer
  106985. * @returns the string with the class name of the effect layer
  106986. */
  106987. EffectLayer.prototype.getClassName = function () {
  106988. return "EffectLayer";
  106989. };
  106990. /**
  106991. * Creates an effect layer from parsed effect layer data
  106992. * @param parsedEffectLayer defines effect layer data
  106993. * @param scene defines the current scene
  106994. * @param rootUrl defines the root URL containing the effect layer information
  106995. * @returns a parsed effect Layer
  106996. */
  106997. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  106998. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  106999. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  107000. };
  107001. __decorate([
  107002. BABYLON.serialize()
  107003. ], EffectLayer.prototype, "name", void 0);
  107004. __decorate([
  107005. BABYLON.serializeAsColor4()
  107006. ], EffectLayer.prototype, "neutralColor", void 0);
  107007. __decorate([
  107008. BABYLON.serialize()
  107009. ], EffectLayer.prototype, "isEnabled", void 0);
  107010. __decorate([
  107011. BABYLON.serializeAsCameraReference()
  107012. ], EffectLayer.prototype, "camera", null);
  107013. __decorate([
  107014. BABYLON.serialize()
  107015. ], EffectLayer.prototype, "renderingGroupId", null);
  107016. return EffectLayer;
  107017. }());
  107018. BABYLON.EffectLayer = EffectLayer;
  107019. })(BABYLON || (BABYLON = {}));
  107020. //# sourceMappingURL=babylon.effectLayer.js.map
  107021. var BABYLON;
  107022. (function (BABYLON) {
  107023. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  107024. for (var index = 0; index < this.effectLayers.length; index++) {
  107025. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  107026. return this.effectLayers[index];
  107027. }
  107028. }
  107029. return null;
  107030. };
  107031. /**
  107032. * Special Glow Blur post process only blurring the alpha channel
  107033. * It enforces keeping the most luminous color in the color channel.
  107034. */
  107035. var GlowBlurPostProcess = /** @class */ (function (_super) {
  107036. __extends(GlowBlurPostProcess, _super);
  107037. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  107038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  107039. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  107040. _this.direction = direction;
  107041. _this.kernel = kernel;
  107042. _this.onApplyObservable.add(function (effect) {
  107043. effect.setFloat2("screenSize", _this.width, _this.height);
  107044. effect.setVector2("direction", _this.direction);
  107045. effect.setFloat("blurWidth", _this.kernel);
  107046. });
  107047. return _this;
  107048. }
  107049. return GlowBlurPostProcess;
  107050. }(BABYLON.PostProcess));
  107051. /**
  107052. * The highlight layer Helps adding a glow effect around a mesh.
  107053. *
  107054. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107055. * glowy meshes to your scene.
  107056. *
  107057. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  107058. */
  107059. var HighlightLayer = /** @class */ (function (_super) {
  107060. __extends(HighlightLayer, _super);
  107061. /**
  107062. * Instantiates a new highlight Layer and references it to the scene..
  107063. * @param name The name of the layer
  107064. * @param scene The scene to use the layer in
  107065. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  107066. */
  107067. function HighlightLayer(name, scene, options) {
  107068. var _this = _super.call(this, name, scene) || this;
  107069. _this.name = name;
  107070. /**
  107071. * Specifies whether or not the inner glow is ACTIVE in the layer.
  107072. */
  107073. _this.innerGlow = true;
  107074. /**
  107075. * Specifies whether or not the outer glow is ACTIVE in the layer.
  107076. */
  107077. _this.outerGlow = true;
  107078. /**
  107079. * An event triggered when the highlight layer is being blurred.
  107080. */
  107081. _this.onBeforeBlurObservable = new BABYLON.Observable();
  107082. /**
  107083. * An event triggered when the highlight layer has been blurred.
  107084. */
  107085. _this.onAfterBlurObservable = new BABYLON.Observable();
  107086. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  107087. _this._meshes = {};
  107088. _this._excludedMeshes = {};
  107089. _this.neutralColor = HighlightLayer.NeutralColor;
  107090. // Warn on stencil
  107091. if (!_this._engine.isStencilEnable) {
  107092. 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 }");
  107093. }
  107094. // Adapt options
  107095. _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);
  107096. // Initialize the layer
  107097. _this._init({
  107098. alphaBlendingMode: _this._options.alphaBlendingMode,
  107099. camera: _this._options.camera,
  107100. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  107101. mainTextureRatio: _this._options.mainTextureRatio,
  107102. renderingGroupId: _this._options.renderingGroupId
  107103. });
  107104. // Do not render as long as no meshes have been added
  107105. _this._shouldRender = false;
  107106. return _this;
  107107. }
  107108. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  107109. /**
  107110. * Gets the horizontal size of the blur.
  107111. */
  107112. get: function () {
  107113. return this._horizontalBlurPostprocess.kernel;
  107114. },
  107115. /**
  107116. * Specifies the horizontal size of the blur.
  107117. */
  107118. set: function (value) {
  107119. this._horizontalBlurPostprocess.kernel = value;
  107120. },
  107121. enumerable: true,
  107122. configurable: true
  107123. });
  107124. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  107125. /**
  107126. * Gets the vertical size of the blur.
  107127. */
  107128. get: function () {
  107129. return this._verticalBlurPostprocess.kernel;
  107130. },
  107131. /**
  107132. * Specifies the vertical size of the blur.
  107133. */
  107134. set: function (value) {
  107135. this._verticalBlurPostprocess.kernel = value;
  107136. },
  107137. enumerable: true,
  107138. configurable: true
  107139. });
  107140. /**
  107141. * Get the effect name of the layer.
  107142. * @return The effect name
  107143. */
  107144. HighlightLayer.prototype.getEffectName = function () {
  107145. return HighlightLayer.EffectName;
  107146. };
  107147. /**
  107148. * Create the merge effect. This is the shader use to blit the information back
  107149. * to the main canvas at the end of the scene rendering.
  107150. */
  107151. HighlightLayer.prototype._createMergeEffect = function () {
  107152. // Effect
  107153. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  107154. };
  107155. /**
  107156. * Creates the render target textures and post processes used in the highlight layer.
  107157. */
  107158. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  107159. var _this = this;
  107160. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  107161. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  107162. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  107163. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  107164. var textureType = 0;
  107165. if (this._engine.getCaps().textureHalfFloatRender) {
  107166. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  107167. }
  107168. else {
  107169. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  107170. }
  107171. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  107172. width: blurTextureWidth,
  107173. height: blurTextureHeight
  107174. }, this._scene, false, true, textureType);
  107175. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107176. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107177. this._blurTexture.anisotropicFilteringLevel = 16;
  107178. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  107179. this._blurTexture.renderParticles = false;
  107180. this._blurTexture.ignoreCameraViewport = true;
  107181. this._textures = [this._blurTexture];
  107182. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  107183. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  107184. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  107185. effect.setTexture("textureSampler", _this._mainTexture);
  107186. });
  107187. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  107188. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  107189. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  107190. });
  107191. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  107192. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  107193. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  107194. });
  107195. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  107196. }
  107197. else {
  107198. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  107199. width: blurTextureWidth,
  107200. height: blurTextureHeight
  107201. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107202. this._horizontalBlurPostprocess.width = blurTextureWidth;
  107203. this._horizontalBlurPostprocess.height = blurTextureHeight;
  107204. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  107205. effect.setTexture("textureSampler", _this._mainTexture);
  107206. });
  107207. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  107208. width: blurTextureWidth,
  107209. height: blurTextureHeight
  107210. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107211. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  107212. }
  107213. this._mainTexture.onAfterUnbindObservable.add(function () {
  107214. _this.onBeforeBlurObservable.notifyObservers(_this);
  107215. var internalTexture = _this._blurTexture.getInternalTexture();
  107216. if (internalTexture) {
  107217. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  107218. }
  107219. _this.onAfterBlurObservable.notifyObservers(_this);
  107220. });
  107221. // Prevent autoClear.
  107222. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  107223. };
  107224. /**
  107225. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  107226. */
  107227. HighlightLayer.prototype.needStencil = function () {
  107228. return true;
  107229. };
  107230. /**
  107231. * Checks for the readiness of the element composing the layer.
  107232. * @param subMesh the mesh to check for
  107233. * @param useInstances specify wether or not to use instances to render the mesh
  107234. * @param emissiveTexture the associated emissive texture used to generate the glow
  107235. * @return true if ready otherwise, false
  107236. */
  107237. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  107238. var material = subMesh.getMaterial();
  107239. var mesh = subMesh.getRenderingMesh();
  107240. if (!material || !mesh || !this._meshes) {
  107241. return false;
  107242. }
  107243. var emissiveTexture = null;
  107244. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  107245. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  107246. emissiveTexture = material.emissiveTexture;
  107247. }
  107248. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  107249. };
  107250. /**
  107251. * Implementation specific of rendering the generating effect on the main canvas.
  107252. * @param effect The effect used to render through
  107253. */
  107254. HighlightLayer.prototype._internalRender = function (effect) {
  107255. // Texture
  107256. effect.setTexture("textureSampler", this._blurTexture);
  107257. // Cache
  107258. var engine = this._engine;
  107259. var previousStencilBuffer = engine.getStencilBuffer();
  107260. var previousStencilFunction = engine.getStencilFunction();
  107261. var previousStencilMask = engine.getStencilMask();
  107262. var previousStencilOperationPass = engine.getStencilOperationPass();
  107263. var previousStencilOperationFail = engine.getStencilOperationFail();
  107264. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  107265. var previousStencilReference = engine.getStencilFunctionReference();
  107266. // Stencil operations
  107267. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  107268. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  107269. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  107270. // Draw order
  107271. engine.setStencilMask(0x00);
  107272. engine.setStencilBuffer(true);
  107273. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  107274. // 2 passes inner outer
  107275. if (this.outerGlow) {
  107276. effect.setFloat("offset", 0);
  107277. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  107278. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107279. }
  107280. if (this.innerGlow) {
  107281. effect.setFloat("offset", 1);
  107282. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  107283. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107284. }
  107285. // Restore Cache
  107286. engine.setStencilFunction(previousStencilFunction);
  107287. engine.setStencilMask(previousStencilMask);
  107288. engine.setStencilBuffer(previousStencilBuffer);
  107289. engine.setStencilOperationPass(previousStencilOperationPass);
  107290. engine.setStencilOperationFail(previousStencilOperationFail);
  107291. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  107292. engine.setStencilFunctionReference(previousStencilReference);
  107293. };
  107294. /**
  107295. * Returns true if the layer contains information to display, otherwise false.
  107296. */
  107297. HighlightLayer.prototype.shouldRender = function () {
  107298. if (_super.prototype.shouldRender.call(this)) {
  107299. return this._meshes ? true : false;
  107300. }
  107301. return false;
  107302. };
  107303. /**
  107304. * Returns true if the mesh should render, otherwise false.
  107305. * @param mesh The mesh to render
  107306. * @returns true if it should render otherwise false
  107307. */
  107308. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  107309. // Excluded Mesh
  107310. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  107311. return false;
  107312. }
  107313. ;
  107314. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107315. return false;
  107316. }
  107317. return true;
  107318. };
  107319. /**
  107320. * Sets the required values for both the emissive texture and and the main color.
  107321. */
  107322. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  107323. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  107324. if (highlightLayerMesh) {
  107325. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  107326. }
  107327. else {
  107328. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  107329. }
  107330. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  107331. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  107332. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  107333. }
  107334. else {
  107335. this._emissiveTextureAndColor.texture = null;
  107336. }
  107337. };
  107338. /**
  107339. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  107340. * @param mesh The mesh to exclude from the highlight layer
  107341. */
  107342. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  107343. if (!this._excludedMeshes) {
  107344. return;
  107345. }
  107346. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  107347. if (!meshExcluded) {
  107348. this._excludedMeshes[mesh.uniqueId] = {
  107349. mesh: mesh,
  107350. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  107351. mesh.getEngine().setStencilBuffer(false);
  107352. }),
  107353. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  107354. mesh.getEngine().setStencilBuffer(true);
  107355. }),
  107356. };
  107357. }
  107358. };
  107359. /**
  107360. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  107361. * @param mesh The mesh to highlight
  107362. */
  107363. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  107364. if (!this._excludedMeshes) {
  107365. return;
  107366. }
  107367. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  107368. if (meshExcluded) {
  107369. if (meshExcluded.beforeRender) {
  107370. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  107371. }
  107372. if (meshExcluded.afterRender) {
  107373. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  107374. }
  107375. }
  107376. this._excludedMeshes[mesh.uniqueId] = null;
  107377. };
  107378. /**
  107379. * Determine if a given mesh will be highlighted by the current HighlightLayer
  107380. * @param mesh mesh to test
  107381. * @returns true if the mesh will be highlighted by the current HighlightLayer
  107382. */
  107383. HighlightLayer.prototype.hasMesh = function (mesh) {
  107384. if (!this._meshes) {
  107385. return false;
  107386. }
  107387. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107388. return false;
  107389. }
  107390. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  107391. };
  107392. /**
  107393. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  107394. * @param mesh The mesh to highlight
  107395. * @param color The color of the highlight
  107396. * @param glowEmissiveOnly Extract the glow from the emissive texture
  107397. */
  107398. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  107399. var _this = this;
  107400. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  107401. if (!this._meshes) {
  107402. return;
  107403. }
  107404. var meshHighlight = this._meshes[mesh.uniqueId];
  107405. if (meshHighlight) {
  107406. meshHighlight.color = color;
  107407. }
  107408. else {
  107409. this._meshes[mesh.uniqueId] = {
  107410. mesh: mesh,
  107411. color: color,
  107412. // Lambda required for capture due to Observable this context
  107413. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  107414. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  107415. _this._defaultStencilReference(mesh);
  107416. }
  107417. else {
  107418. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  107419. }
  107420. }),
  107421. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  107422. glowEmissiveOnly: glowEmissiveOnly
  107423. };
  107424. mesh.onDisposeObservable.add(function () {
  107425. _this._disposeMesh(mesh);
  107426. });
  107427. }
  107428. this._shouldRender = true;
  107429. };
  107430. /**
  107431. * Remove a mesh from the highlight layer in order to make it stop glowing.
  107432. * @param mesh The mesh to highlight
  107433. */
  107434. HighlightLayer.prototype.removeMesh = function (mesh) {
  107435. if (!this._meshes) {
  107436. return;
  107437. }
  107438. var meshHighlight = this._meshes[mesh.uniqueId];
  107439. if (meshHighlight) {
  107440. if (meshHighlight.observerHighlight) {
  107441. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  107442. }
  107443. if (meshHighlight.observerDefault) {
  107444. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  107445. }
  107446. delete this._meshes[mesh.uniqueId];
  107447. }
  107448. this._shouldRender = false;
  107449. for (var meshHighlightToCheck in this._meshes) {
  107450. if (this._meshes[meshHighlightToCheck]) {
  107451. this._shouldRender = true;
  107452. break;
  107453. }
  107454. }
  107455. };
  107456. /**
  107457. * Force the stencil to the normal expected value for none glowing parts
  107458. */
  107459. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  107460. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  107461. };
  107462. /**
  107463. * Free any resources and references associated to a mesh.
  107464. * Internal use
  107465. * @param mesh The mesh to free.
  107466. * @hidden
  107467. */
  107468. HighlightLayer.prototype._disposeMesh = function (mesh) {
  107469. this.removeMesh(mesh);
  107470. this.removeExcludedMesh(mesh);
  107471. };
  107472. /**
  107473. * Dispose the highlight layer and free resources.
  107474. */
  107475. HighlightLayer.prototype.dispose = function () {
  107476. if (this._meshes) {
  107477. // Clean mesh references
  107478. for (var id in this._meshes) {
  107479. var meshHighlight = this._meshes[id];
  107480. if (meshHighlight && meshHighlight.mesh) {
  107481. if (meshHighlight.observerHighlight) {
  107482. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  107483. }
  107484. if (meshHighlight.observerDefault) {
  107485. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  107486. }
  107487. }
  107488. }
  107489. this._meshes = null;
  107490. }
  107491. if (this._excludedMeshes) {
  107492. for (var id in this._excludedMeshes) {
  107493. var meshHighlight = this._excludedMeshes[id];
  107494. if (meshHighlight) {
  107495. if (meshHighlight.beforeRender) {
  107496. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  107497. }
  107498. if (meshHighlight.afterRender) {
  107499. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  107500. }
  107501. }
  107502. }
  107503. this._excludedMeshes = null;
  107504. }
  107505. _super.prototype.dispose.call(this);
  107506. };
  107507. /**
  107508. * Gets the class name of the effect layer
  107509. * @returns the string with the class name of the effect layer
  107510. */
  107511. HighlightLayer.prototype.getClassName = function () {
  107512. return "HighlightLayer";
  107513. };
  107514. /**
  107515. * Serializes this Highlight layer
  107516. * @returns a serialized Highlight layer object
  107517. */
  107518. HighlightLayer.prototype.serialize = function () {
  107519. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107520. serializationObject.customType = "BABYLON.HighlightLayer";
  107521. // Highlighted meshes
  107522. serializationObject.meshes = [];
  107523. if (this._meshes) {
  107524. for (var m in this._meshes) {
  107525. var mesh = this._meshes[m];
  107526. if (mesh) {
  107527. serializationObject.meshes.push({
  107528. glowEmissiveOnly: mesh.glowEmissiveOnly,
  107529. color: mesh.color.asArray(),
  107530. meshId: mesh.mesh.id
  107531. });
  107532. }
  107533. }
  107534. }
  107535. // Excluded meshes
  107536. serializationObject.excludedMeshes = [];
  107537. if (this._excludedMeshes) {
  107538. for (var e in this._excludedMeshes) {
  107539. var excludedMesh = this._excludedMeshes[e];
  107540. if (excludedMesh) {
  107541. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  107542. }
  107543. }
  107544. }
  107545. return serializationObject;
  107546. };
  107547. /**
  107548. * Creates a Highlight layer from parsed Highlight layer data
  107549. * @param parsedHightlightLayer defines the Highlight layer data
  107550. * @param scene defines the current scene
  107551. * @param rootUrl defines the root URL containing the Highlight layer information
  107552. * @returns a parsed Highlight layer
  107553. */
  107554. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  107555. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  107556. var index;
  107557. // Excluded meshes
  107558. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  107559. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  107560. if (mesh) {
  107561. hl.addExcludedMesh(mesh);
  107562. }
  107563. }
  107564. // Included meshes
  107565. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  107566. var highlightedMesh = parsedHightlightLayer.meshes[index];
  107567. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  107568. if (mesh) {
  107569. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  107570. }
  107571. }
  107572. return hl;
  107573. };
  107574. /**
  107575. * Effect Name of the highlight layer.
  107576. */
  107577. HighlightLayer.EffectName = "HighlightLayer";
  107578. /**
  107579. * The neutral color used during the preparation of the glow effect.
  107580. * This is black by default as the blend operation is a blend operation.
  107581. */
  107582. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  107583. /**
  107584. * Stencil value used for glowing meshes.
  107585. */
  107586. HighlightLayer.GlowingMeshStencilReference = 0x02;
  107587. /**
  107588. * Stencil value used for the other meshes in the scene.
  107589. */
  107590. HighlightLayer.NormalMeshStencilReference = 0x01;
  107591. __decorate([
  107592. BABYLON.serialize()
  107593. ], HighlightLayer.prototype, "innerGlow", void 0);
  107594. __decorate([
  107595. BABYLON.serialize()
  107596. ], HighlightLayer.prototype, "outerGlow", void 0);
  107597. __decorate([
  107598. BABYLON.serialize()
  107599. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  107600. __decorate([
  107601. BABYLON.serialize()
  107602. ], HighlightLayer.prototype, "blurVerticalSize", null);
  107603. __decorate([
  107604. BABYLON.serialize("options")
  107605. ], HighlightLayer.prototype, "_options", void 0);
  107606. return HighlightLayer;
  107607. }(BABYLON.EffectLayer));
  107608. BABYLON.HighlightLayer = HighlightLayer;
  107609. })(BABYLON || (BABYLON = {}));
  107610. //# sourceMappingURL=babylon.highlightLayer.js.map
  107611. var BABYLON;
  107612. (function (BABYLON) {
  107613. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  107614. for (var index = 0; index < this.effectLayers.length; index++) {
  107615. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  107616. return this.effectLayers[index];
  107617. }
  107618. }
  107619. return null;
  107620. };
  107621. /**
  107622. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  107623. *
  107624. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107625. * glowy meshes to your scene.
  107626. *
  107627. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  107628. */
  107629. var GlowLayer = /** @class */ (function (_super) {
  107630. __extends(GlowLayer, _super);
  107631. /**
  107632. * Instantiates a new glow Layer and references it to the scene.
  107633. * @param name The name of the layer
  107634. * @param scene The scene to use the layer in
  107635. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  107636. */
  107637. function GlowLayer(name, scene, options) {
  107638. var _this = _super.call(this, name, scene) || this;
  107639. _this._intensity = 1.0;
  107640. _this._includedOnlyMeshes = [];
  107641. _this._excludedMeshes = [];
  107642. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  107643. // Adapt options
  107644. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  107645. // Initialize the layer
  107646. _this._init({
  107647. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  107648. camera: _this._options.camera,
  107649. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  107650. mainTextureRatio: _this._options.mainTextureRatio,
  107651. renderingGroupId: _this._options.renderingGroupId
  107652. });
  107653. return _this;
  107654. }
  107655. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  107656. /**
  107657. * Gets the kernel size of the blur.
  107658. */
  107659. get: function () {
  107660. return this._horizontalBlurPostprocess1.kernel;
  107661. },
  107662. /**
  107663. * Sets the kernel size of the blur.
  107664. */
  107665. set: function (value) {
  107666. this._horizontalBlurPostprocess1.kernel = value;
  107667. this._verticalBlurPostprocess1.kernel = value;
  107668. this._horizontalBlurPostprocess2.kernel = value;
  107669. this._verticalBlurPostprocess2.kernel = value;
  107670. },
  107671. enumerable: true,
  107672. configurable: true
  107673. });
  107674. Object.defineProperty(GlowLayer.prototype, "intensity", {
  107675. /**
  107676. * Gets the glow intensity.
  107677. */
  107678. get: function () {
  107679. return this._intensity;
  107680. },
  107681. /**
  107682. * Sets the glow intensity.
  107683. */
  107684. set: function (value) {
  107685. this._intensity = value;
  107686. },
  107687. enumerable: true,
  107688. configurable: true
  107689. });
  107690. /**
  107691. * Get the effect name of the layer.
  107692. * @return The effect name
  107693. */
  107694. GlowLayer.prototype.getEffectName = function () {
  107695. return GlowLayer.EffectName;
  107696. };
  107697. /**
  107698. * Create the merge effect. This is the shader use to blit the information back
  107699. * to the main canvas at the end of the scene rendering.
  107700. */
  107701. GlowLayer.prototype._createMergeEffect = function () {
  107702. // Effect
  107703. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  107704. };
  107705. /**
  107706. * Creates the render target textures and post processes used in the glow layer.
  107707. */
  107708. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  107709. var _this = this;
  107710. var blurTextureWidth = this._mainTextureDesiredSize.width;
  107711. var blurTextureHeight = this._mainTextureDesiredSize.height;
  107712. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  107713. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  107714. var textureType = 0;
  107715. if (this._engine.getCaps().textureHalfFloatRender) {
  107716. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  107717. }
  107718. else {
  107719. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  107720. }
  107721. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  107722. width: blurTextureWidth,
  107723. height: blurTextureHeight
  107724. }, this._scene, false, true, textureType);
  107725. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107726. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107727. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107728. this._blurTexture1.renderParticles = false;
  107729. this._blurTexture1.ignoreCameraViewport = true;
  107730. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  107731. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  107732. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  107733. width: blurTextureWidth2,
  107734. height: blurTextureHeight2
  107735. }, this._scene, false, true, textureType);
  107736. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107737. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107738. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107739. this._blurTexture2.renderParticles = false;
  107740. this._blurTexture2.ignoreCameraViewport = true;
  107741. this._textures = [this._blurTexture1, this._blurTexture2];
  107742. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  107743. width: blurTextureWidth,
  107744. height: blurTextureHeight
  107745. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107746. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  107747. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  107748. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  107749. effect.setTexture("textureSampler", _this._mainTexture);
  107750. });
  107751. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  107752. width: blurTextureWidth,
  107753. height: blurTextureHeight
  107754. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107755. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  107756. width: blurTextureWidth2,
  107757. height: blurTextureHeight2
  107758. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107759. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  107760. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  107761. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  107762. effect.setTexture("textureSampler", _this._blurTexture1);
  107763. });
  107764. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  107765. width: blurTextureWidth2,
  107766. height: blurTextureHeight2
  107767. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107768. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  107769. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  107770. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  107771. this._mainTexture.samples = this._options.mainTextureSamples;
  107772. this._mainTexture.onAfterUnbindObservable.add(function () {
  107773. var internalTexture = _this._blurTexture1.getInternalTexture();
  107774. if (internalTexture) {
  107775. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  107776. internalTexture = _this._blurTexture2.getInternalTexture();
  107777. if (internalTexture) {
  107778. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  107779. }
  107780. }
  107781. });
  107782. // Prevent autoClear.
  107783. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  107784. };
  107785. /**
  107786. * Checks for the readiness of the element composing the layer.
  107787. * @param subMesh the mesh to check for
  107788. * @param useInstances specify wether or not to use instances to render the mesh
  107789. * @param emissiveTexture the associated emissive texture used to generate the glow
  107790. * @return true if ready otherwise, false
  107791. */
  107792. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  107793. var material = subMesh.getMaterial();
  107794. var mesh = subMesh.getRenderingMesh();
  107795. if (!material || !mesh) {
  107796. return false;
  107797. }
  107798. var emissiveTexture = material.emissiveTexture;
  107799. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  107800. };
  107801. /**
  107802. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  107803. */
  107804. GlowLayer.prototype.needStencil = function () {
  107805. return false;
  107806. };
  107807. /**
  107808. * Implementation specific of rendering the generating effect on the main canvas.
  107809. * @param effect The effect used to render through
  107810. */
  107811. GlowLayer.prototype._internalRender = function (effect) {
  107812. // Texture
  107813. effect.setTexture("textureSampler", this._blurTexture1);
  107814. effect.setTexture("textureSampler2", this._blurTexture2);
  107815. effect.setFloat("offset", this._intensity);
  107816. // Cache
  107817. var engine = this._engine;
  107818. var previousStencilBuffer = engine.getStencilBuffer();
  107819. // Draw order
  107820. engine.setStencilBuffer(false);
  107821. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107822. // Draw order
  107823. engine.setStencilBuffer(previousStencilBuffer);
  107824. };
  107825. /**
  107826. * Sets the required values for both the emissive texture and and the main color.
  107827. */
  107828. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  107829. var textureLevel = 1.0;
  107830. if (this.customEmissiveTextureSelector) {
  107831. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  107832. }
  107833. else {
  107834. if (material) {
  107835. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  107836. if (this._emissiveTextureAndColor.texture) {
  107837. textureLevel = this._emissiveTextureAndColor.texture.level;
  107838. }
  107839. }
  107840. else {
  107841. this._emissiveTextureAndColor.texture = null;
  107842. }
  107843. }
  107844. if (this.customEmissiveColorSelector) {
  107845. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  107846. }
  107847. else {
  107848. if (material.emissiveColor) {
  107849. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  107850. }
  107851. else {
  107852. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  107853. }
  107854. }
  107855. };
  107856. /**
  107857. * Returns true if the mesh should render, otherwise false.
  107858. * @param mesh The mesh to render
  107859. * @returns true if it should render otherwise false
  107860. */
  107861. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  107862. return this.hasMesh(mesh);
  107863. };
  107864. /**
  107865. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  107866. * @param mesh The mesh to exclude from the glow layer
  107867. */
  107868. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  107869. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  107870. this._excludedMeshes.push(mesh.uniqueId);
  107871. }
  107872. };
  107873. /**
  107874. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  107875. * @param mesh The mesh to remove
  107876. */
  107877. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  107878. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  107879. if (index !== -1) {
  107880. this._excludedMeshes.splice(index, 1);
  107881. }
  107882. };
  107883. /**
  107884. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  107885. * @param mesh The mesh to include in the glow layer
  107886. */
  107887. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  107888. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  107889. this._includedOnlyMeshes.push(mesh.uniqueId);
  107890. }
  107891. };
  107892. /**
  107893. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  107894. * @param mesh The mesh to remove
  107895. */
  107896. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  107897. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  107898. if (index !== -1) {
  107899. this._includedOnlyMeshes.splice(index, 1);
  107900. }
  107901. };
  107902. /**
  107903. * Determine if a given mesh will be used in the glow layer
  107904. * @param mesh The mesh to test
  107905. * @returns true if the mesh will be highlighted by the current glow layer
  107906. */
  107907. GlowLayer.prototype.hasMesh = function (mesh) {
  107908. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107909. return false;
  107910. }
  107911. // Included Mesh
  107912. if (this._includedOnlyMeshes.length) {
  107913. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  107914. }
  107915. ;
  107916. // Excluded Mesh
  107917. if (this._excludedMeshes.length) {
  107918. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  107919. }
  107920. ;
  107921. return true;
  107922. };
  107923. /**
  107924. * Free any resources and references associated to a mesh.
  107925. * Internal use
  107926. * @param mesh The mesh to free.
  107927. * @hidden
  107928. */
  107929. GlowLayer.prototype._disposeMesh = function (mesh) {
  107930. this.removeIncludedOnlyMesh(mesh);
  107931. this.removeExcludedMesh(mesh);
  107932. };
  107933. /**
  107934. * Gets the class name of the effect layer
  107935. * @returns the string with the class name of the effect layer
  107936. */
  107937. GlowLayer.prototype.getClassName = function () {
  107938. return "GlowLayer";
  107939. };
  107940. /**
  107941. * Serializes this glow layer
  107942. * @returns a serialized glow layer object
  107943. */
  107944. GlowLayer.prototype.serialize = function () {
  107945. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107946. serializationObject.customType = "BABYLON.GlowLayer";
  107947. var index;
  107948. // Included meshes
  107949. serializationObject.includedMeshes = [];
  107950. if (this._includedOnlyMeshes.length) {
  107951. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  107952. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  107953. if (mesh) {
  107954. serializationObject.includedMeshes.push(mesh.id);
  107955. }
  107956. }
  107957. }
  107958. // Excluded meshes
  107959. serializationObject.excludedMeshes = [];
  107960. if (this._excludedMeshes.length) {
  107961. for (index = 0; index < this._excludedMeshes.length; index++) {
  107962. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  107963. if (mesh) {
  107964. serializationObject.excludedMeshes.push(mesh.id);
  107965. }
  107966. }
  107967. }
  107968. return serializationObject;
  107969. };
  107970. /**
  107971. * Creates a Glow Layer from parsed glow layer data
  107972. * @param parsedGlowLayer defines glow layer data
  107973. * @param scene defines the current scene
  107974. * @param rootUrl defines the root URL containing the glow layer information
  107975. * @returns a parsed Glow Layer
  107976. */
  107977. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  107978. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  107979. var index;
  107980. // Excluded meshes
  107981. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  107982. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  107983. if (mesh) {
  107984. gl.addExcludedMesh(mesh);
  107985. }
  107986. }
  107987. // Included meshes
  107988. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  107989. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  107990. if (mesh) {
  107991. gl.addIncludedOnlyMesh(mesh);
  107992. }
  107993. }
  107994. return gl;
  107995. };
  107996. /**
  107997. * Effect Name of the layer.
  107998. */
  107999. GlowLayer.EffectName = "GlowLayer";
  108000. /**
  108001. * The default blur kernel size used for the glow.
  108002. */
  108003. GlowLayer.DefaultBlurKernelSize = 32;
  108004. /**
  108005. * The default texture size ratio used for the glow.
  108006. */
  108007. GlowLayer.DefaultTextureRatio = 0.5;
  108008. __decorate([
  108009. BABYLON.serialize()
  108010. ], GlowLayer.prototype, "blurKernelSize", null);
  108011. __decorate([
  108012. BABYLON.serialize()
  108013. ], GlowLayer.prototype, "intensity", null);
  108014. __decorate([
  108015. BABYLON.serialize("options")
  108016. ], GlowLayer.prototype, "_options", void 0);
  108017. return GlowLayer;
  108018. }(BABYLON.EffectLayer));
  108019. BABYLON.GlowLayer = GlowLayer;
  108020. })(BABYLON || (BABYLON = {}));
  108021. //# sourceMappingURL=babylon.glowLayer.js.map
  108022. var BABYLON;
  108023. (function (BABYLON) {
  108024. /**
  108025. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  108026. */
  108027. var AssetTaskState;
  108028. (function (AssetTaskState) {
  108029. /**
  108030. * Initialization
  108031. */
  108032. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  108033. /**
  108034. * Running
  108035. */
  108036. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  108037. /**
  108038. * Done
  108039. */
  108040. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  108041. /**
  108042. * Error
  108043. */
  108044. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  108045. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  108046. /**
  108047. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  108048. */
  108049. var AbstractAssetTask = /** @class */ (function () {
  108050. /**
  108051. * Creates a new {BABYLON.AssetsManager}
  108052. * @param name defines the name of the task
  108053. */
  108054. function AbstractAssetTask(
  108055. /**
  108056. * Task name
  108057. */ name) {
  108058. this.name = name;
  108059. this._isCompleted = false;
  108060. this._taskState = AssetTaskState.INIT;
  108061. }
  108062. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  108063. /**
  108064. * Get if the task is completed
  108065. */
  108066. get: function () {
  108067. return this._isCompleted;
  108068. },
  108069. enumerable: true,
  108070. configurable: true
  108071. });
  108072. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  108073. /**
  108074. * Gets the current state of the task
  108075. */
  108076. get: function () {
  108077. return this._taskState;
  108078. },
  108079. enumerable: true,
  108080. configurable: true
  108081. });
  108082. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  108083. /**
  108084. * Gets the current error object (if task is in error)
  108085. */
  108086. get: function () {
  108087. return this._errorObject;
  108088. },
  108089. enumerable: true,
  108090. configurable: true
  108091. });
  108092. /**
  108093. * Internal only
  108094. * @hidden
  108095. */
  108096. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  108097. if (this._errorObject) {
  108098. return;
  108099. }
  108100. this._errorObject = {
  108101. message: message,
  108102. exception: exception
  108103. };
  108104. };
  108105. /**
  108106. * Execute the current task
  108107. * @param scene defines the scene where you want your assets to be loaded
  108108. * @param onSuccess is a callback called when the task is successfully executed
  108109. * @param onError is a callback called if an error occurs
  108110. */
  108111. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  108112. var _this = this;
  108113. this._taskState = AssetTaskState.RUNNING;
  108114. this.runTask(scene, function () {
  108115. _this.onDoneCallback(onSuccess, onError);
  108116. }, function (msg, exception) {
  108117. _this.onErrorCallback(onError, msg, exception);
  108118. });
  108119. };
  108120. /**
  108121. * Execute the current task
  108122. * @param scene defines the scene where you want your assets to be loaded
  108123. * @param onSuccess is a callback called when the task is successfully executed
  108124. * @param onError is a callback called if an error occurs
  108125. */
  108126. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108127. throw new Error("runTask is not implemented");
  108128. };
  108129. /**
  108130. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  108131. * This can be used with failed tasks that have the reason for failure fixed.
  108132. */
  108133. AbstractAssetTask.prototype.reset = function () {
  108134. this._taskState = AssetTaskState.INIT;
  108135. };
  108136. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  108137. this._taskState = AssetTaskState.ERROR;
  108138. this._errorObject = {
  108139. message: message,
  108140. exception: exception
  108141. };
  108142. if (this.onError) {
  108143. this.onError(this, message, exception);
  108144. }
  108145. onError();
  108146. };
  108147. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  108148. try {
  108149. this._taskState = AssetTaskState.DONE;
  108150. this._isCompleted = true;
  108151. if (this.onSuccess) {
  108152. this.onSuccess(this);
  108153. }
  108154. onSuccess();
  108155. }
  108156. catch (e) {
  108157. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  108158. }
  108159. };
  108160. return AbstractAssetTask;
  108161. }());
  108162. BABYLON.AbstractAssetTask = AbstractAssetTask;
  108163. /**
  108164. * Class used to share progress information about assets loading
  108165. */
  108166. var AssetsProgressEvent = /** @class */ (function () {
  108167. /**
  108168. * Creates a {BABYLON.AssetsProgressEvent}
  108169. * @param remainingCount defines the number of remaining tasks to process
  108170. * @param totalCount defines the total number of tasks
  108171. * @param task defines the task that was just processed
  108172. */
  108173. function AssetsProgressEvent(remainingCount, totalCount, task) {
  108174. this.remainingCount = remainingCount;
  108175. this.totalCount = totalCount;
  108176. this.task = task;
  108177. }
  108178. return AssetsProgressEvent;
  108179. }());
  108180. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  108181. /**
  108182. * Define a task used by {BABYLON.AssetsManager} to load meshes
  108183. */
  108184. var MeshAssetTask = /** @class */ (function (_super) {
  108185. __extends(MeshAssetTask, _super);
  108186. /**
  108187. * Creates a new {BABYLON.MeshAssetTask}
  108188. * @param name defines the name of the task
  108189. * @param meshesNames defines the list of mesh's names you want to load
  108190. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  108191. * @param sceneFilename defines the filename of the scene to load from
  108192. */
  108193. function MeshAssetTask(
  108194. /**
  108195. * Defines the name of the task
  108196. */
  108197. name,
  108198. /**
  108199. * Defines the list of mesh's names you want to load
  108200. */
  108201. meshesNames,
  108202. /**
  108203. * Defines the root url to use as a base to load your meshes and associated resources
  108204. */
  108205. rootUrl,
  108206. /**
  108207. * Defines the filename of the scene to load from
  108208. */
  108209. sceneFilename) {
  108210. var _this = _super.call(this, name) || this;
  108211. _this.name = name;
  108212. _this.meshesNames = meshesNames;
  108213. _this.rootUrl = rootUrl;
  108214. _this.sceneFilename = sceneFilename;
  108215. return _this;
  108216. }
  108217. /**
  108218. * Execute the current task
  108219. * @param scene defines the scene where you want your assets to be loaded
  108220. * @param onSuccess is a callback called when the task is successfully executed
  108221. * @param onError is a callback called if an error occurs
  108222. */
  108223. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108224. var _this = this;
  108225. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  108226. _this.loadedMeshes = meshes;
  108227. _this.loadedParticleSystems = particleSystems;
  108228. _this.loadedSkeletons = skeletons;
  108229. onSuccess();
  108230. }, null, function (scene, message, exception) {
  108231. onError(message, exception);
  108232. });
  108233. };
  108234. return MeshAssetTask;
  108235. }(AbstractAssetTask));
  108236. BABYLON.MeshAssetTask = MeshAssetTask;
  108237. /**
  108238. * Define a task used by {BABYLON.AssetsManager} to load text content
  108239. */
  108240. var TextFileAssetTask = /** @class */ (function (_super) {
  108241. __extends(TextFileAssetTask, _super);
  108242. /**
  108243. * Creates a new TextFileAssetTask object
  108244. * @param name defines the name of the task
  108245. * @param url defines the location of the file to load
  108246. */
  108247. function TextFileAssetTask(
  108248. /**
  108249. * Defines the name of the task
  108250. */
  108251. name,
  108252. /**
  108253. * Defines the location of the file to load
  108254. */
  108255. url) {
  108256. var _this = _super.call(this, name) || this;
  108257. _this.name = name;
  108258. _this.url = url;
  108259. return _this;
  108260. }
  108261. /**
  108262. * Execute the current task
  108263. * @param scene defines the scene where you want your assets to be loaded
  108264. * @param onSuccess is a callback called when the task is successfully executed
  108265. * @param onError is a callback called if an error occurs
  108266. */
  108267. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108268. var _this = this;
  108269. scene._loadFile(this.url, function (data) {
  108270. _this.text = data;
  108271. onSuccess();
  108272. }, undefined, false, false, function (request, exception) {
  108273. if (request) {
  108274. onError(request.status + " " + request.statusText, exception);
  108275. }
  108276. });
  108277. };
  108278. return TextFileAssetTask;
  108279. }(AbstractAssetTask));
  108280. BABYLON.TextFileAssetTask = TextFileAssetTask;
  108281. /**
  108282. * Define a task used by {BABYLON.AssetsManager} to load binary data
  108283. */
  108284. var BinaryFileAssetTask = /** @class */ (function (_super) {
  108285. __extends(BinaryFileAssetTask, _super);
  108286. /**
  108287. * Creates a new BinaryFileAssetTask object
  108288. * @param name defines the name of the new task
  108289. * @param url defines the location of the file to load
  108290. */
  108291. function BinaryFileAssetTask(
  108292. /**
  108293. * Defines the name of the task
  108294. */
  108295. name,
  108296. /**
  108297. * Defines the location of the file to load
  108298. */
  108299. url) {
  108300. var _this = _super.call(this, name) || this;
  108301. _this.name = name;
  108302. _this.url = url;
  108303. return _this;
  108304. }
  108305. /**
  108306. * Execute the current task
  108307. * @param scene defines the scene where you want your assets to be loaded
  108308. * @param onSuccess is a callback called when the task is successfully executed
  108309. * @param onError is a callback called if an error occurs
  108310. */
  108311. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108312. var _this = this;
  108313. scene._loadFile(this.url, function (data) {
  108314. _this.data = data;
  108315. onSuccess();
  108316. }, undefined, true, true, function (request, exception) {
  108317. if (request) {
  108318. onError(request.status + " " + request.statusText, exception);
  108319. }
  108320. });
  108321. };
  108322. return BinaryFileAssetTask;
  108323. }(AbstractAssetTask));
  108324. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  108325. /**
  108326. * Define a task used by {BABYLON.AssetsManager} to load images
  108327. */
  108328. var ImageAssetTask = /** @class */ (function (_super) {
  108329. __extends(ImageAssetTask, _super);
  108330. /**
  108331. * Creates a new ImageAssetTask
  108332. * @param name defines the name of the task
  108333. * @param url defines the location of the image to load
  108334. */
  108335. function ImageAssetTask(
  108336. /**
  108337. * Defines the name of the task
  108338. */
  108339. name,
  108340. /**
  108341. * Defines the location of the image to load
  108342. */
  108343. url) {
  108344. var _this = _super.call(this, name) || this;
  108345. _this.name = name;
  108346. _this.url = url;
  108347. return _this;
  108348. }
  108349. /**
  108350. * Execute the current task
  108351. * @param scene defines the scene where you want your assets to be loaded
  108352. * @param onSuccess is a callback called when the task is successfully executed
  108353. * @param onError is a callback called if an error occurs
  108354. */
  108355. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108356. var _this = this;
  108357. var img = new Image();
  108358. BABYLON.Tools.SetCorsBehavior(this.url, img);
  108359. img.onload = function () {
  108360. _this.image = img;
  108361. onSuccess();
  108362. };
  108363. img.onerror = function (err) {
  108364. onError("Error loading image", err);
  108365. };
  108366. img.src = this.url;
  108367. };
  108368. return ImageAssetTask;
  108369. }(AbstractAssetTask));
  108370. BABYLON.ImageAssetTask = ImageAssetTask;
  108371. /**
  108372. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  108373. */
  108374. var TextureAssetTask = /** @class */ (function (_super) {
  108375. __extends(TextureAssetTask, _super);
  108376. /**
  108377. * Creates a new TextureAssetTask object
  108378. * @param name defines the name of the task
  108379. * @param url defines the location of the file to load
  108380. * @param noMipmap defines if mipmap should not be generated (default is false)
  108381. * @param invertY defines if texture must be inverted on Y axis (default is false)
  108382. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  108383. */
  108384. function TextureAssetTask(
  108385. /**
  108386. * Defines the name of the task
  108387. */
  108388. name,
  108389. /**
  108390. * Defines the location of the file to load
  108391. */
  108392. url,
  108393. /**
  108394. * Defines if mipmap should not be generated (default is false)
  108395. */
  108396. noMipmap,
  108397. /**
  108398. * Defines if texture must be inverted on Y axis (default is false)
  108399. */
  108400. invertY,
  108401. /**
  108402. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  108403. */
  108404. samplingMode) {
  108405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108406. var _this = _super.call(this, name) || this;
  108407. _this.name = name;
  108408. _this.url = url;
  108409. _this.noMipmap = noMipmap;
  108410. _this.invertY = invertY;
  108411. _this.samplingMode = samplingMode;
  108412. return _this;
  108413. }
  108414. /**
  108415. * Execute the current task
  108416. * @param scene defines the scene where you want your assets to be loaded
  108417. * @param onSuccess is a callback called when the task is successfully executed
  108418. * @param onError is a callback called if an error occurs
  108419. */
  108420. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108421. var onload = function () {
  108422. onSuccess();
  108423. };
  108424. var onerror = function (message, exception) {
  108425. onError(message, exception);
  108426. };
  108427. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  108428. };
  108429. return TextureAssetTask;
  108430. }(AbstractAssetTask));
  108431. BABYLON.TextureAssetTask = TextureAssetTask;
  108432. /**
  108433. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  108434. */
  108435. var CubeTextureAssetTask = /** @class */ (function (_super) {
  108436. __extends(CubeTextureAssetTask, _super);
  108437. /**
  108438. * Creates a new CubeTextureAssetTask
  108439. * @param name defines the name of the task
  108440. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  108441. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  108442. * @param noMipmap defines if mipmaps should not be generated (default is false)
  108443. * @param files defines the explicit list of files (undefined by default)
  108444. */
  108445. function CubeTextureAssetTask(
  108446. /**
  108447. * Defines the name of the task
  108448. */
  108449. name,
  108450. /**
  108451. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  108452. */
  108453. url,
  108454. /**
  108455. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  108456. */
  108457. extensions,
  108458. /**
  108459. * Defines if mipmaps should not be generated (default is false)
  108460. */
  108461. noMipmap,
  108462. /**
  108463. * Defines the explicit list of files (undefined by default)
  108464. */
  108465. files) {
  108466. var _this = _super.call(this, name) || this;
  108467. _this.name = name;
  108468. _this.url = url;
  108469. _this.extensions = extensions;
  108470. _this.noMipmap = noMipmap;
  108471. _this.files = files;
  108472. return _this;
  108473. }
  108474. /**
  108475. * Execute the current task
  108476. * @param scene defines the scene where you want your assets to be loaded
  108477. * @param onSuccess is a callback called when the task is successfully executed
  108478. * @param onError is a callback called if an error occurs
  108479. */
  108480. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108481. var onload = function () {
  108482. onSuccess();
  108483. };
  108484. var onerror = function (message, exception) {
  108485. onError(message, exception);
  108486. };
  108487. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  108488. };
  108489. return CubeTextureAssetTask;
  108490. }(AbstractAssetTask));
  108491. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  108492. /**
  108493. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  108494. */
  108495. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  108496. __extends(HDRCubeTextureAssetTask, _super);
  108497. /**
  108498. * Creates a new HDRCubeTextureAssetTask object
  108499. * @param name defines the name of the task
  108500. * @param url defines the location of the file to load
  108501. * @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.
  108502. * @param noMipmap defines if mipmaps should not be generated (default is false)
  108503. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  108504. * @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)
  108505. * @param reserved Internal use only
  108506. */
  108507. function HDRCubeTextureAssetTask(
  108508. /**
  108509. * Defines the name of the task
  108510. */
  108511. name,
  108512. /**
  108513. * Defines the location of the file to load
  108514. */
  108515. url,
  108516. /**
  108517. * Defines the desired size (the more it increases the longer the generation will be)
  108518. */
  108519. size,
  108520. /**
  108521. * Defines if mipmaps should not be generated (default is false)
  108522. */
  108523. noMipmap,
  108524. /**
  108525. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  108526. */
  108527. generateHarmonics,
  108528. /**
  108529. * 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)
  108530. */
  108531. gammaSpace,
  108532. /**
  108533. * Internal Use Only
  108534. */
  108535. reserved) {
  108536. if (noMipmap === void 0) { noMipmap = false; }
  108537. if (generateHarmonics === void 0) { generateHarmonics = true; }
  108538. if (gammaSpace === void 0) { gammaSpace = false; }
  108539. if (reserved === void 0) { reserved = false; }
  108540. var _this = _super.call(this, name) || this;
  108541. _this.name = name;
  108542. _this.url = url;
  108543. _this.size = size;
  108544. _this.noMipmap = noMipmap;
  108545. _this.generateHarmonics = generateHarmonics;
  108546. _this.gammaSpace = gammaSpace;
  108547. _this.reserved = reserved;
  108548. return _this;
  108549. }
  108550. /**
  108551. * Execute the current task
  108552. * @param scene defines the scene where you want your assets to be loaded
  108553. * @param onSuccess is a callback called when the task is successfully executed
  108554. * @param onError is a callback called if an error occurs
  108555. */
  108556. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  108557. var onload = function () {
  108558. onSuccess();
  108559. };
  108560. var onerror = function (message, exception) {
  108561. onError(message, exception);
  108562. };
  108563. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  108564. };
  108565. return HDRCubeTextureAssetTask;
  108566. }(AbstractAssetTask));
  108567. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  108568. /**
  108569. * This class can be used to easily import assets into a scene
  108570. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  108571. */
  108572. var AssetsManager = /** @class */ (function () {
  108573. /**
  108574. * Creates a new AssetsManager
  108575. * @param scene defines the scene to work on
  108576. */
  108577. function AssetsManager(scene) {
  108578. this._isLoading = false;
  108579. this._tasks = new Array();
  108580. this._waitingTasksCount = 0;
  108581. this._totalTasksCount = 0;
  108582. /**
  108583. * Observable called when all tasks are processed
  108584. */
  108585. this.onTaskSuccessObservable = new BABYLON.Observable();
  108586. /**
  108587. * Observable called when a task had an error
  108588. */
  108589. this.onTaskErrorObservable = new BABYLON.Observable();
  108590. /**
  108591. * Observable called when a task is successful
  108592. */
  108593. this.onTasksDoneObservable = new BABYLON.Observable();
  108594. /**
  108595. * Observable called when a task is done (whatever the result is)
  108596. */
  108597. this.onProgressObservable = new BABYLON.Observable();
  108598. /**
  108599. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  108600. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  108601. */
  108602. this.useDefaultLoadingScreen = true;
  108603. this._scene = scene;
  108604. }
  108605. /**
  108606. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  108607. * @param taskName defines the name of the new task
  108608. * @param meshesNames defines the name of meshes to load
  108609. * @param rootUrl defines the root url to use to locate files
  108610. * @param sceneFilename defines the filename of the scene file
  108611. * @returns a new {BABYLON.MeshAssetTask} object
  108612. */
  108613. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  108614. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  108615. this._tasks.push(task);
  108616. return task;
  108617. };
  108618. /**
  108619. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  108620. * @param taskName defines the name of the new task
  108621. * @param url defines the url of the file to load
  108622. * @returns a new {BABYLON.TextFileAssetTask} object
  108623. */
  108624. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  108625. var task = new TextFileAssetTask(taskName, url);
  108626. this._tasks.push(task);
  108627. return task;
  108628. };
  108629. /**
  108630. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  108631. * @param taskName defines the name of the new task
  108632. * @param url defines the url of the file to load
  108633. * @returns a new {BABYLON.BinaryFileAssetTask} object
  108634. */
  108635. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  108636. var task = new BinaryFileAssetTask(taskName, url);
  108637. this._tasks.push(task);
  108638. return task;
  108639. };
  108640. /**
  108641. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  108642. * @param taskName defines the name of the new task
  108643. * @param url defines the url of the file to load
  108644. * @returns a new {BABYLON.ImageAssetTask} object
  108645. */
  108646. AssetsManager.prototype.addImageTask = function (taskName, url) {
  108647. var task = new ImageAssetTask(taskName, url);
  108648. this._tasks.push(task);
  108649. return task;
  108650. };
  108651. /**
  108652. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  108653. * @param taskName defines the name of the new task
  108654. * @param url defines the url of the file to load
  108655. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  108656. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  108657. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  108658. * @returns a new {BABYLON.TextureAssetTask} object
  108659. */
  108660. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  108661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108662. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  108663. this._tasks.push(task);
  108664. return task;
  108665. };
  108666. /**
  108667. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  108668. * @param taskName defines the name of the new task
  108669. * @param url defines the url of the file to load
  108670. * @param extensions defines the extension to use to load the cube map (can be null)
  108671. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  108672. * @param files defines the list of files to load (can be null)
  108673. * @returns a new {BABYLON.CubeTextureAssetTask} object
  108674. */
  108675. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  108676. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  108677. this._tasks.push(task);
  108678. return task;
  108679. };
  108680. /**
  108681. *
  108682. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  108683. * @param taskName defines the name of the new task
  108684. * @param url defines the url of the file to load
  108685. * @param size defines the size you want for the cubemap (can be null)
  108686. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  108687. * @param generateHarmonics defines if you want to automatically generate (true by default)
  108688. * @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)
  108689. * @param reserved Internal use only
  108690. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  108691. */
  108692. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  108693. if (noMipmap === void 0) { noMipmap = false; }
  108694. if (generateHarmonics === void 0) { generateHarmonics = true; }
  108695. if (gammaSpace === void 0) { gammaSpace = false; }
  108696. if (reserved === void 0) { reserved = false; }
  108697. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  108698. this._tasks.push(task);
  108699. return task;
  108700. };
  108701. /**
  108702. * Remove a task from the assets manager.
  108703. * @param task the task to remove
  108704. */
  108705. AssetsManager.prototype.removeTask = function (task) {
  108706. var index = this._tasks.indexOf(task);
  108707. if (index > -1) {
  108708. this._tasks.splice(index, 1);
  108709. }
  108710. };
  108711. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  108712. this._waitingTasksCount--;
  108713. try {
  108714. if (this.onProgress) {
  108715. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  108716. }
  108717. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  108718. }
  108719. catch (e) {
  108720. BABYLON.Tools.Error("Error running progress callbacks.");
  108721. console.log(e);
  108722. }
  108723. if (this._waitingTasksCount === 0) {
  108724. try {
  108725. if (this.onFinish) {
  108726. this.onFinish(this._tasks);
  108727. }
  108728. // Let's remove successfull tasks
  108729. var currentTasks = this._tasks.slice();
  108730. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  108731. var task = currentTasks_1[_i];
  108732. if (task.taskState === AssetTaskState.DONE) {
  108733. var index = this._tasks.indexOf(task);
  108734. if (index > -1) {
  108735. this._tasks.splice(index, 1);
  108736. }
  108737. }
  108738. }
  108739. this.onTasksDoneObservable.notifyObservers(this._tasks);
  108740. }
  108741. catch (e) {
  108742. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  108743. console.log(e);
  108744. }
  108745. this._isLoading = false;
  108746. this._scene.getEngine().hideLoadingUI();
  108747. }
  108748. };
  108749. AssetsManager.prototype._runTask = function (task) {
  108750. var _this = this;
  108751. var done = function () {
  108752. try {
  108753. if (_this.onTaskSuccess) {
  108754. _this.onTaskSuccess(task);
  108755. }
  108756. _this.onTaskSuccessObservable.notifyObservers(task);
  108757. _this._decreaseWaitingTasksCount(task);
  108758. }
  108759. catch (e) {
  108760. error("Error executing task success callbacks", e);
  108761. }
  108762. };
  108763. var error = function (message, exception) {
  108764. task._setErrorObject(message, exception);
  108765. if (_this.onTaskError) {
  108766. _this.onTaskError(task);
  108767. }
  108768. _this.onTaskErrorObservable.notifyObservers(task);
  108769. _this._decreaseWaitingTasksCount(task);
  108770. };
  108771. task.run(this._scene, done, error);
  108772. };
  108773. /**
  108774. * Reset the {BABYLON.AssetsManager} and remove all tasks
  108775. * @return the current instance of the {BABYLON.AssetsManager}
  108776. */
  108777. AssetsManager.prototype.reset = function () {
  108778. this._isLoading = false;
  108779. this._tasks = new Array();
  108780. return this;
  108781. };
  108782. /**
  108783. * Start the loading process
  108784. * @return the current instance of the {BABYLON.AssetsManager}
  108785. */
  108786. AssetsManager.prototype.load = function () {
  108787. if (this._isLoading) {
  108788. return this;
  108789. }
  108790. this._isLoading = true;
  108791. this._waitingTasksCount = this._tasks.length;
  108792. this._totalTasksCount = this._tasks.length;
  108793. if (this._waitingTasksCount === 0) {
  108794. this._isLoading = false;
  108795. if (this.onFinish) {
  108796. this.onFinish(this._tasks);
  108797. }
  108798. this.onTasksDoneObservable.notifyObservers(this._tasks);
  108799. return this;
  108800. }
  108801. if (this.useDefaultLoadingScreen) {
  108802. this._scene.getEngine().displayLoadingUI();
  108803. }
  108804. for (var index = 0; index < this._tasks.length; index++) {
  108805. var task = this._tasks[index];
  108806. if (task.taskState === AssetTaskState.INIT) {
  108807. this._runTask(task);
  108808. }
  108809. }
  108810. return this;
  108811. };
  108812. return AssetsManager;
  108813. }());
  108814. BABYLON.AssetsManager = AssetsManager;
  108815. })(BABYLON || (BABYLON = {}));
  108816. //# sourceMappingURL=babylon.assetsManager.js.map
  108817. var BABYLON;
  108818. (function (BABYLON) {
  108819. var serializedGeometries = [];
  108820. var serializeGeometry = function (geometry, serializationGeometries) {
  108821. if (serializedGeometries[geometry.id]) {
  108822. return;
  108823. }
  108824. if (geometry.doNotSerialize) {
  108825. return;
  108826. }
  108827. if (geometry instanceof BABYLON.BoxGeometry) {
  108828. serializationGeometries.boxes.push(geometry.serialize());
  108829. }
  108830. else if (geometry instanceof BABYLON.SphereGeometry) {
  108831. serializationGeometries.spheres.push(geometry.serialize());
  108832. }
  108833. else if (geometry instanceof BABYLON.CylinderGeometry) {
  108834. serializationGeometries.cylinders.push(geometry.serialize());
  108835. }
  108836. else if (geometry instanceof BABYLON.TorusGeometry) {
  108837. serializationGeometries.toruses.push(geometry.serialize());
  108838. }
  108839. else if (geometry instanceof BABYLON.GroundGeometry) {
  108840. serializationGeometries.grounds.push(geometry.serialize());
  108841. }
  108842. else if (geometry instanceof BABYLON.Plane) {
  108843. serializationGeometries.planes.push(geometry.serialize());
  108844. }
  108845. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  108846. serializationGeometries.torusKnots.push(geometry.serialize());
  108847. }
  108848. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  108849. throw new Error("Unknown primitive type");
  108850. }
  108851. else {
  108852. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  108853. }
  108854. serializedGeometries[geometry.id] = true;
  108855. };
  108856. var serializeMesh = function (mesh, serializationScene) {
  108857. var serializationObject = {};
  108858. // Geometry
  108859. var geometry = mesh._geometry;
  108860. if (geometry) {
  108861. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  108862. // 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
  108863. serializeGeometry(geometry, serializationScene.geometries);
  108864. }
  108865. }
  108866. // Custom
  108867. if (mesh.serialize) {
  108868. mesh.serialize(serializationObject);
  108869. }
  108870. return serializationObject;
  108871. };
  108872. var finalizeSingleMesh = function (mesh, serializationObject) {
  108873. //only works if the mesh is already loaded
  108874. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  108875. //serialize material
  108876. if (mesh.material) {
  108877. if (mesh.material instanceof BABYLON.MultiMaterial) {
  108878. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  108879. serializationObject.materials = serializationObject.materials || [];
  108880. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108881. serializationObject.multiMaterials.push(mesh.material.serialize());
  108882. var _loop_1 = function (submaterial) {
  108883. if (submaterial) {
  108884. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  108885. serializationObject.materials.push(submaterial.serialize());
  108886. }
  108887. }
  108888. };
  108889. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  108890. var submaterial = _a[_i];
  108891. _loop_1(submaterial);
  108892. }
  108893. }
  108894. }
  108895. else {
  108896. serializationObject.materials = serializationObject.materials || [];
  108897. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108898. serializationObject.materials.push(mesh.material.serialize());
  108899. }
  108900. }
  108901. }
  108902. //serialize geometry
  108903. var geometry = mesh._geometry;
  108904. if (geometry) {
  108905. if (!serializationObject.geometries) {
  108906. serializationObject.geometries = {};
  108907. serializationObject.geometries.boxes = [];
  108908. serializationObject.geometries.spheres = [];
  108909. serializationObject.geometries.cylinders = [];
  108910. serializationObject.geometries.toruses = [];
  108911. serializationObject.geometries.grounds = [];
  108912. serializationObject.geometries.planes = [];
  108913. serializationObject.geometries.torusKnots = [];
  108914. serializationObject.geometries.vertexData = [];
  108915. }
  108916. serializeGeometry(geometry, serializationObject.geometries);
  108917. }
  108918. // Skeletons
  108919. if (mesh.skeleton) {
  108920. serializationObject.skeletons = serializationObject.skeletons || [];
  108921. serializationObject.skeletons.push(mesh.skeleton.serialize());
  108922. }
  108923. //serialize the actual mesh
  108924. serializationObject.meshes = serializationObject.meshes || [];
  108925. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  108926. }
  108927. };
  108928. /**
  108929. * Class used to serialize a scene into a string
  108930. */
  108931. var SceneSerializer = /** @class */ (function () {
  108932. function SceneSerializer() {
  108933. }
  108934. /**
  108935. * Clear cache used by a previous serialization
  108936. */
  108937. SceneSerializer.ClearCache = function () {
  108938. serializedGeometries = [];
  108939. };
  108940. /**
  108941. * Serialize a scene into a JSON compatible object
  108942. * @param scene defines the scene to serialize
  108943. * @returns a JSON compatible object
  108944. */
  108945. SceneSerializer.Serialize = function (scene) {
  108946. var serializationObject = {};
  108947. SceneSerializer.ClearCache();
  108948. // Scene
  108949. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  108950. serializationObject.autoClear = scene.autoClear;
  108951. serializationObject.clearColor = scene.clearColor.asArray();
  108952. serializationObject.ambientColor = scene.ambientColor.asArray();
  108953. serializationObject.gravity = scene.gravity.asArray();
  108954. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  108955. serializationObject.workerCollisions = scene.workerCollisions;
  108956. // Fog
  108957. if (scene.fogMode && scene.fogMode !== 0) {
  108958. serializationObject.fogMode = scene.fogMode;
  108959. serializationObject.fogColor = scene.fogColor.asArray();
  108960. serializationObject.fogStart = scene.fogStart;
  108961. serializationObject.fogEnd = scene.fogEnd;
  108962. serializationObject.fogDensity = scene.fogDensity;
  108963. }
  108964. //Physics
  108965. if (scene.isPhysicsEnabled()) {
  108966. var physicEngine = scene.getPhysicsEngine();
  108967. if (physicEngine) {
  108968. serializationObject.physicsEnabled = true;
  108969. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  108970. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  108971. }
  108972. }
  108973. // Metadata
  108974. if (scene.metadata) {
  108975. serializationObject.metadata = scene.metadata;
  108976. }
  108977. // Morph targets
  108978. serializationObject.morphTargetManagers = [];
  108979. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  108980. var abstractMesh = _a[_i];
  108981. var manager = abstractMesh.morphTargetManager;
  108982. if (manager) {
  108983. serializationObject.morphTargetManagers.push(manager.serialize());
  108984. }
  108985. }
  108986. // Lights
  108987. serializationObject.lights = [];
  108988. var index;
  108989. var light;
  108990. for (index = 0; index < scene.lights.length; index++) {
  108991. light = scene.lights[index];
  108992. if (!light.doNotSerialize) {
  108993. serializationObject.lights.push(light.serialize());
  108994. }
  108995. }
  108996. // Cameras
  108997. serializationObject.cameras = [];
  108998. for (index = 0; index < scene.cameras.length; index++) {
  108999. var camera = scene.cameras[index];
  109000. if (!camera.doNotSerialize) {
  109001. serializationObject.cameras.push(camera.serialize());
  109002. }
  109003. }
  109004. if (scene.activeCamera) {
  109005. serializationObject.activeCameraID = scene.activeCamera.id;
  109006. }
  109007. // Animations
  109008. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  109009. // Materials
  109010. serializationObject.materials = [];
  109011. serializationObject.multiMaterials = [];
  109012. var material;
  109013. for (index = 0; index < scene.materials.length; index++) {
  109014. material = scene.materials[index];
  109015. if (!material.doNotSerialize) {
  109016. serializationObject.materials.push(material.serialize());
  109017. }
  109018. }
  109019. // MultiMaterials
  109020. serializationObject.multiMaterials = [];
  109021. for (index = 0; index < scene.multiMaterials.length; index++) {
  109022. var multiMaterial = scene.multiMaterials[index];
  109023. serializationObject.multiMaterials.push(multiMaterial.serialize());
  109024. }
  109025. // Environment texture
  109026. if (scene.environmentTexture) {
  109027. serializationObject.environmentTexture = scene.environmentTexture.name;
  109028. }
  109029. // Skeletons
  109030. serializationObject.skeletons = [];
  109031. for (index = 0; index < scene.skeletons.length; index++) {
  109032. var skeleton = scene.skeletons[index];
  109033. if (!skeleton.doNotSerialize) {
  109034. serializationObject.skeletons.push(skeleton.serialize());
  109035. }
  109036. }
  109037. // Transform nodes
  109038. serializationObject.transformNodes = [];
  109039. for (index = 0; index < scene.transformNodes.length; index++) {
  109040. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  109041. }
  109042. // Geometries
  109043. serializationObject.geometries = {};
  109044. serializationObject.geometries.boxes = [];
  109045. serializationObject.geometries.spheres = [];
  109046. serializationObject.geometries.cylinders = [];
  109047. serializationObject.geometries.toruses = [];
  109048. serializationObject.geometries.grounds = [];
  109049. serializationObject.geometries.planes = [];
  109050. serializationObject.geometries.torusKnots = [];
  109051. serializationObject.geometries.vertexData = [];
  109052. serializedGeometries = [];
  109053. var geometries = scene.getGeometries();
  109054. for (index = 0; index < geometries.length; index++) {
  109055. var geometry = geometries[index];
  109056. if (geometry.isReady()) {
  109057. serializeGeometry(geometry, serializationObject.geometries);
  109058. }
  109059. }
  109060. // Meshes
  109061. serializationObject.meshes = [];
  109062. for (index = 0; index < scene.meshes.length; index++) {
  109063. var abstractMesh = scene.meshes[index];
  109064. if (abstractMesh instanceof BABYLON.Mesh) {
  109065. var mesh = abstractMesh;
  109066. if (!mesh.doNotSerialize) {
  109067. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109068. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109069. }
  109070. }
  109071. }
  109072. }
  109073. // Particles Systems
  109074. serializationObject.particleSystems = [];
  109075. for (index = 0; index < scene.particleSystems.length; index++) {
  109076. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  109077. }
  109078. // Action Manager
  109079. if (scene.actionManager) {
  109080. serializationObject.actions = scene.actionManager.serialize("scene");
  109081. }
  109082. // Components
  109083. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  109084. var component = _c[_b];
  109085. component.serialize(serializationObject);
  109086. }
  109087. return serializationObject;
  109088. };
  109089. /**
  109090. * Serialize a mesh into a JSON compatible object
  109091. * @param toSerialize defines the mesh to serialize
  109092. * @param withParents defines if parents must be serialized as well
  109093. * @param withChildren defines if children must be serialized as well
  109094. * @returns a JSON compatible object
  109095. */
  109096. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  109097. if (withParents === void 0) { withParents = false; }
  109098. if (withChildren === void 0) { withChildren = false; }
  109099. var serializationObject = {};
  109100. SceneSerializer.ClearCache();
  109101. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  109102. if (withParents || withChildren) {
  109103. //deliberate for loop! not for each, appended should be processed as well.
  109104. for (var i = 0; i < toSerialize.length; ++i) {
  109105. if (withChildren) {
  109106. toSerialize[i].getDescendants().forEach(function (node) {
  109107. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  109108. toSerialize.push(node);
  109109. }
  109110. });
  109111. }
  109112. //make sure the array doesn't contain the object already
  109113. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  109114. toSerialize.push(toSerialize[i].parent);
  109115. }
  109116. }
  109117. }
  109118. toSerialize.forEach(function (mesh) {
  109119. finalizeSingleMesh(mesh, serializationObject);
  109120. });
  109121. return serializationObject;
  109122. };
  109123. return SceneSerializer;
  109124. }());
  109125. BABYLON.SceneSerializer = SceneSerializer;
  109126. })(BABYLON || (BABYLON = {}));
  109127. //# sourceMappingURL=babylon.sceneSerializer.js.map
  109128. var BABYLON;
  109129. (function (BABYLON) {
  109130. /**
  109131. * Class used to generate realtime reflection / refraction cube textures
  109132. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  109133. */
  109134. var ReflectionProbe = /** @class */ (function () {
  109135. /**
  109136. * Creates a new reflection probe
  109137. * @param name defines the name of the probe
  109138. * @param size defines the texture resolution (for each face)
  109139. * @param scene defines the hosting scene
  109140. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  109141. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  109142. */
  109143. function ReflectionProbe(
  109144. /** defines the name of the probe */
  109145. name, size, scene, generateMipMaps, useFloat) {
  109146. if (generateMipMaps === void 0) { generateMipMaps = true; }
  109147. if (useFloat === void 0) { useFloat = false; }
  109148. var _this = this;
  109149. this.name = name;
  109150. this._viewMatrix = BABYLON.Matrix.Identity();
  109151. this._target = BABYLON.Vector3.Zero();
  109152. this._add = BABYLON.Vector3.Zero();
  109153. this._invertYAxis = false;
  109154. /** Gets or sets probe position (center of the cube map) */
  109155. this.position = BABYLON.Vector3.Zero();
  109156. this._scene = scene;
  109157. // Create the scene field if not exist.
  109158. if (!this._scene.reflectionProbes) {
  109159. this._scene.reflectionProbes = new Array();
  109160. }
  109161. this._scene.reflectionProbes.push(this);
  109162. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  109163. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  109164. switch (faceIndex) {
  109165. case 0:
  109166. _this._add.copyFromFloats(1, 0, 0);
  109167. break;
  109168. case 1:
  109169. _this._add.copyFromFloats(-1, 0, 0);
  109170. break;
  109171. case 2:
  109172. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  109173. break;
  109174. case 3:
  109175. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  109176. break;
  109177. case 4:
  109178. _this._add.copyFromFloats(0, 0, 1);
  109179. break;
  109180. case 5:
  109181. _this._add.copyFromFloats(0, 0, -1);
  109182. break;
  109183. }
  109184. if (_this._attachedMesh) {
  109185. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  109186. }
  109187. _this.position.addToRef(_this._add, _this._target);
  109188. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  109189. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  109190. scene._forcedViewPosition = _this.position;
  109191. });
  109192. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  109193. scene._forcedViewPosition = null;
  109194. scene.updateTransformMatrix(true);
  109195. });
  109196. if (scene.activeCamera) {
  109197. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  109198. }
  109199. }
  109200. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  109201. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  109202. get: function () {
  109203. return this._renderTargetTexture.samples;
  109204. },
  109205. set: function (value) {
  109206. this._renderTargetTexture.samples = value;
  109207. },
  109208. enumerable: true,
  109209. configurable: true
  109210. });
  109211. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  109212. /** Gets or sets the refresh rate to use (on every frame by default) */
  109213. get: function () {
  109214. return this._renderTargetTexture.refreshRate;
  109215. },
  109216. set: function (value) {
  109217. this._renderTargetTexture.refreshRate = value;
  109218. },
  109219. enumerable: true,
  109220. configurable: true
  109221. });
  109222. /**
  109223. * Gets the hosting scene
  109224. * @returns a Scene
  109225. */
  109226. ReflectionProbe.prototype.getScene = function () {
  109227. return this._scene;
  109228. };
  109229. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  109230. /** Gets the internal CubeTexture used to render to */
  109231. get: function () {
  109232. return this._renderTargetTexture;
  109233. },
  109234. enumerable: true,
  109235. configurable: true
  109236. });
  109237. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  109238. /** Gets the list of meshes to render */
  109239. get: function () {
  109240. return this._renderTargetTexture.renderList;
  109241. },
  109242. enumerable: true,
  109243. configurable: true
  109244. });
  109245. /**
  109246. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  109247. * @param mesh defines the mesh to attach to
  109248. */
  109249. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  109250. this._attachedMesh = mesh;
  109251. };
  109252. /**
  109253. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  109254. * @param renderingGroupId The rendering group id corresponding to its index
  109255. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  109256. */
  109257. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  109258. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  109259. };
  109260. /**
  109261. * Clean all associated resources
  109262. */
  109263. ReflectionProbe.prototype.dispose = function () {
  109264. var index = this._scene.reflectionProbes.indexOf(this);
  109265. if (index !== -1) {
  109266. // Remove from the scene if found
  109267. this._scene.reflectionProbes.splice(index, 1);
  109268. }
  109269. if (this._renderTargetTexture) {
  109270. this._renderTargetTexture.dispose();
  109271. this._renderTargetTexture = null;
  109272. }
  109273. };
  109274. return ReflectionProbe;
  109275. }());
  109276. BABYLON.ReflectionProbe = ReflectionProbe;
  109277. })(BABYLON || (BABYLON = {}));
  109278. //# sourceMappingURL=babylon.reflectionProbe.js.map
  109279. var BABYLON;
  109280. (function (BABYLON) {
  109281. /**
  109282. * Defines the layer scene component responsible to manage any layers
  109283. * in a given scene.
  109284. */
  109285. var LayerSceneComponent = /** @class */ (function () {
  109286. /**
  109287. * Creates a new instance of the component for the given scene
  109288. * @param scene Defines the scene to register the component in
  109289. */
  109290. function LayerSceneComponent(scene) {
  109291. /**
  109292. * The component name helpfull to identify the component in the list of scene components.
  109293. */
  109294. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  109295. this.scene = scene;
  109296. this._engine = scene.getEngine();
  109297. scene.layers = new Array();
  109298. }
  109299. /**
  109300. * Registers the component in a given scene
  109301. */
  109302. LayerSceneComponent.prototype.register = function () {
  109303. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  109304. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  109305. };
  109306. /**
  109307. * Rebuilds the elements related to this component in case of
  109308. * context lost for instance.
  109309. */
  109310. LayerSceneComponent.prototype.rebuild = function () {
  109311. var layers = this.scene.layers;
  109312. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  109313. var layer = layers_1[_i];
  109314. layer._rebuild();
  109315. }
  109316. };
  109317. /**
  109318. * Disposes the component and the associated ressources.
  109319. */
  109320. LayerSceneComponent.prototype.dispose = function () {
  109321. var layers = this.scene.layers;
  109322. while (layers.length) {
  109323. layers[0].dispose();
  109324. }
  109325. };
  109326. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  109327. var layers = this.scene.layers;
  109328. if (layers.length) {
  109329. this._engine.setDepthBuffer(false);
  109330. var cameraLayerMask = camera.layerMask;
  109331. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  109332. var layer = layers_2[_i];
  109333. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  109334. layer.render();
  109335. }
  109336. }
  109337. this._engine.setDepthBuffer(true);
  109338. }
  109339. };
  109340. LayerSceneComponent.prototype._drawBackground = function (camera) {
  109341. this._draw(camera, true);
  109342. };
  109343. LayerSceneComponent.prototype._drawForeground = function (camera) {
  109344. this._draw(camera, false);
  109345. };
  109346. return LayerSceneComponent;
  109347. }());
  109348. BABYLON.LayerSceneComponent = LayerSceneComponent;
  109349. })(BABYLON || (BABYLON = {}));
  109350. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  109351. var BABYLON;
  109352. (function (BABYLON) {
  109353. /**
  109354. * This represents a full screen 2d layer.
  109355. * This can be usefull to display a picture in the background of your scene for instance.
  109356. * @see https://www.babylonjs-playground.com/#08A2BS#1
  109357. */
  109358. var Layer = /** @class */ (function () {
  109359. /**
  109360. * Instantiates a new layer.
  109361. * This represents a full screen 2d layer.
  109362. * This can be usefull to display a picture in the background of your scene for instance.
  109363. * @see https://www.babylonjs-playground.com/#08A2BS#1
  109364. * @param name Define the name of the layer in the scene
  109365. * @param imgUrl Define the url of the texture to display in the layer
  109366. * @param scene Define the scene the layer belongs to
  109367. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  109368. * @param color Defines a color for the layer
  109369. */
  109370. function Layer(
  109371. /**
  109372. * Define the name of the layer.
  109373. */
  109374. name, imgUrl, scene, isBackground, color) {
  109375. this.name = name;
  109376. /**
  109377. * Define the scale of the layer in order to zoom in out of the texture.
  109378. */
  109379. this.scale = new BABYLON.Vector2(1, 1);
  109380. /**
  109381. * Define an offset for the layer in order to shift the texture.
  109382. */
  109383. this.offset = new BABYLON.Vector2(0, 0);
  109384. /**
  109385. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  109386. */
  109387. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  109388. /**
  109389. * Define a mask to restrict the layer to only some of the scene cameras.
  109390. */
  109391. this.layerMask = 0x0FFFFFFF;
  109392. this._vertexBuffers = {};
  109393. /**
  109394. * An event triggered when the layer is disposed.
  109395. */
  109396. this.onDisposeObservable = new BABYLON.Observable();
  109397. /**
  109398. * An event triggered before rendering the scene
  109399. */
  109400. this.onBeforeRenderObservable = new BABYLON.Observable();
  109401. /**
  109402. * An event triggered after rendering the scene
  109403. */
  109404. this.onAfterRenderObservable = new BABYLON.Observable();
  109405. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  109406. this.isBackground = isBackground === undefined ? true : isBackground;
  109407. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  109408. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  109409. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  109410. if (!layerComponent) {
  109411. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  109412. this._scene._addComponent(layerComponent);
  109413. }
  109414. this._scene.layers.push(this);
  109415. var engine = this._scene.getEngine();
  109416. // VBO
  109417. var vertices = [];
  109418. vertices.push(1, 1);
  109419. vertices.push(-1, 1);
  109420. vertices.push(-1, -1);
  109421. vertices.push(1, -1);
  109422. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  109423. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  109424. this._createIndexBuffer();
  109425. // Effects
  109426. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  109427. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  109428. }
  109429. Object.defineProperty(Layer.prototype, "onDispose", {
  109430. /**
  109431. * Back compatibility with callback before the onDisposeObservable existed.
  109432. * The set callback will be triggered when the layer has been disposed.
  109433. */
  109434. set: function (callback) {
  109435. if (this._onDisposeObserver) {
  109436. this.onDisposeObservable.remove(this._onDisposeObserver);
  109437. }
  109438. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  109439. },
  109440. enumerable: true,
  109441. configurable: true
  109442. });
  109443. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  109444. /**
  109445. * Back compatibility with callback before the onBeforeRenderObservable existed.
  109446. * The set callback will be triggered just before rendering the layer.
  109447. */
  109448. set: function (callback) {
  109449. if (this._onBeforeRenderObserver) {
  109450. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  109451. }
  109452. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  109453. },
  109454. enumerable: true,
  109455. configurable: true
  109456. });
  109457. Object.defineProperty(Layer.prototype, "onAfterRender", {
  109458. /**
  109459. * Back compatibility with callback before the onAfterRenderObservable existed.
  109460. * The set callback will be triggered just after rendering the layer.
  109461. */
  109462. set: function (callback) {
  109463. if (this._onAfterRenderObserver) {
  109464. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  109465. }
  109466. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  109467. },
  109468. enumerable: true,
  109469. configurable: true
  109470. });
  109471. Layer.prototype._createIndexBuffer = function () {
  109472. var engine = this._scene.getEngine();
  109473. // Indices
  109474. var indices = [];
  109475. indices.push(0);
  109476. indices.push(1);
  109477. indices.push(2);
  109478. indices.push(0);
  109479. indices.push(2);
  109480. indices.push(3);
  109481. this._indexBuffer = engine.createIndexBuffer(indices);
  109482. };
  109483. /** @hidden */
  109484. Layer.prototype._rebuild = function () {
  109485. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109486. if (vb) {
  109487. vb._rebuild();
  109488. }
  109489. this._createIndexBuffer();
  109490. };
  109491. /**
  109492. * Renders the layer in the scene.
  109493. */
  109494. Layer.prototype.render = function () {
  109495. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  109496. // Check
  109497. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  109498. return;
  109499. var engine = this._scene.getEngine();
  109500. this.onBeforeRenderObservable.notifyObservers(this);
  109501. // Render
  109502. engine.enableEffect(currentEffect);
  109503. engine.setState(false);
  109504. // Texture
  109505. currentEffect.setTexture("textureSampler", this.texture);
  109506. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  109507. // Color
  109508. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  109509. // Scale / offset
  109510. currentEffect.setVector2("offset", this.offset);
  109511. currentEffect.setVector2("scale", this.scale);
  109512. // VBOs
  109513. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109514. // Draw order
  109515. if (!this.alphaTest) {
  109516. engine.setAlphaMode(this.alphaBlendingMode);
  109517. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109518. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  109519. }
  109520. else {
  109521. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109522. }
  109523. this.onAfterRenderObservable.notifyObservers(this);
  109524. };
  109525. /**
  109526. * Disposes and releases the associated ressources.
  109527. */
  109528. Layer.prototype.dispose = function () {
  109529. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109530. if (vertexBuffer) {
  109531. vertexBuffer.dispose();
  109532. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109533. }
  109534. if (this._indexBuffer) {
  109535. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109536. this._indexBuffer = null;
  109537. }
  109538. if (this.texture) {
  109539. this.texture.dispose();
  109540. this.texture = null;
  109541. }
  109542. // Remove from scene
  109543. var index = this._scene.layers.indexOf(this);
  109544. this._scene.layers.splice(index, 1);
  109545. // Callback
  109546. this.onDisposeObservable.notifyObservers(this);
  109547. this.onDisposeObservable.clear();
  109548. this.onAfterRenderObservable.clear();
  109549. this.onBeforeRenderObservable.clear();
  109550. };
  109551. return Layer;
  109552. }());
  109553. BABYLON.Layer = Layer;
  109554. })(BABYLON || (BABYLON = {}));
  109555. //# sourceMappingURL=babylon.layer.js.map
  109556. var BABYLON;
  109557. (function (BABYLON) {
  109558. /**
  109559. * Class used to host texture specific utilities
  109560. */
  109561. var TextureTools = /** @class */ (function () {
  109562. function TextureTools() {
  109563. }
  109564. /**
  109565. * Uses the GPU to create a copy texture rescaled at a given size
  109566. * @param texture Texture to copy from
  109567. * @param width defines the desired width
  109568. * @param height defines the desired height
  109569. * @param useBilinearMode defines if bilinear mode has to be used
  109570. * @return the generated texture
  109571. */
  109572. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  109573. if (useBilinearMode === void 0) { useBilinearMode = true; }
  109574. var scene = texture.getScene();
  109575. var engine = scene.getEngine();
  109576. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  109577. rtt.wrapU = texture.wrapU;
  109578. rtt.wrapV = texture.wrapV;
  109579. rtt.uOffset = texture.uOffset;
  109580. rtt.vOffset = texture.vOffset;
  109581. rtt.uScale = texture.uScale;
  109582. rtt.vScale = texture.vScale;
  109583. rtt.uAng = texture.uAng;
  109584. rtt.vAng = texture.vAng;
  109585. rtt.wAng = texture.wAng;
  109586. rtt.coordinatesIndex = texture.coordinatesIndex;
  109587. rtt.level = texture.level;
  109588. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  109589. rtt._texture.isReady = false;
  109590. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109591. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109592. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  109593. passPostProcess.getEffect().executeWhenCompiled(function () {
  109594. passPostProcess.onApply = function (effect) {
  109595. effect.setTexture("textureSampler", texture);
  109596. };
  109597. var internalTexture = rtt.getInternalTexture();
  109598. if (internalTexture) {
  109599. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  109600. engine.unBindFramebuffer(internalTexture);
  109601. rtt.disposeFramebufferObjects();
  109602. passPostProcess.dispose();
  109603. internalTexture.isReady = true;
  109604. }
  109605. });
  109606. return rtt;
  109607. };
  109608. /**
  109609. * Gets an environment BRDF texture for a given scene
  109610. * @param scene defines the hosting scene
  109611. * @returns the environment BRDF texture
  109612. */
  109613. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  109614. if (!scene._environmentBRDFTexture) {
  109615. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  109616. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109617. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109618. scene._environmentBRDFTexture = texture;
  109619. }
  109620. return scene._environmentBRDFTexture;
  109621. };
  109622. 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=";
  109623. return TextureTools;
  109624. }());
  109625. BABYLON.TextureTools = TextureTools;
  109626. })(BABYLON || (BABYLON = {}));
  109627. //# sourceMappingURL=babylon.textureTools.js.map
  109628. var BABYLON;
  109629. (function (BABYLON) {
  109630. /**
  109631. * 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.
  109632. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  109633. */
  109634. var FramingBehavior = /** @class */ (function () {
  109635. function FramingBehavior() {
  109636. this._mode = FramingBehavior.FitFrustumSidesMode;
  109637. this._radiusScale = 1.0;
  109638. this._positionScale = 0.5;
  109639. this._defaultElevation = 0.3;
  109640. this._elevationReturnTime = 1500;
  109641. this._elevationReturnWaitTime = 1000;
  109642. this._zoomStopsAnimation = false;
  109643. this._framingTime = 1500;
  109644. /**
  109645. * Define if the behavior should automatically change the configured
  109646. * camera limits and sensibilities.
  109647. */
  109648. this.autoCorrectCameraLimitsAndSensibility = true;
  109649. this._isPointerDown = false;
  109650. this._lastInteractionTime = -Infinity;
  109651. // Framing control
  109652. this._animatables = new Array();
  109653. this._betaIsAnimating = false;
  109654. }
  109655. Object.defineProperty(FramingBehavior.prototype, "name", {
  109656. /**
  109657. * Gets the name of the behavior.
  109658. */
  109659. get: function () {
  109660. return "Framing";
  109661. },
  109662. enumerable: true,
  109663. configurable: true
  109664. });
  109665. Object.defineProperty(FramingBehavior.prototype, "mode", {
  109666. /**
  109667. * Gets current mode used by the behavior.
  109668. */
  109669. get: function () {
  109670. return this._mode;
  109671. },
  109672. /**
  109673. * Sets the current mode used by the behavior
  109674. */
  109675. set: function (mode) {
  109676. this._mode = mode;
  109677. },
  109678. enumerable: true,
  109679. configurable: true
  109680. });
  109681. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  109682. /**
  109683. * Gets the scale applied to the radius
  109684. */
  109685. get: function () {
  109686. return this._radiusScale;
  109687. },
  109688. /**
  109689. * Sets the scale applied to the radius (1 by default)
  109690. */
  109691. set: function (radius) {
  109692. this._radiusScale = radius;
  109693. },
  109694. enumerable: true,
  109695. configurable: true
  109696. });
  109697. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  109698. /**
  109699. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  109700. */
  109701. get: function () {
  109702. return this._positionScale;
  109703. },
  109704. /**
  109705. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  109706. */
  109707. set: function (scale) {
  109708. this._positionScale = scale;
  109709. },
  109710. enumerable: true,
  109711. configurable: true
  109712. });
  109713. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  109714. /**
  109715. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  109716. * behaviour is triggered, in radians.
  109717. */
  109718. get: function () {
  109719. return this._defaultElevation;
  109720. },
  109721. /**
  109722. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  109723. * behaviour is triggered, in radians.
  109724. */
  109725. set: function (elevation) {
  109726. this._defaultElevation = elevation;
  109727. },
  109728. enumerable: true,
  109729. configurable: true
  109730. });
  109731. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  109732. /**
  109733. * Gets the time (in milliseconds) taken to return to the default beta position.
  109734. * Negative value indicates camera should not return to default.
  109735. */
  109736. get: function () {
  109737. return this._elevationReturnTime;
  109738. },
  109739. /**
  109740. * Sets the time (in milliseconds) taken to return to the default beta position.
  109741. * Negative value indicates camera should not return to default.
  109742. */
  109743. set: function (speed) {
  109744. this._elevationReturnTime = speed;
  109745. },
  109746. enumerable: true,
  109747. configurable: true
  109748. });
  109749. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  109750. /**
  109751. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  109752. */
  109753. get: function () {
  109754. return this._elevationReturnWaitTime;
  109755. },
  109756. /**
  109757. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  109758. */
  109759. set: function (time) {
  109760. this._elevationReturnWaitTime = time;
  109761. },
  109762. enumerable: true,
  109763. configurable: true
  109764. });
  109765. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  109766. /**
  109767. * Gets the flag that indicates if user zooming should stop animation.
  109768. */
  109769. get: function () {
  109770. return this._zoomStopsAnimation;
  109771. },
  109772. /**
  109773. * Sets the flag that indicates if user zooming should stop animation.
  109774. */
  109775. set: function (flag) {
  109776. this._zoomStopsAnimation = flag;
  109777. },
  109778. enumerable: true,
  109779. configurable: true
  109780. });
  109781. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  109782. /**
  109783. * Gets the transition time when framing the mesh, in milliseconds
  109784. */
  109785. get: function () {
  109786. return this._framingTime;
  109787. },
  109788. /**
  109789. * Sets the transition time when framing the mesh, in milliseconds
  109790. */
  109791. set: function (time) {
  109792. this._framingTime = time;
  109793. },
  109794. enumerable: true,
  109795. configurable: true
  109796. });
  109797. /**
  109798. * Initializes the behavior.
  109799. */
  109800. FramingBehavior.prototype.init = function () {
  109801. // Do notihng
  109802. };
  109803. /**
  109804. * Attaches the behavior to its arc rotate camera.
  109805. * @param camera Defines the camera to attach the behavior to
  109806. */
  109807. FramingBehavior.prototype.attach = function (camera) {
  109808. var _this = this;
  109809. this._attachedCamera = camera;
  109810. var scene = this._attachedCamera.getScene();
  109811. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  109812. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109813. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109814. _this._isPointerDown = true;
  109815. return;
  109816. }
  109817. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109818. _this._isPointerDown = false;
  109819. }
  109820. });
  109821. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  109822. if (mesh) {
  109823. _this.zoomOnMesh(mesh);
  109824. }
  109825. });
  109826. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109827. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109828. _this._applyUserInteraction();
  109829. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  109830. // back to the default position after a given timeout
  109831. _this._maintainCameraAboveGround();
  109832. });
  109833. };
  109834. /**
  109835. * Detaches the behavior from its current arc rotate camera.
  109836. */
  109837. FramingBehavior.prototype.detach = function () {
  109838. if (!this._attachedCamera) {
  109839. return;
  109840. }
  109841. var scene = this._attachedCamera.getScene();
  109842. if (this._onPrePointerObservableObserver) {
  109843. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109844. }
  109845. if (this._onAfterCheckInputsObserver) {
  109846. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109847. }
  109848. if (this._onMeshTargetChangedObserver) {
  109849. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109850. }
  109851. this._attachedCamera = null;
  109852. };
  109853. /**
  109854. * Targets the given mesh and updates zoom level accordingly.
  109855. * @param mesh The mesh to target.
  109856. * @param radius Optional. If a cached radius position already exists, overrides default.
  109857. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109858. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109859. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109860. */
  109861. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109862. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109863. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109864. mesh.computeWorldMatrix(true);
  109865. var boundingBox = mesh.getBoundingInfo().boundingBox;
  109866. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  109867. };
  109868. /**
  109869. * Targets the given mesh with its children and updates zoom level accordingly.
  109870. * @param mesh The mesh to target.
  109871. * @param radius Optional. If a cached radius position already exists, overrides default.
  109872. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109873. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109874. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109875. */
  109876. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109877. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109878. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109879. mesh.computeWorldMatrix(true);
  109880. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  109881. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  109882. };
  109883. /**
  109884. * Targets the given meshes with their children and updates zoom level accordingly.
  109885. * @param meshes The mesh to target.
  109886. * @param radius Optional. If a cached radius position already exists, overrides default.
  109887. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109888. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109889. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109890. */
  109891. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  109892. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109893. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109894. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  109895. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  109896. for (var i = 0; i < meshes.length; i++) {
  109897. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  109898. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  109899. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  109900. }
  109901. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  109902. };
  109903. /**
  109904. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  109905. * @param minimumWorld Determines the smaller position of the bounding box extend
  109906. * @param maximumWorld Determines the bigger position of the bounding box extend
  109907. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109908. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109909. */
  109910. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  109911. var _this = this;
  109912. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109913. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109914. var zoomTarget;
  109915. if (!this._attachedCamera) {
  109916. return;
  109917. }
  109918. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  109919. var bottom = minimumWorld.y;
  109920. var top = maximumWorld.y;
  109921. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  109922. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  109923. if (focusOnOriginXZ) {
  109924. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  109925. }
  109926. else {
  109927. var centerWorld = minimumWorld.add(radiusWorld);
  109928. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  109929. }
  109930. if (!this._vectorTransition) {
  109931. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  109932. }
  109933. this._betaIsAnimating = true;
  109934. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  109935. if (animatable) {
  109936. this._animatables.push(animatable);
  109937. }
  109938. // sets the radius and lower radius bounds
  109939. // Small delta ensures camera is not always at lower zoom limit.
  109940. var radius = 0;
  109941. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  109942. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109943. if (this.autoCorrectCameraLimitsAndSensibility) {
  109944. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  109945. }
  109946. radius = position;
  109947. }
  109948. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  109949. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109950. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  109951. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  109952. }
  109953. }
  109954. // Set sensibilities
  109955. if (this.autoCorrectCameraLimitsAndSensibility) {
  109956. var extend = maximumWorld.subtract(minimumWorld).length();
  109957. this._attachedCamera.panningSensibility = 5000 / extend;
  109958. this._attachedCamera.wheelPrecision = 100 / radius;
  109959. }
  109960. // transition to new radius
  109961. if (!this._radiusTransition) {
  109962. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  109963. }
  109964. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  109965. _this.stopAllAnimations();
  109966. if (onAnimationEnd) {
  109967. onAnimationEnd();
  109968. }
  109969. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  109970. _this._attachedCamera.storeState();
  109971. }
  109972. });
  109973. if (animatable) {
  109974. this._animatables.push(animatable);
  109975. }
  109976. };
  109977. /**
  109978. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  109979. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  109980. * frustum width.
  109981. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  109982. * to fully enclose the mesh in the viewing frustum.
  109983. */
  109984. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  109985. var size = maximumWorld.subtract(minimumWorld);
  109986. var boxVectorGlobalDiagonal = size.length();
  109987. var frustumSlope = this._getFrustumSlope();
  109988. // Formula for setting distance
  109989. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  109990. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  109991. // Horizon distance
  109992. var radius = radiusWithoutFraming * this._radiusScale;
  109993. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  109994. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  109995. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  109996. var camera = this._attachedCamera;
  109997. if (!camera) {
  109998. return 0;
  109999. }
  110000. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110001. // Don't exceed the requested limit
  110002. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  110003. }
  110004. // Don't exceed the upper radius limit
  110005. if (camera.upperRadiusLimit) {
  110006. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  110007. }
  110008. return distance;
  110009. };
  110010. /**
  110011. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  110012. * is automatically returned to its default position (expected to be above ground plane).
  110013. */
  110014. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  110015. var _this = this;
  110016. if (this._elevationReturnTime < 0) {
  110017. return;
  110018. }
  110019. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  110020. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  110021. var limitBeta = Math.PI * 0.5;
  110022. // Bring the camera back up if below the ground plane
  110023. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  110024. this._betaIsAnimating = true;
  110025. //Transition to new position
  110026. this.stopAllAnimations();
  110027. if (!this._betaTransition) {
  110028. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110029. }
  110030. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  110031. _this._clearAnimationLocks();
  110032. _this.stopAllAnimations();
  110033. });
  110034. if (animatabe) {
  110035. this._animatables.push(animatabe);
  110036. }
  110037. }
  110038. };
  110039. /**
  110040. * Returns the frustum slope based on the canvas ratio and camera FOV
  110041. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  110042. */
  110043. FramingBehavior.prototype._getFrustumSlope = function () {
  110044. // Calculate the viewport ratio
  110045. // Aspect Ratio is Height/Width.
  110046. var camera = this._attachedCamera;
  110047. if (!camera) {
  110048. return BABYLON.Vector2.Zero();
  110049. }
  110050. var engine = camera.getScene().getEngine();
  110051. var aspectRatio = engine.getAspectRatio(camera);
  110052. // Camera FOV is the vertical field of view (top-bottom) in radians.
  110053. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  110054. var frustumSlopeY = Math.tan(camera.fov / 2);
  110055. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  110056. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  110057. // along the forward vector.
  110058. var frustumSlopeX = frustumSlopeY * aspectRatio;
  110059. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  110060. };
  110061. /**
  110062. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  110063. */
  110064. FramingBehavior.prototype._clearAnimationLocks = function () {
  110065. this._betaIsAnimating = false;
  110066. };
  110067. /**
  110068. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  110069. */
  110070. FramingBehavior.prototype._applyUserInteraction = function () {
  110071. if (this.isUserIsMoving) {
  110072. this._lastInteractionTime = BABYLON.Tools.Now;
  110073. this.stopAllAnimations();
  110074. this._clearAnimationLocks();
  110075. }
  110076. };
  110077. /**
  110078. * Stops and removes all animations that have been applied to the camera
  110079. */
  110080. FramingBehavior.prototype.stopAllAnimations = function () {
  110081. if (this._attachedCamera) {
  110082. this._attachedCamera.animations = [];
  110083. }
  110084. while (this._animatables.length) {
  110085. if (this._animatables[0]) {
  110086. this._animatables[0].onAnimationEnd = null;
  110087. this._animatables[0].stop();
  110088. }
  110089. this._animatables.shift();
  110090. }
  110091. };
  110092. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  110093. /**
  110094. * Gets a value indicating if the user is moving the camera
  110095. */
  110096. get: function () {
  110097. if (!this._attachedCamera) {
  110098. return false;
  110099. }
  110100. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  110101. this._attachedCamera.inertialBetaOffset !== 0 ||
  110102. this._attachedCamera.inertialRadiusOffset !== 0 ||
  110103. this._attachedCamera.inertialPanningX !== 0 ||
  110104. this._attachedCamera.inertialPanningY !== 0 ||
  110105. this._isPointerDown;
  110106. },
  110107. enumerable: true,
  110108. configurable: true
  110109. });
  110110. /**
  110111. * The easing function used by animations
  110112. */
  110113. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  110114. /**
  110115. * The easing mode used by animations
  110116. */
  110117. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  110118. // Statics
  110119. /**
  110120. * The camera can move all the way towards the mesh.
  110121. */
  110122. FramingBehavior.IgnoreBoundsSizeMode = 0;
  110123. /**
  110124. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  110125. */
  110126. FramingBehavior.FitFrustumSidesMode = 1;
  110127. return FramingBehavior;
  110128. }());
  110129. BABYLON.FramingBehavior = FramingBehavior;
  110130. })(BABYLON || (BABYLON = {}));
  110131. //# sourceMappingURL=babylon.framingBehavior.js.map
  110132. var BABYLON;
  110133. (function (BABYLON) {
  110134. /**
  110135. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  110136. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  110137. */
  110138. var BouncingBehavior = /** @class */ (function () {
  110139. function BouncingBehavior() {
  110140. /**
  110141. * The duration of the animation, in milliseconds
  110142. */
  110143. this.transitionDuration = 450;
  110144. /**
  110145. * Length of the distance animated by the transition when lower radius is reached
  110146. */
  110147. this.lowerRadiusTransitionRange = 2;
  110148. /**
  110149. * Length of the distance animated by the transition when upper radius is reached
  110150. */
  110151. this.upperRadiusTransitionRange = -2;
  110152. this._autoTransitionRange = false;
  110153. // Animations
  110154. this._radiusIsAnimating = false;
  110155. this._radiusBounceTransition = null;
  110156. this._animatables = new Array();
  110157. }
  110158. Object.defineProperty(BouncingBehavior.prototype, "name", {
  110159. /**
  110160. * Gets the name of the behavior.
  110161. */
  110162. get: function () {
  110163. return "Bouncing";
  110164. },
  110165. enumerable: true,
  110166. configurable: true
  110167. });
  110168. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  110169. /**
  110170. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  110171. */
  110172. get: function () {
  110173. return this._autoTransitionRange;
  110174. },
  110175. /**
  110176. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  110177. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  110178. */
  110179. set: function (value) {
  110180. var _this = this;
  110181. if (this._autoTransitionRange === value) {
  110182. return;
  110183. }
  110184. this._autoTransitionRange = value;
  110185. var camera = this._attachedCamera;
  110186. if (!camera) {
  110187. return;
  110188. }
  110189. if (value) {
  110190. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  110191. if (!mesh) {
  110192. return;
  110193. }
  110194. mesh.computeWorldMatrix(true);
  110195. var diagonal = mesh.getBoundingInfo().diagonalLength;
  110196. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  110197. _this.upperRadiusTransitionRange = diagonal * 0.05;
  110198. });
  110199. }
  110200. else if (this._onMeshTargetChangedObserver) {
  110201. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110202. }
  110203. },
  110204. enumerable: true,
  110205. configurable: true
  110206. });
  110207. /**
  110208. * Initializes the behavior.
  110209. */
  110210. BouncingBehavior.prototype.init = function () {
  110211. // Do notihng
  110212. };
  110213. /**
  110214. * Attaches the behavior to its arc rotate camera.
  110215. * @param camera Defines the camera to attach the behavior to
  110216. */
  110217. BouncingBehavior.prototype.attach = function (camera) {
  110218. var _this = this;
  110219. this._attachedCamera = camera;
  110220. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110221. if (!_this._attachedCamera) {
  110222. return;
  110223. }
  110224. // Add the bounce animation to the lower radius limit
  110225. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  110226. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  110227. }
  110228. // Add the bounce animation to the upper radius limit
  110229. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  110230. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  110231. }
  110232. });
  110233. };
  110234. /**
  110235. * Detaches the behavior from its current arc rotate camera.
  110236. */
  110237. BouncingBehavior.prototype.detach = function () {
  110238. if (!this._attachedCamera) {
  110239. return;
  110240. }
  110241. if (this._onAfterCheckInputsObserver) {
  110242. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110243. }
  110244. if (this._onMeshTargetChangedObserver) {
  110245. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110246. }
  110247. this._attachedCamera = null;
  110248. };
  110249. /**
  110250. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  110251. * @param radiusLimit The limit to check against.
  110252. * @return Bool to indicate if at limit.
  110253. */
  110254. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  110255. if (!this._attachedCamera) {
  110256. return false;
  110257. }
  110258. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  110259. return true;
  110260. }
  110261. return false;
  110262. };
  110263. /**
  110264. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  110265. * @param radiusDelta The delta by which to animate to. Can be negative.
  110266. */
  110267. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  110268. var _this = this;
  110269. if (!this._attachedCamera) {
  110270. return;
  110271. }
  110272. if (!this._radiusBounceTransition) {
  110273. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  110274. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  110275. }
  110276. // Prevent zoom until bounce has completed
  110277. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  110278. this._attachedCamera.wheelPrecision = Infinity;
  110279. this._attachedCamera.inertialRadiusOffset = 0;
  110280. // Animate to the radius limit
  110281. this.stopAllAnimations();
  110282. this._radiusIsAnimating = true;
  110283. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  110284. if (animatable) {
  110285. this._animatables.push(animatable);
  110286. }
  110287. };
  110288. /**
  110289. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  110290. */
  110291. BouncingBehavior.prototype._clearAnimationLocks = function () {
  110292. this._radiusIsAnimating = false;
  110293. if (this._attachedCamera) {
  110294. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  110295. }
  110296. };
  110297. /**
  110298. * Stops and removes all animations that have been applied to the camera
  110299. */
  110300. BouncingBehavior.prototype.stopAllAnimations = function () {
  110301. if (this._attachedCamera) {
  110302. this._attachedCamera.animations = [];
  110303. }
  110304. while (this._animatables.length) {
  110305. this._animatables[0].onAnimationEnd = null;
  110306. this._animatables[0].stop();
  110307. this._animatables.shift();
  110308. }
  110309. };
  110310. /**
  110311. * The easing function used by animations
  110312. */
  110313. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  110314. /**
  110315. * The easing mode used by animations
  110316. */
  110317. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  110318. return BouncingBehavior;
  110319. }());
  110320. BABYLON.BouncingBehavior = BouncingBehavior;
  110321. })(BABYLON || (BABYLON = {}));
  110322. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  110323. var BABYLON;
  110324. (function (BABYLON) {
  110325. /**
  110326. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  110327. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  110328. */
  110329. var AutoRotationBehavior = /** @class */ (function () {
  110330. function AutoRotationBehavior() {
  110331. this._zoomStopsAnimation = false;
  110332. this._idleRotationSpeed = 0.05;
  110333. this._idleRotationWaitTime = 2000;
  110334. this._idleRotationSpinupTime = 2000;
  110335. this._isPointerDown = false;
  110336. this._lastFrameTime = null;
  110337. this._lastInteractionTime = -Infinity;
  110338. this._cameraRotationSpeed = 0;
  110339. this._lastFrameRadius = 0;
  110340. }
  110341. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  110342. /**
  110343. * Gets the name of the behavior.
  110344. */
  110345. get: function () {
  110346. return "AutoRotation";
  110347. },
  110348. enumerable: true,
  110349. configurable: true
  110350. });
  110351. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  110352. /**
  110353. * Gets the flag that indicates if user zooming should stop animation.
  110354. */
  110355. get: function () {
  110356. return this._zoomStopsAnimation;
  110357. },
  110358. /**
  110359. * Sets the flag that indicates if user zooming should stop animation.
  110360. */
  110361. set: function (flag) {
  110362. this._zoomStopsAnimation = flag;
  110363. },
  110364. enumerable: true,
  110365. configurable: true
  110366. });
  110367. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  110368. /**
  110369. * Gets the default speed at which the camera rotates around the model.
  110370. */
  110371. get: function () {
  110372. return this._idleRotationSpeed;
  110373. },
  110374. /**
  110375. * Sets the default speed at which the camera rotates around the model.
  110376. */
  110377. set: function (speed) {
  110378. this._idleRotationSpeed = speed;
  110379. },
  110380. enumerable: true,
  110381. configurable: true
  110382. });
  110383. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  110384. /**
  110385. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  110386. */
  110387. get: function () {
  110388. return this._idleRotationWaitTime;
  110389. },
  110390. /**
  110391. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  110392. */
  110393. set: function (time) {
  110394. this._idleRotationWaitTime = time;
  110395. },
  110396. enumerable: true,
  110397. configurable: true
  110398. });
  110399. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  110400. /**
  110401. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  110402. */
  110403. get: function () {
  110404. return this._idleRotationSpinupTime;
  110405. },
  110406. /**
  110407. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  110408. */
  110409. set: function (time) {
  110410. this._idleRotationSpinupTime = time;
  110411. },
  110412. enumerable: true,
  110413. configurable: true
  110414. });
  110415. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  110416. /**
  110417. * Gets a value indicating if the camera is currently rotating because of this behavior
  110418. */
  110419. get: function () {
  110420. return Math.abs(this._cameraRotationSpeed) > 0;
  110421. },
  110422. enumerable: true,
  110423. configurable: true
  110424. });
  110425. /**
  110426. * Initializes the behavior.
  110427. */
  110428. AutoRotationBehavior.prototype.init = function () {
  110429. // Do notihng
  110430. };
  110431. /**
  110432. * Attaches the behavior to its arc rotate camera.
  110433. * @param camera Defines the camera to attach the behavior to
  110434. */
  110435. AutoRotationBehavior.prototype.attach = function (camera) {
  110436. var _this = this;
  110437. this._attachedCamera = camera;
  110438. var scene = this._attachedCamera.getScene();
  110439. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  110440. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  110441. _this._isPointerDown = true;
  110442. return;
  110443. }
  110444. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  110445. _this._isPointerDown = false;
  110446. }
  110447. });
  110448. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110449. var now = BABYLON.Tools.Now;
  110450. var dt = 0;
  110451. if (_this._lastFrameTime != null) {
  110452. dt = now - _this._lastFrameTime;
  110453. }
  110454. _this._lastFrameTime = now;
  110455. // Stop the animation if there is user interaction and the animation should stop for this interaction
  110456. _this._applyUserInteraction();
  110457. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  110458. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  110459. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  110460. // Step camera rotation by rotation speed
  110461. if (_this._attachedCamera) {
  110462. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  110463. }
  110464. });
  110465. };
  110466. /**
  110467. * Detaches the behavior from its current arc rotate camera.
  110468. */
  110469. AutoRotationBehavior.prototype.detach = function () {
  110470. if (!this._attachedCamera) {
  110471. return;
  110472. }
  110473. var scene = this._attachedCamera.getScene();
  110474. if (this._onPrePointerObservableObserver) {
  110475. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  110476. }
  110477. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110478. this._attachedCamera = null;
  110479. };
  110480. /**
  110481. * Returns true if user is scrolling.
  110482. * @return true if user is scrolling.
  110483. */
  110484. AutoRotationBehavior.prototype._userIsZooming = function () {
  110485. if (!this._attachedCamera) {
  110486. return false;
  110487. }
  110488. return this._attachedCamera.inertialRadiusOffset !== 0;
  110489. };
  110490. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  110491. if (!this._attachedCamera) {
  110492. return false;
  110493. }
  110494. var zoomHasHitLimit = false;
  110495. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  110496. zoomHasHitLimit = true;
  110497. }
  110498. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  110499. this._lastFrameRadius = this._attachedCamera.radius;
  110500. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  110501. };
  110502. /**
  110503. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  110504. */
  110505. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  110506. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  110507. this._lastInteractionTime = BABYLON.Tools.Now;
  110508. }
  110509. };
  110510. // Tools
  110511. AutoRotationBehavior.prototype._userIsMoving = function () {
  110512. if (!this._attachedCamera) {
  110513. return false;
  110514. }
  110515. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  110516. this._attachedCamera.inertialBetaOffset !== 0 ||
  110517. this._attachedCamera.inertialRadiusOffset !== 0 ||
  110518. this._attachedCamera.inertialPanningX !== 0 ||
  110519. this._attachedCamera.inertialPanningY !== 0 ||
  110520. this._isPointerDown;
  110521. };
  110522. return AutoRotationBehavior;
  110523. }());
  110524. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  110525. })(BABYLON || (BABYLON = {}));
  110526. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  110527. var BABYLON;
  110528. (function (BABYLON) {
  110529. var NullEngineOptions = /** @class */ (function () {
  110530. function NullEngineOptions() {
  110531. this.renderWidth = 512;
  110532. this.renderHeight = 256;
  110533. this.textureSize = 512;
  110534. this.deterministicLockstep = false;
  110535. this.lockstepMaxSteps = 4;
  110536. }
  110537. return NullEngineOptions;
  110538. }());
  110539. BABYLON.NullEngineOptions = NullEngineOptions;
  110540. /**
  110541. * The null engine class provides support for headless version of babylon.js.
  110542. * This can be used in server side scenario or for testing purposes
  110543. */
  110544. var NullEngine = /** @class */ (function (_super) {
  110545. __extends(NullEngine, _super);
  110546. function NullEngine(options) {
  110547. if (options === void 0) { options = new NullEngineOptions(); }
  110548. var _this = _super.call(this, null) || this;
  110549. if (options.deterministicLockstep === undefined) {
  110550. options.deterministicLockstep = false;
  110551. }
  110552. if (options.lockstepMaxSteps === undefined) {
  110553. options.lockstepMaxSteps = 4;
  110554. }
  110555. _this._options = options;
  110556. // Init caps
  110557. // We consider we are on a webgl1 capable device
  110558. _this._caps = new BABYLON.EngineCapabilities();
  110559. _this._caps.maxTexturesImageUnits = 16;
  110560. _this._caps.maxVertexTextureImageUnits = 16;
  110561. _this._caps.maxTextureSize = 512;
  110562. _this._caps.maxCubemapTextureSize = 512;
  110563. _this._caps.maxRenderTextureSize = 512;
  110564. _this._caps.maxVertexAttribs = 16;
  110565. _this._caps.maxVaryingVectors = 16;
  110566. _this._caps.maxFragmentUniformVectors = 16;
  110567. _this._caps.maxVertexUniformVectors = 16;
  110568. // Extensions
  110569. _this._caps.standardDerivatives = false;
  110570. _this._caps.astc = null;
  110571. _this._caps.s3tc = null;
  110572. _this._caps.pvrtc = null;
  110573. _this._caps.etc1 = null;
  110574. _this._caps.etc2 = null;
  110575. _this._caps.textureAnisotropicFilterExtension = null;
  110576. _this._caps.maxAnisotropy = 0;
  110577. _this._caps.uintIndices = false;
  110578. _this._caps.fragmentDepthSupported = false;
  110579. _this._caps.highPrecisionShaderSupported = true;
  110580. _this._caps.colorBufferFloat = false;
  110581. _this._caps.textureFloat = false;
  110582. _this._caps.textureFloatLinearFiltering = false;
  110583. _this._caps.textureFloatRender = false;
  110584. _this._caps.textureHalfFloat = false;
  110585. _this._caps.textureHalfFloatLinearFiltering = false;
  110586. _this._caps.textureHalfFloatRender = false;
  110587. _this._caps.textureLOD = false;
  110588. _this._caps.drawBuffersExtension = false;
  110589. _this._caps.depthTextureExtension = false;
  110590. _this._caps.vertexArrayObject = false;
  110591. _this._caps.instancedArrays = false;
  110592. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  110593. // Wrappers
  110594. if (typeof URL === "undefined") {
  110595. URL = {
  110596. createObjectURL: function () { },
  110597. revokeObjectURL: function () { }
  110598. };
  110599. }
  110600. if (typeof Blob === "undefined") {
  110601. Blob = function () { };
  110602. }
  110603. return _this;
  110604. }
  110605. NullEngine.prototype.isDeterministicLockStep = function () {
  110606. return this._options.deterministicLockstep;
  110607. };
  110608. NullEngine.prototype.getLockstepMaxSteps = function () {
  110609. return this._options.lockstepMaxSteps;
  110610. };
  110611. NullEngine.prototype.getHardwareScalingLevel = function () {
  110612. return 1.0;
  110613. };
  110614. NullEngine.prototype.createVertexBuffer = function (vertices) {
  110615. return {
  110616. capacity: 0,
  110617. references: 1,
  110618. is32Bits: false
  110619. };
  110620. };
  110621. NullEngine.prototype.createIndexBuffer = function (indices) {
  110622. return {
  110623. capacity: 0,
  110624. references: 1,
  110625. is32Bits: false
  110626. };
  110627. };
  110628. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  110629. if (stencil === void 0) { stencil = false; }
  110630. };
  110631. NullEngine.prototype.getRenderWidth = function (useScreen) {
  110632. if (useScreen === void 0) { useScreen = false; }
  110633. if (!useScreen && this._currentRenderTarget) {
  110634. return this._currentRenderTarget.width;
  110635. }
  110636. return this._options.renderWidth;
  110637. };
  110638. NullEngine.prototype.getRenderHeight = function (useScreen) {
  110639. if (useScreen === void 0) { useScreen = false; }
  110640. if (!useScreen && this._currentRenderTarget) {
  110641. return this._currentRenderTarget.height;
  110642. }
  110643. return this._options.renderHeight;
  110644. };
  110645. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  110646. this._cachedViewport = viewport;
  110647. };
  110648. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  110649. return {
  110650. transformFeedback: null,
  110651. __SPECTOR_rebuildProgram: null
  110652. };
  110653. };
  110654. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  110655. return [];
  110656. };
  110657. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  110658. return [];
  110659. };
  110660. NullEngine.prototype.bindSamplers = function (effect) {
  110661. this._currentEffect = null;
  110662. };
  110663. NullEngine.prototype.enableEffect = function (effect) {
  110664. this._currentEffect = effect;
  110665. if (effect.onBind) {
  110666. effect.onBind(effect);
  110667. }
  110668. if (effect._onBindObservable) {
  110669. effect._onBindObservable.notifyObservers(effect);
  110670. }
  110671. };
  110672. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  110673. if (zOffset === void 0) { zOffset = 0; }
  110674. if (reverseSide === void 0) { reverseSide = false; }
  110675. };
  110676. NullEngine.prototype.setIntArray = function (uniform, array) {
  110677. };
  110678. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  110679. };
  110680. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  110681. };
  110682. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  110683. };
  110684. NullEngine.prototype.setFloatArray = function (uniform, array) {
  110685. };
  110686. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  110687. };
  110688. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  110689. };
  110690. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  110691. };
  110692. NullEngine.prototype.setArray = function (uniform, array) {
  110693. };
  110694. NullEngine.prototype.setArray2 = function (uniform, array) {
  110695. };
  110696. NullEngine.prototype.setArray3 = function (uniform, array) {
  110697. };
  110698. NullEngine.prototype.setArray4 = function (uniform, array) {
  110699. };
  110700. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  110701. };
  110702. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  110703. };
  110704. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  110705. };
  110706. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  110707. };
  110708. NullEngine.prototype.setFloat = function (uniform, value) {
  110709. };
  110710. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  110711. };
  110712. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  110713. };
  110714. NullEngine.prototype.setBool = function (uniform, bool) {
  110715. };
  110716. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  110717. };
  110718. NullEngine.prototype.setColor3 = function (uniform, color3) {
  110719. };
  110720. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  110721. };
  110722. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  110723. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  110724. if (this._alphaMode === mode) {
  110725. return;
  110726. }
  110727. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  110728. if (!noDepthWriteChange) {
  110729. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  110730. }
  110731. this._alphaMode = mode;
  110732. };
  110733. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  110734. };
  110735. NullEngine.prototype.wipeCaches = function (bruteForce) {
  110736. if (this.preventCacheWipeBetweenFrames) {
  110737. return;
  110738. }
  110739. this.resetTextureCache();
  110740. this._currentEffect = null;
  110741. if (bruteForce) {
  110742. this._currentProgram = null;
  110743. this._stencilState.reset();
  110744. this._depthCullingState.reset();
  110745. this._alphaState.reset();
  110746. }
  110747. this._cachedVertexBuffers = null;
  110748. this._cachedIndexBuffer = null;
  110749. this._cachedEffectForVertexBuffers = null;
  110750. };
  110751. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  110752. };
  110753. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  110754. };
  110755. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  110756. };
  110757. /** @hidden */
  110758. NullEngine.prototype._createTexture = function () {
  110759. return {};
  110760. };
  110761. /** @hidden */
  110762. NullEngine.prototype._releaseTexture = function (texture) {
  110763. };
  110764. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  110765. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110766. if (onLoad === void 0) { onLoad = null; }
  110767. if (onError === void 0) { onError = null; }
  110768. if (buffer === void 0) { buffer = null; }
  110769. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  110770. var url = String(urlArg);
  110771. texture.url = url;
  110772. texture.generateMipMaps = !noMipmap;
  110773. texture.samplingMode = samplingMode;
  110774. texture.invertY = invertY;
  110775. texture.baseWidth = this._options.textureSize;
  110776. texture.baseHeight = this._options.textureSize;
  110777. texture.width = this._options.textureSize;
  110778. texture.height = this._options.textureSize;
  110779. if (format) {
  110780. texture.format = format;
  110781. }
  110782. texture.isReady = true;
  110783. if (onLoad) {
  110784. onLoad();
  110785. }
  110786. this._internalTexturesCache.push(texture);
  110787. return texture;
  110788. };
  110789. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  110790. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  110791. if (options !== undefined && typeof options === "object") {
  110792. fullOptions.generateMipMaps = options.generateMipMaps;
  110793. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  110794. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  110795. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  110796. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  110797. }
  110798. else {
  110799. fullOptions.generateMipMaps = options;
  110800. fullOptions.generateDepthBuffer = true;
  110801. fullOptions.generateStencilBuffer = false;
  110802. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110803. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  110804. }
  110805. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  110806. var width = size.width || size;
  110807. var height = size.height || size;
  110808. texture._depthStencilBuffer = {};
  110809. texture._framebuffer = {};
  110810. texture.baseWidth = width;
  110811. texture.baseHeight = height;
  110812. texture.width = width;
  110813. texture.height = height;
  110814. texture.isReady = true;
  110815. texture.samples = 1;
  110816. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  110817. texture.samplingMode = fullOptions.samplingMode;
  110818. texture.type = fullOptions.type;
  110819. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  110820. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  110821. this._internalTexturesCache.push(texture);
  110822. return texture;
  110823. };
  110824. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  110825. texture.samplingMode = samplingMode;
  110826. };
  110827. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  110828. if (this._currentRenderTarget) {
  110829. this.unBindFramebuffer(this._currentRenderTarget);
  110830. }
  110831. this._currentRenderTarget = texture;
  110832. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  110833. if (this._cachedViewport && !forceFullscreenViewport) {
  110834. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  110835. }
  110836. };
  110837. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  110838. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  110839. this._currentRenderTarget = null;
  110840. if (onBeforeUnbind) {
  110841. if (texture._MSAAFramebuffer) {
  110842. this._currentFramebuffer = texture._framebuffer;
  110843. }
  110844. onBeforeUnbind();
  110845. }
  110846. this._currentFramebuffer = null;
  110847. };
  110848. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  110849. var vbo = {
  110850. capacity: 1,
  110851. references: 1,
  110852. is32Bits: false
  110853. };
  110854. return vbo;
  110855. };
  110856. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  110857. if (premulAlpha === void 0) { premulAlpha = false; }
  110858. };
  110859. /**
  110860. * @hidden
  110861. * Get the current error code of the webGL context
  110862. * @returns the error code
  110863. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  110864. */
  110865. NullEngine.prototype.getError = function () {
  110866. return 0;
  110867. };
  110868. /** @hidden */
  110869. NullEngine.prototype._getUnpackAlignement = function () {
  110870. return 1;
  110871. };
  110872. /** @hidden */
  110873. NullEngine.prototype._unpackFlipY = function (value) {
  110874. };
  110875. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  110876. if (offset === void 0) { offset = 0; }
  110877. };
  110878. /**
  110879. * Updates a dynamic vertex buffer.
  110880. * @param vertexBuffer the vertex buffer to update
  110881. * @param data the data used to update the vertex buffer
  110882. * @param byteOffset the byte offset of the data (optional)
  110883. * @param byteLength the byte length of the data (optional)
  110884. */
  110885. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  110886. };
  110887. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  110888. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  110889. this._boundTexturesCache[this._activeChannel] = texture;
  110890. return true;
  110891. }
  110892. return false;
  110893. };
  110894. /** @hidden */
  110895. NullEngine.prototype._bindTexture = function (channel, texture) {
  110896. if (channel < 0) {
  110897. return;
  110898. }
  110899. this._bindTextureDirectly(0, texture);
  110900. };
  110901. /** @hidden */
  110902. NullEngine.prototype._releaseBuffer = function (buffer) {
  110903. buffer.references--;
  110904. if (buffer.references === 0) {
  110905. return true;
  110906. }
  110907. return false;
  110908. };
  110909. NullEngine.prototype.releaseEffects = function () {
  110910. };
  110911. NullEngine.prototype.displayLoadingUI = function () {
  110912. };
  110913. NullEngine.prototype.hideLoadingUI = function () {
  110914. };
  110915. /** @hidden */
  110916. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  110917. if (faceIndex === void 0) { faceIndex = 0; }
  110918. if (lod === void 0) { lod = 0; }
  110919. };
  110920. /** @hidden */
  110921. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  110922. if (faceIndex === void 0) { faceIndex = 0; }
  110923. if (lod === void 0) { lod = 0; }
  110924. };
  110925. /** @hidden */
  110926. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  110927. if (faceIndex === void 0) { faceIndex = 0; }
  110928. if (lod === void 0) { lod = 0; }
  110929. };
  110930. /** @hidden */
  110931. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  110932. if (faceIndex === void 0) { faceIndex = 0; }
  110933. if (lod === void 0) { lod = 0; }
  110934. };
  110935. return NullEngine;
  110936. }(BABYLON.Engine));
  110937. BABYLON.NullEngine = NullEngine;
  110938. })(BABYLON || (BABYLON = {}));
  110939. //# sourceMappingURL=babylon.nullEngine.js.map
  110940. var BABYLON;
  110941. (function (BABYLON) {
  110942. /**
  110943. * This class can be used to get instrumentation data from a Babylon engine
  110944. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110945. */
  110946. var EngineInstrumentation = /** @class */ (function () {
  110947. /**
  110948. * Instantiates a new engine instrumentation.
  110949. * This class can be used to get instrumentation data from a Babylon engine
  110950. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110951. * @param engine Defines the engine to instrument
  110952. */
  110953. function EngineInstrumentation(
  110954. /**
  110955. * Define the instrumented engine.
  110956. */
  110957. engine) {
  110958. this.engine = engine;
  110959. this._captureGPUFrameTime = false;
  110960. this._gpuFrameTime = new BABYLON.PerfCounter();
  110961. this._captureShaderCompilationTime = false;
  110962. this._shaderCompilationTime = new BABYLON.PerfCounter();
  110963. // Observers
  110964. this._onBeginFrameObserver = null;
  110965. this._onEndFrameObserver = null;
  110966. this._onBeforeShaderCompilationObserver = null;
  110967. this._onAfterShaderCompilationObserver = null;
  110968. }
  110969. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  110970. // Properties
  110971. /**
  110972. * Gets the perf counter used for GPU frame time
  110973. */
  110974. get: function () {
  110975. return this._gpuFrameTime;
  110976. },
  110977. enumerable: true,
  110978. configurable: true
  110979. });
  110980. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  110981. /**
  110982. * Gets the GPU frame time capture status
  110983. */
  110984. get: function () {
  110985. return this._captureGPUFrameTime;
  110986. },
  110987. /**
  110988. * Enable or disable the GPU frame time capture
  110989. */
  110990. set: function (value) {
  110991. var _this = this;
  110992. if (value === this._captureGPUFrameTime) {
  110993. return;
  110994. }
  110995. this._captureGPUFrameTime = value;
  110996. if (value) {
  110997. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  110998. if (!_this._gpuFrameTimeToken) {
  110999. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  111000. }
  111001. });
  111002. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  111003. if (!_this._gpuFrameTimeToken) {
  111004. return;
  111005. }
  111006. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  111007. if (time > -1) {
  111008. _this._gpuFrameTimeToken = null;
  111009. _this._gpuFrameTime.fetchNewFrame();
  111010. _this._gpuFrameTime.addCount(time, true);
  111011. }
  111012. });
  111013. }
  111014. else {
  111015. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111016. this._onBeginFrameObserver = null;
  111017. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111018. this._onEndFrameObserver = null;
  111019. }
  111020. },
  111021. enumerable: true,
  111022. configurable: true
  111023. });
  111024. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  111025. /**
  111026. * Gets the perf counter used for shader compilation time
  111027. */
  111028. get: function () {
  111029. return this._shaderCompilationTime;
  111030. },
  111031. enumerable: true,
  111032. configurable: true
  111033. });
  111034. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  111035. /**
  111036. * Gets the shader compilation time capture status
  111037. */
  111038. get: function () {
  111039. return this._captureShaderCompilationTime;
  111040. },
  111041. /**
  111042. * Enable or disable the shader compilation time capture
  111043. */
  111044. set: function (value) {
  111045. var _this = this;
  111046. if (value === this._captureShaderCompilationTime) {
  111047. return;
  111048. }
  111049. this._captureShaderCompilationTime = value;
  111050. if (value) {
  111051. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  111052. _this._shaderCompilationTime.fetchNewFrame();
  111053. _this._shaderCompilationTime.beginMonitoring();
  111054. });
  111055. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  111056. _this._shaderCompilationTime.endMonitoring();
  111057. });
  111058. }
  111059. else {
  111060. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111061. this._onBeforeShaderCompilationObserver = null;
  111062. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111063. this._onAfterShaderCompilationObserver = null;
  111064. }
  111065. },
  111066. enumerable: true,
  111067. configurable: true
  111068. });
  111069. /**
  111070. * Dispose and release associated resources.
  111071. */
  111072. EngineInstrumentation.prototype.dispose = function () {
  111073. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111074. this._onBeginFrameObserver = null;
  111075. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111076. this._onEndFrameObserver = null;
  111077. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111078. this._onBeforeShaderCompilationObserver = null;
  111079. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111080. this._onAfterShaderCompilationObserver = null;
  111081. this.engine = null;
  111082. };
  111083. return EngineInstrumentation;
  111084. }());
  111085. BABYLON.EngineInstrumentation = EngineInstrumentation;
  111086. })(BABYLON || (BABYLON = {}));
  111087. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  111088. var BABYLON;
  111089. (function (BABYLON) {
  111090. /**
  111091. * This class can be used to get instrumentation data from a Babylon engine
  111092. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111093. */
  111094. var SceneInstrumentation = /** @class */ (function () {
  111095. /**
  111096. * Instantiates a new scene instrumentation.
  111097. * This class can be used to get instrumentation data from a Babylon engine
  111098. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111099. * @param scene Defines the scene to instrument
  111100. */
  111101. function SceneInstrumentation(
  111102. /**
  111103. * Defines the scene to instrument
  111104. */
  111105. scene) {
  111106. var _this = this;
  111107. this.scene = scene;
  111108. this._captureActiveMeshesEvaluationTime = false;
  111109. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  111110. this._captureRenderTargetsRenderTime = false;
  111111. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  111112. this._captureFrameTime = false;
  111113. this._frameTime = new BABYLON.PerfCounter();
  111114. this._captureRenderTime = false;
  111115. this._renderTime = new BABYLON.PerfCounter();
  111116. this._captureInterFrameTime = false;
  111117. this._interFrameTime = new BABYLON.PerfCounter();
  111118. this._captureParticlesRenderTime = false;
  111119. this._particlesRenderTime = new BABYLON.PerfCounter();
  111120. this._captureSpritesRenderTime = false;
  111121. this._spritesRenderTime = new BABYLON.PerfCounter();
  111122. this._capturePhysicsTime = false;
  111123. this._physicsTime = new BABYLON.PerfCounter();
  111124. this._captureAnimationsTime = false;
  111125. this._animationsTime = new BABYLON.PerfCounter();
  111126. this._captureCameraRenderTime = false;
  111127. this._cameraRenderTime = new BABYLON.PerfCounter();
  111128. // Observers
  111129. this._onBeforeActiveMeshesEvaluationObserver = null;
  111130. this._onAfterActiveMeshesEvaluationObserver = null;
  111131. this._onBeforeRenderTargetsRenderObserver = null;
  111132. this._onAfterRenderTargetsRenderObserver = null;
  111133. this._onAfterRenderObserver = null;
  111134. this._onBeforeDrawPhaseObserver = null;
  111135. this._onAfterDrawPhaseObserver = null;
  111136. this._onBeforeAnimationsObserver = null;
  111137. this._onBeforeParticlesRenderingObserver = null;
  111138. this._onAfterParticlesRenderingObserver = null;
  111139. this._onBeforeSpritesRenderingObserver = null;
  111140. this._onAfterSpritesRenderingObserver = null;
  111141. this._onBeforePhysicsObserver = null;
  111142. this._onAfterPhysicsObserver = null;
  111143. this._onAfterAnimationsObserver = null;
  111144. this._onBeforeCameraRenderObserver = null;
  111145. this._onAfterCameraRenderObserver = null;
  111146. // Before render
  111147. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  111148. if (_this._captureActiveMeshesEvaluationTime) {
  111149. _this._activeMeshesEvaluationTime.fetchNewFrame();
  111150. }
  111151. if (_this._captureRenderTargetsRenderTime) {
  111152. _this._renderTargetsRenderTime.fetchNewFrame();
  111153. }
  111154. if (_this._captureFrameTime) {
  111155. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  111156. _this._frameTime.beginMonitoring();
  111157. }
  111158. if (_this._captureInterFrameTime) {
  111159. _this._interFrameTime.endMonitoring();
  111160. }
  111161. if (_this._captureParticlesRenderTime) {
  111162. _this._particlesRenderTime.fetchNewFrame();
  111163. }
  111164. if (_this._captureSpritesRenderTime) {
  111165. _this._spritesRenderTime.fetchNewFrame();
  111166. }
  111167. if (_this._captureAnimationsTime) {
  111168. _this._animationsTime.beginMonitoring();
  111169. }
  111170. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  111171. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  111172. });
  111173. // After render
  111174. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  111175. if (_this._captureFrameTime) {
  111176. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  111177. _this._frameTime.endMonitoring();
  111178. }
  111179. if (_this._captureRenderTime) {
  111180. _this._renderTime.endMonitoring(false);
  111181. }
  111182. if (_this._captureInterFrameTime) {
  111183. _this._interFrameTime.beginMonitoring();
  111184. }
  111185. });
  111186. }
  111187. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  111188. // Properties
  111189. /**
  111190. * Gets the perf counter used for active meshes evaluation time
  111191. */
  111192. get: function () {
  111193. return this._activeMeshesEvaluationTime;
  111194. },
  111195. enumerable: true,
  111196. configurable: true
  111197. });
  111198. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  111199. /**
  111200. * Gets the active meshes evaluation time capture status
  111201. */
  111202. get: function () {
  111203. return this._captureActiveMeshesEvaluationTime;
  111204. },
  111205. /**
  111206. * Enable or disable the active meshes evaluation time capture
  111207. */
  111208. set: function (value) {
  111209. var _this = this;
  111210. if (value === this._captureActiveMeshesEvaluationTime) {
  111211. return;
  111212. }
  111213. this._captureActiveMeshesEvaluationTime = value;
  111214. if (value) {
  111215. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  111216. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  111217. _this._activeMeshesEvaluationTime.beginMonitoring();
  111218. });
  111219. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  111220. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  111221. _this._activeMeshesEvaluationTime.endMonitoring();
  111222. });
  111223. }
  111224. else {
  111225. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  111226. this._onBeforeActiveMeshesEvaluationObserver = null;
  111227. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  111228. this._onAfterActiveMeshesEvaluationObserver = null;
  111229. }
  111230. },
  111231. enumerable: true,
  111232. configurable: true
  111233. });
  111234. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  111235. /**
  111236. * Gets the perf counter used for render targets render time
  111237. */
  111238. get: function () {
  111239. return this._renderTargetsRenderTime;
  111240. },
  111241. enumerable: true,
  111242. configurable: true
  111243. });
  111244. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  111245. /**
  111246. * Gets the render targets render time capture status
  111247. */
  111248. get: function () {
  111249. return this._captureRenderTargetsRenderTime;
  111250. },
  111251. /**
  111252. * Enable or disable the render targets render time capture
  111253. */
  111254. set: function (value) {
  111255. var _this = this;
  111256. if (value === this._captureRenderTargetsRenderTime) {
  111257. return;
  111258. }
  111259. this._captureRenderTargetsRenderTime = value;
  111260. if (value) {
  111261. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  111262. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  111263. _this._renderTargetsRenderTime.beginMonitoring();
  111264. });
  111265. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  111266. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  111267. _this._renderTargetsRenderTime.endMonitoring(false);
  111268. });
  111269. }
  111270. else {
  111271. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  111272. this._onBeforeRenderTargetsRenderObserver = null;
  111273. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  111274. this._onAfterRenderTargetsRenderObserver = null;
  111275. }
  111276. },
  111277. enumerable: true,
  111278. configurable: true
  111279. });
  111280. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  111281. /**
  111282. * Gets the perf counter used for particles render time
  111283. */
  111284. get: function () {
  111285. return this._particlesRenderTime;
  111286. },
  111287. enumerable: true,
  111288. configurable: true
  111289. });
  111290. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  111291. /**
  111292. * Gets the particles render time capture status
  111293. */
  111294. get: function () {
  111295. return this._captureParticlesRenderTime;
  111296. },
  111297. /**
  111298. * Enable or disable the particles render time capture
  111299. */
  111300. set: function (value) {
  111301. var _this = this;
  111302. if (value === this._captureParticlesRenderTime) {
  111303. return;
  111304. }
  111305. this._captureParticlesRenderTime = value;
  111306. if (value) {
  111307. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  111308. BABYLON.Tools.StartPerformanceCounter("Particles");
  111309. _this._particlesRenderTime.beginMonitoring();
  111310. });
  111311. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  111312. BABYLON.Tools.EndPerformanceCounter("Particles");
  111313. _this._particlesRenderTime.endMonitoring(false);
  111314. });
  111315. }
  111316. else {
  111317. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  111318. this._onBeforeParticlesRenderingObserver = null;
  111319. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  111320. this._onAfterParticlesRenderingObserver = null;
  111321. }
  111322. },
  111323. enumerable: true,
  111324. configurable: true
  111325. });
  111326. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  111327. /**
  111328. * Gets the perf counter used for sprites render time
  111329. */
  111330. get: function () {
  111331. return this._spritesRenderTime;
  111332. },
  111333. enumerable: true,
  111334. configurable: true
  111335. });
  111336. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  111337. /**
  111338. * Gets the sprites render time capture status
  111339. */
  111340. get: function () {
  111341. return this._captureSpritesRenderTime;
  111342. },
  111343. /**
  111344. * Enable or disable the sprites render time capture
  111345. */
  111346. set: function (value) {
  111347. var _this = this;
  111348. if (value === this._captureSpritesRenderTime) {
  111349. return;
  111350. }
  111351. this._captureSpritesRenderTime = value;
  111352. if (!this.scene.spriteManagers) {
  111353. return;
  111354. }
  111355. if (value) {
  111356. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  111357. BABYLON.Tools.StartPerformanceCounter("Sprites");
  111358. _this._spritesRenderTime.beginMonitoring();
  111359. });
  111360. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  111361. BABYLON.Tools.EndPerformanceCounter("Sprites");
  111362. _this._spritesRenderTime.endMonitoring(false);
  111363. });
  111364. }
  111365. else {
  111366. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  111367. this._onBeforeSpritesRenderingObserver = null;
  111368. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  111369. this._onAfterSpritesRenderingObserver = null;
  111370. }
  111371. },
  111372. enumerable: true,
  111373. configurable: true
  111374. });
  111375. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  111376. /**
  111377. * Gets the perf counter used for physics time
  111378. */
  111379. get: function () {
  111380. return this._physicsTime;
  111381. },
  111382. enumerable: true,
  111383. configurable: true
  111384. });
  111385. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  111386. /**
  111387. * Gets the physics time capture status
  111388. */
  111389. get: function () {
  111390. return this._capturePhysicsTime;
  111391. },
  111392. /**
  111393. * Enable or disable the physics time capture
  111394. */
  111395. set: function (value) {
  111396. var _this = this;
  111397. if (value === this._capturePhysicsTime) {
  111398. return;
  111399. }
  111400. if (!this.scene.onBeforePhysicsObservable) {
  111401. return;
  111402. }
  111403. this._capturePhysicsTime = value;
  111404. if (value) {
  111405. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  111406. BABYLON.Tools.StartPerformanceCounter("Physics");
  111407. _this._physicsTime.beginMonitoring();
  111408. });
  111409. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  111410. BABYLON.Tools.EndPerformanceCounter("Physics");
  111411. _this._physicsTime.endMonitoring();
  111412. });
  111413. }
  111414. else {
  111415. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  111416. this._onBeforePhysicsObserver = null;
  111417. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  111418. this._onAfterPhysicsObserver = null;
  111419. }
  111420. },
  111421. enumerable: true,
  111422. configurable: true
  111423. });
  111424. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  111425. /**
  111426. * Gets the perf counter used for animations time
  111427. */
  111428. get: function () {
  111429. return this._animationsTime;
  111430. },
  111431. enumerable: true,
  111432. configurable: true
  111433. });
  111434. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  111435. /**
  111436. * Gets the animations time capture status
  111437. */
  111438. get: function () {
  111439. return this._captureAnimationsTime;
  111440. },
  111441. /**
  111442. * Enable or disable the animations time capture
  111443. */
  111444. set: function (value) {
  111445. var _this = this;
  111446. if (value === this._captureAnimationsTime) {
  111447. return;
  111448. }
  111449. this._captureAnimationsTime = value;
  111450. if (value) {
  111451. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  111452. _this._animationsTime.endMonitoring();
  111453. });
  111454. }
  111455. else {
  111456. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  111457. this._onAfterAnimationsObserver = null;
  111458. }
  111459. },
  111460. enumerable: true,
  111461. configurable: true
  111462. });
  111463. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  111464. /**
  111465. * Gets the perf counter used for frame time capture
  111466. */
  111467. get: function () {
  111468. return this._frameTime;
  111469. },
  111470. enumerable: true,
  111471. configurable: true
  111472. });
  111473. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  111474. /**
  111475. * Gets the frame time capture status
  111476. */
  111477. get: function () {
  111478. return this._captureFrameTime;
  111479. },
  111480. /**
  111481. * Enable or disable the frame time capture
  111482. */
  111483. set: function (value) {
  111484. this._captureFrameTime = value;
  111485. },
  111486. enumerable: true,
  111487. configurable: true
  111488. });
  111489. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  111490. /**
  111491. * Gets the perf counter used for inter-frames time capture
  111492. */
  111493. get: function () {
  111494. return this._interFrameTime;
  111495. },
  111496. enumerable: true,
  111497. configurable: true
  111498. });
  111499. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  111500. /**
  111501. * Gets the inter-frames time capture status
  111502. */
  111503. get: function () {
  111504. return this._captureInterFrameTime;
  111505. },
  111506. /**
  111507. * Enable or disable the inter-frames time capture
  111508. */
  111509. set: function (value) {
  111510. this._captureInterFrameTime = value;
  111511. },
  111512. enumerable: true,
  111513. configurable: true
  111514. });
  111515. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  111516. /**
  111517. * Gets the perf counter used for render time capture
  111518. */
  111519. get: function () {
  111520. return this._renderTime;
  111521. },
  111522. enumerable: true,
  111523. configurable: true
  111524. });
  111525. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  111526. /**
  111527. * Gets the render time capture status
  111528. */
  111529. get: function () {
  111530. return this._captureRenderTime;
  111531. },
  111532. /**
  111533. * Enable or disable the render time capture
  111534. */
  111535. set: function (value) {
  111536. var _this = this;
  111537. if (value === this._captureRenderTime) {
  111538. return;
  111539. }
  111540. this._captureRenderTime = value;
  111541. if (value) {
  111542. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  111543. _this._renderTime.beginMonitoring();
  111544. BABYLON.Tools.StartPerformanceCounter("Main render");
  111545. });
  111546. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  111547. _this._renderTime.endMonitoring(false);
  111548. BABYLON.Tools.EndPerformanceCounter("Main render");
  111549. });
  111550. }
  111551. else {
  111552. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  111553. this._onBeforeDrawPhaseObserver = null;
  111554. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  111555. this._onAfterDrawPhaseObserver = null;
  111556. }
  111557. },
  111558. enumerable: true,
  111559. configurable: true
  111560. });
  111561. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  111562. /**
  111563. * Gets the perf counter used for camera render time capture
  111564. */
  111565. get: function () {
  111566. return this._cameraRenderTime;
  111567. },
  111568. enumerable: true,
  111569. configurable: true
  111570. });
  111571. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  111572. /**
  111573. * Gets the camera render time capture status
  111574. */
  111575. get: function () {
  111576. return this._captureCameraRenderTime;
  111577. },
  111578. /**
  111579. * Enable or disable the camera render time capture
  111580. */
  111581. set: function (value) {
  111582. var _this = this;
  111583. if (value === this._captureCameraRenderTime) {
  111584. return;
  111585. }
  111586. this._captureCameraRenderTime = value;
  111587. if (value) {
  111588. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  111589. _this._cameraRenderTime.beginMonitoring();
  111590. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  111591. });
  111592. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  111593. _this._cameraRenderTime.endMonitoring(false);
  111594. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  111595. });
  111596. }
  111597. else {
  111598. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  111599. this._onBeforeCameraRenderObserver = null;
  111600. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  111601. this._onAfterCameraRenderObserver = null;
  111602. }
  111603. },
  111604. enumerable: true,
  111605. configurable: true
  111606. });
  111607. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  111608. /**
  111609. * Gets the perf counter used for draw calls
  111610. */
  111611. get: function () {
  111612. return this.scene.getEngine()._drawCalls;
  111613. },
  111614. enumerable: true,
  111615. configurable: true
  111616. });
  111617. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  111618. /**
  111619. * Gets the perf counter used for texture collisions
  111620. */
  111621. get: function () {
  111622. return this.scene.getEngine()._textureCollisions;
  111623. },
  111624. enumerable: true,
  111625. configurable: true
  111626. });
  111627. /**
  111628. * Dispose and release associated resources.
  111629. */
  111630. SceneInstrumentation.prototype.dispose = function () {
  111631. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  111632. this._onAfterRenderObserver = null;
  111633. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  111634. this._onBeforeActiveMeshesEvaluationObserver = null;
  111635. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  111636. this._onAfterActiveMeshesEvaluationObserver = null;
  111637. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  111638. this._onBeforeRenderTargetsRenderObserver = null;
  111639. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  111640. this._onAfterRenderTargetsRenderObserver = null;
  111641. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  111642. this._onBeforeAnimationsObserver = null;
  111643. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  111644. this._onBeforeParticlesRenderingObserver = null;
  111645. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  111646. this._onAfterParticlesRenderingObserver = null;
  111647. if (this._onBeforeSpritesRenderingObserver) {
  111648. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  111649. this._onBeforeSpritesRenderingObserver = null;
  111650. }
  111651. if (this._onAfterSpritesRenderingObserver) {
  111652. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  111653. this._onAfterSpritesRenderingObserver = null;
  111654. }
  111655. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  111656. this._onBeforeDrawPhaseObserver = null;
  111657. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  111658. this._onAfterDrawPhaseObserver = null;
  111659. if (this._onBeforePhysicsObserver) {
  111660. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  111661. this._onBeforePhysicsObserver = null;
  111662. }
  111663. if (this._onAfterPhysicsObserver) {
  111664. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  111665. this._onAfterPhysicsObserver = null;
  111666. }
  111667. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  111668. this._onAfterAnimationsObserver = null;
  111669. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  111670. this._onBeforeCameraRenderObserver = null;
  111671. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  111672. this._onAfterCameraRenderObserver = null;
  111673. this.scene = null;
  111674. };
  111675. return SceneInstrumentation;
  111676. }());
  111677. BABYLON.SceneInstrumentation = SceneInstrumentation;
  111678. })(BABYLON || (BABYLON = {}));
  111679. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  111680. var BABYLON;
  111681. (function (BABYLON) {
  111682. /**
  111683. * @hidden
  111684. **/
  111685. var _TimeToken = /** @class */ (function () {
  111686. function _TimeToken() {
  111687. this._timeElapsedQueryEnded = false;
  111688. }
  111689. return _TimeToken;
  111690. }());
  111691. BABYLON._TimeToken = _TimeToken;
  111692. })(BABYLON || (BABYLON = {}));
  111693. //# sourceMappingURL=babylon.timeToken.js.map
  111694. var BABYLON;
  111695. (function (BABYLON) {
  111696. /**
  111697. * Background material defines definition.
  111698. * @hidden Mainly internal Use
  111699. */
  111700. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  111701. __extends(BackgroundMaterialDefines, _super);
  111702. /**
  111703. * Constructor of the defines.
  111704. */
  111705. function BackgroundMaterialDefines() {
  111706. var _this = _super.call(this) || this;
  111707. /**
  111708. * True if the diffuse texture is in use.
  111709. */
  111710. _this.DIFFUSE = false;
  111711. /**
  111712. * The direct UV channel to use.
  111713. */
  111714. _this.DIFFUSEDIRECTUV = 0;
  111715. /**
  111716. * True if the diffuse texture is in gamma space.
  111717. */
  111718. _this.GAMMADIFFUSE = false;
  111719. /**
  111720. * True if the diffuse texture has opacity in the alpha channel.
  111721. */
  111722. _this.DIFFUSEHASALPHA = false;
  111723. /**
  111724. * True if you want the material to fade to transparent at grazing angle.
  111725. */
  111726. _this.OPACITYFRESNEL = false;
  111727. /**
  111728. * True if an extra blur needs to be added in the reflection.
  111729. */
  111730. _this.REFLECTIONBLUR = false;
  111731. /**
  111732. * True if you want the material to fade to reflection at grazing angle.
  111733. */
  111734. _this.REFLECTIONFRESNEL = false;
  111735. /**
  111736. * True if you want the material to falloff as far as you move away from the scene center.
  111737. */
  111738. _this.REFLECTIONFALLOFF = false;
  111739. /**
  111740. * False if the current Webgl implementation does not support the texture lod extension.
  111741. */
  111742. _this.TEXTURELODSUPPORT = false;
  111743. /**
  111744. * True to ensure the data are premultiplied.
  111745. */
  111746. _this.PREMULTIPLYALPHA = false;
  111747. /**
  111748. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  111749. */
  111750. _this.USERGBCOLOR = false;
  111751. /**
  111752. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  111753. * stays aligned with the desired configuration.
  111754. */
  111755. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  111756. /**
  111757. * True to add noise in order to reduce the banding effect.
  111758. */
  111759. _this.NOISE = false;
  111760. /**
  111761. * is the reflection texture in BGR color scheme?
  111762. * Mainly used to solve a bug in ios10 video tag
  111763. */
  111764. _this.REFLECTIONBGR = false;
  111765. _this.IMAGEPROCESSING = false;
  111766. _this.VIGNETTE = false;
  111767. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  111768. _this.VIGNETTEBLENDMODEOPAQUE = false;
  111769. _this.TONEMAPPING = false;
  111770. _this.TONEMAPPING_ACES = false;
  111771. _this.CONTRAST = false;
  111772. _this.COLORCURVES = false;
  111773. _this.COLORGRADING = false;
  111774. _this.COLORGRADING3D = false;
  111775. _this.SAMPLER3DGREENDEPTH = false;
  111776. _this.SAMPLER3DBGRMAP = false;
  111777. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  111778. _this.EXPOSURE = false;
  111779. // Reflection.
  111780. _this.REFLECTION = false;
  111781. _this.REFLECTIONMAP_3D = false;
  111782. _this.REFLECTIONMAP_SPHERICAL = false;
  111783. _this.REFLECTIONMAP_PLANAR = false;
  111784. _this.REFLECTIONMAP_CUBIC = false;
  111785. _this.REFLECTIONMAP_PROJECTION = false;
  111786. _this.REFLECTIONMAP_SKYBOX = false;
  111787. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  111788. _this.REFLECTIONMAP_EXPLICIT = false;
  111789. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  111790. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  111791. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  111792. _this.INVERTCUBICMAP = false;
  111793. _this.REFLECTIONMAP_OPPOSITEZ = false;
  111794. _this.LODINREFLECTIONALPHA = false;
  111795. _this.GAMMAREFLECTION = false;
  111796. _this.RGBDREFLECTION = false;
  111797. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  111798. // Default BJS.
  111799. _this.MAINUV1 = false;
  111800. _this.MAINUV2 = false;
  111801. _this.UV1 = false;
  111802. _this.UV2 = false;
  111803. _this.CLIPPLANE = false;
  111804. _this.CLIPPLANE2 = false;
  111805. _this.CLIPPLANE3 = false;
  111806. _this.CLIPPLANE4 = false;
  111807. _this.POINTSIZE = false;
  111808. _this.FOG = false;
  111809. _this.NORMAL = false;
  111810. _this.NUM_BONE_INFLUENCERS = 0;
  111811. _this.BonesPerMesh = 0;
  111812. _this.INSTANCES = false;
  111813. _this.SHADOWFLOAT = false;
  111814. _this.rebuild();
  111815. return _this;
  111816. }
  111817. return BackgroundMaterialDefines;
  111818. }(BABYLON.MaterialDefines));
  111819. /**
  111820. * Background material used to create an efficient environement around your scene.
  111821. */
  111822. var BackgroundMaterial = /** @class */ (function (_super) {
  111823. __extends(BackgroundMaterial, _super);
  111824. /**
  111825. * Instantiates a Background Material in the given scene
  111826. * @param name The friendly name of the material
  111827. * @param scene The scene to add the material to
  111828. */
  111829. function BackgroundMaterial(name, scene) {
  111830. var _this = _super.call(this, name, scene) || this;
  111831. /**
  111832. * Key light Color (multiply against the environement texture)
  111833. */
  111834. _this.primaryColor = BABYLON.Color3.White();
  111835. _this._primaryColorShadowLevel = 0;
  111836. _this._primaryColorHighlightLevel = 0;
  111837. /**
  111838. * Reflection Texture used in the material.
  111839. * Should be author in a specific way for the best result (refer to the documentation).
  111840. */
  111841. _this.reflectionTexture = null;
  111842. /**
  111843. * Reflection Texture level of blur.
  111844. *
  111845. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  111846. * texture twice.
  111847. */
  111848. _this.reflectionBlur = 0;
  111849. /**
  111850. * Diffuse Texture used in the material.
  111851. * Should be author in a specific way for the best result (refer to the documentation).
  111852. */
  111853. _this.diffuseTexture = null;
  111854. _this._shadowLights = null;
  111855. /**
  111856. * Specify the list of lights casting shadow on the material.
  111857. * All scene shadow lights will be included if null.
  111858. */
  111859. _this.shadowLights = null;
  111860. /**
  111861. * Helps adjusting the shadow to a softer level if required.
  111862. * 0 means black shadows and 1 means no shadows.
  111863. */
  111864. _this.shadowLevel = 0;
  111865. /**
  111866. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  111867. * It is usually zero but might be interesting to modify according to your setup.
  111868. */
  111869. _this.sceneCenter = BABYLON.Vector3.Zero();
  111870. /**
  111871. * This helps specifying that the material is falling off to the sky box at grazing angle.
  111872. * This helps ensuring a nice transition when the camera goes under the ground.
  111873. */
  111874. _this.opacityFresnel = true;
  111875. /**
  111876. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  111877. * This helps adding a mirror texture on the ground.
  111878. */
  111879. _this.reflectionFresnel = false;
  111880. /**
  111881. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  111882. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  111883. */
  111884. _this.reflectionFalloffDistance = 0.0;
  111885. /**
  111886. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  111887. */
  111888. _this.reflectionAmount = 1.0;
  111889. /**
  111890. * This specifies the weight of the reflection at grazing angle.
  111891. */
  111892. _this.reflectionReflectance0 = 0.05;
  111893. /**
  111894. * This specifies the weight of the reflection at a perpendicular point of view.
  111895. */
  111896. _this.reflectionReflectance90 = 0.5;
  111897. /**
  111898. * Helps to directly use the maps channels instead of their level.
  111899. */
  111900. _this.useRGBColor = true;
  111901. /**
  111902. * This helps reducing the banding effect that could occur on the background.
  111903. */
  111904. _this.enableNoise = false;
  111905. _this._fovMultiplier = 1.0;
  111906. /**
  111907. * Enable the FOV adjustment feature controlled by fovMultiplier.
  111908. */
  111909. _this.useEquirectangularFOV = false;
  111910. _this._maxSimultaneousLights = 4;
  111911. /**
  111912. * Number of Simultaneous lights allowed on the material.
  111913. */
  111914. _this.maxSimultaneousLights = 4;
  111915. /**
  111916. * Keep track of the image processing observer to allow dispose and replace.
  111917. */
  111918. _this._imageProcessingObserver = null;
  111919. /**
  111920. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  111921. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  111922. */
  111923. _this.switchToBGR = false;
  111924. // Temp values kept as cache in the material.
  111925. _this._renderTargets = new BABYLON.SmartArray(16);
  111926. _this._reflectionControls = BABYLON.Vector4.Zero();
  111927. _this._white = BABYLON.Color3.White();
  111928. _this._primaryShadowColor = BABYLON.Color3.Black();
  111929. _this._primaryHighlightColor = BABYLON.Color3.Black();
  111930. // Setup the default processing configuration to the scene.
  111931. _this._attachImageProcessingConfiguration(null);
  111932. _this.getRenderTargetTextures = function () {
  111933. _this._renderTargets.reset();
  111934. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  111935. _this._renderTargets.push(_this._diffuseTexture);
  111936. }
  111937. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  111938. _this._renderTargets.push(_this._reflectionTexture);
  111939. }
  111940. return _this._renderTargets;
  111941. };
  111942. return _this;
  111943. }
  111944. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  111945. /**
  111946. * Experimental Internal Use Only.
  111947. *
  111948. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  111949. * This acts as a helper to set the primary color to a more "human friendly" value.
  111950. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  111951. * output color as close as possible from the chosen value.
  111952. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  111953. * part of lighting setup.)
  111954. */
  111955. get: function () {
  111956. return this.__perceptualColor;
  111957. },
  111958. set: function (value) {
  111959. this.__perceptualColor = value;
  111960. this._computePrimaryColorFromPerceptualColor();
  111961. this._markAllSubMeshesAsLightsDirty();
  111962. },
  111963. enumerable: true,
  111964. configurable: true
  111965. });
  111966. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  111967. /**
  111968. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  111969. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  111970. */
  111971. get: function () {
  111972. return this._primaryColorShadowLevel;
  111973. },
  111974. set: function (value) {
  111975. this._primaryColorShadowLevel = value;
  111976. this._computePrimaryColors();
  111977. this._markAllSubMeshesAsLightsDirty();
  111978. },
  111979. enumerable: true,
  111980. configurable: true
  111981. });
  111982. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  111983. /**
  111984. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  111985. * The primary color is used at the level chosen to define what the white area would look.
  111986. */
  111987. get: function () {
  111988. return this._primaryColorHighlightLevel;
  111989. },
  111990. set: function (value) {
  111991. this._primaryColorHighlightLevel = value;
  111992. this._computePrimaryColors();
  111993. this._markAllSubMeshesAsLightsDirty();
  111994. },
  111995. enumerable: true,
  111996. configurable: true
  111997. });
  111998. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  111999. /**
  112000. * Sets the reflection reflectance fresnel values according to the default standard
  112001. * empirically know to work well :-)
  112002. */
  112003. set: function (value) {
  112004. var reflectionWeight = value;
  112005. if (reflectionWeight < 0.5) {
  112006. reflectionWeight = reflectionWeight * 2.0;
  112007. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  112008. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  112009. }
  112010. else {
  112011. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  112012. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  112013. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  112014. }
  112015. },
  112016. enumerable: true,
  112017. configurable: true
  112018. });
  112019. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  112020. /**
  112021. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112022. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  112023. * Recommended to be keep at 1.0 except for special cases.
  112024. */
  112025. get: function () {
  112026. return this._fovMultiplier;
  112027. },
  112028. set: function (value) {
  112029. if (isNaN(value)) {
  112030. value = 1.0;
  112031. }
  112032. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  112033. },
  112034. enumerable: true,
  112035. configurable: true
  112036. });
  112037. /**
  112038. * Attaches a new image processing configuration to the PBR Material.
  112039. * @param configuration (if null the scene configuration will be use)
  112040. */
  112041. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  112042. var _this = this;
  112043. if (configuration === this._imageProcessingConfiguration) {
  112044. return;
  112045. }
  112046. // Detaches observer.
  112047. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112048. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112049. }
  112050. // Pick the scene configuration if needed.
  112051. if (!configuration) {
  112052. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  112053. }
  112054. else {
  112055. this._imageProcessingConfiguration = configuration;
  112056. }
  112057. // Attaches observer.
  112058. if (this._imageProcessingConfiguration) {
  112059. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  112060. _this._computePrimaryColorFromPerceptualColor();
  112061. _this._markAllSubMeshesAsImageProcessingDirty();
  112062. });
  112063. }
  112064. };
  112065. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  112066. /**
  112067. * Gets the image processing configuration used either in this material.
  112068. */
  112069. get: function () {
  112070. return this._imageProcessingConfiguration;
  112071. },
  112072. /**
  112073. * Sets the Default image processing configuration used either in the this material.
  112074. *
  112075. * If sets to null, the scene one is in use.
  112076. */
  112077. set: function (value) {
  112078. this._attachImageProcessingConfiguration(value);
  112079. // Ensure the effect will be rebuilt.
  112080. this._markAllSubMeshesAsTexturesDirty();
  112081. },
  112082. enumerable: true,
  112083. configurable: true
  112084. });
  112085. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  112086. /**
  112087. * Gets wether the color curves effect is enabled.
  112088. */
  112089. get: function () {
  112090. return this.imageProcessingConfiguration.colorCurvesEnabled;
  112091. },
  112092. /**
  112093. * Sets wether the color curves effect is enabled.
  112094. */
  112095. set: function (value) {
  112096. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  112097. },
  112098. enumerable: true,
  112099. configurable: true
  112100. });
  112101. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  112102. /**
  112103. * Gets wether the color grading effect is enabled.
  112104. */
  112105. get: function () {
  112106. return this.imageProcessingConfiguration.colorGradingEnabled;
  112107. },
  112108. /**
  112109. * Gets wether the color grading effect is enabled.
  112110. */
  112111. set: function (value) {
  112112. this.imageProcessingConfiguration.colorGradingEnabled = value;
  112113. },
  112114. enumerable: true,
  112115. configurable: true
  112116. });
  112117. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  112118. /**
  112119. * Gets wether tonemapping is enabled or not.
  112120. */
  112121. get: function () {
  112122. return this._imageProcessingConfiguration.toneMappingEnabled;
  112123. },
  112124. /**
  112125. * Sets wether tonemapping is enabled or not
  112126. */
  112127. set: function (value) {
  112128. this._imageProcessingConfiguration.toneMappingEnabled = value;
  112129. },
  112130. enumerable: true,
  112131. configurable: true
  112132. });
  112133. ;
  112134. ;
  112135. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  112136. /**
  112137. * The camera exposure used on this material.
  112138. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  112139. * This corresponds to a photographic exposure.
  112140. */
  112141. get: function () {
  112142. return this._imageProcessingConfiguration.exposure;
  112143. },
  112144. /**
  112145. * The camera exposure used on this material.
  112146. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  112147. * This corresponds to a photographic exposure.
  112148. */
  112149. set: function (value) {
  112150. this._imageProcessingConfiguration.exposure = value;
  112151. },
  112152. enumerable: true,
  112153. configurable: true
  112154. });
  112155. ;
  112156. ;
  112157. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  112158. /**
  112159. * Gets The camera contrast used on this material.
  112160. */
  112161. get: function () {
  112162. return this._imageProcessingConfiguration.contrast;
  112163. },
  112164. /**
  112165. * Sets The camera contrast used on this material.
  112166. */
  112167. set: function (value) {
  112168. this._imageProcessingConfiguration.contrast = value;
  112169. },
  112170. enumerable: true,
  112171. configurable: true
  112172. });
  112173. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  112174. /**
  112175. * Gets the Color Grading 2D Lookup Texture.
  112176. */
  112177. get: function () {
  112178. return this._imageProcessingConfiguration.colorGradingTexture;
  112179. },
  112180. /**
  112181. * Sets the Color Grading 2D Lookup Texture.
  112182. */
  112183. set: function (value) {
  112184. this.imageProcessingConfiguration.colorGradingTexture = value;
  112185. },
  112186. enumerable: true,
  112187. configurable: true
  112188. });
  112189. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  112190. /**
  112191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  112192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  112193. * 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;
  112194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  112195. */
  112196. get: function () {
  112197. return this.imageProcessingConfiguration.colorCurves;
  112198. },
  112199. /**
  112200. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  112201. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  112202. * 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;
  112203. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  112204. */
  112205. set: function (value) {
  112206. this.imageProcessingConfiguration.colorCurves = value;
  112207. },
  112208. enumerable: true,
  112209. configurable: true
  112210. });
  112211. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  112212. /**
  112213. * Gets a boolean indicating that current material needs to register RTT
  112214. */
  112215. get: function () {
  112216. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  112217. return true;
  112218. }
  112219. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  112220. return true;
  112221. }
  112222. return false;
  112223. },
  112224. enumerable: true,
  112225. configurable: true
  112226. });
  112227. /**
  112228. * The entire material has been created in order to prevent overdraw.
  112229. * @returns false
  112230. */
  112231. BackgroundMaterial.prototype.needAlphaTesting = function () {
  112232. return true;
  112233. };
  112234. /**
  112235. * The entire material has been created in order to prevent overdraw.
  112236. * @returns true if blending is enable
  112237. */
  112238. BackgroundMaterial.prototype.needAlphaBlending = function () {
  112239. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  112240. };
  112241. /**
  112242. * Checks wether the material is ready to be rendered for a given mesh.
  112243. * @param mesh The mesh to render
  112244. * @param subMesh The submesh to check against
  112245. * @param useInstances Specify wether or not the material is used with instances
  112246. * @returns true if all the dependencies are ready (Textures, Effects...)
  112247. */
  112248. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  112249. var _this = this;
  112250. if (useInstances === void 0) { useInstances = false; }
  112251. if (subMesh.effect && this.isFrozen) {
  112252. if (this._wasPreviouslyReady) {
  112253. return true;
  112254. }
  112255. }
  112256. if (!subMesh._materialDefines) {
  112257. subMesh._materialDefines = new BackgroundMaterialDefines();
  112258. }
  112259. var scene = this.getScene();
  112260. var defines = subMesh._materialDefines;
  112261. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  112262. if (defines._renderId === scene.getRenderId()) {
  112263. return true;
  112264. }
  112265. }
  112266. var engine = scene.getEngine();
  112267. // Lights
  112268. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  112269. defines._needNormals = true;
  112270. // Textures
  112271. if (defines._areTexturesDirty) {
  112272. defines._needUVs = false;
  112273. if (scene.texturesEnabled) {
  112274. if (scene.getEngine().getCaps().textureLOD) {
  112275. defines.TEXTURELODSUPPORT = true;
  112276. }
  112277. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  112278. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  112279. return false;
  112280. }
  112281. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  112282. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  112283. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  112284. defines.OPACITYFRESNEL = this._opacityFresnel;
  112285. }
  112286. else {
  112287. defines.DIFFUSE = false;
  112288. defines.DIFFUSEHASALPHA = false;
  112289. defines.GAMMADIFFUSE = false;
  112290. defines.OPACITYFRESNEL = false;
  112291. }
  112292. var reflectionTexture = this._reflectionTexture;
  112293. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  112294. if (!reflectionTexture.isReadyOrNotBlocking()) {
  112295. return false;
  112296. }
  112297. defines.REFLECTION = true;
  112298. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  112299. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  112300. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  112301. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  112302. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  112303. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  112304. defines.REFLECTIONBGR = this.switchToBGR;
  112305. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  112306. defines.INVERTCUBICMAP = true;
  112307. }
  112308. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  112309. switch (reflectionTexture.coordinatesMode) {
  112310. case BABYLON.Texture.EXPLICIT_MODE:
  112311. defines.REFLECTIONMAP_EXPLICIT = true;
  112312. break;
  112313. case BABYLON.Texture.PLANAR_MODE:
  112314. defines.REFLECTIONMAP_PLANAR = true;
  112315. break;
  112316. case BABYLON.Texture.PROJECTION_MODE:
  112317. defines.REFLECTIONMAP_PROJECTION = true;
  112318. break;
  112319. case BABYLON.Texture.SKYBOX_MODE:
  112320. defines.REFLECTIONMAP_SKYBOX = true;
  112321. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  112322. break;
  112323. case BABYLON.Texture.SPHERICAL_MODE:
  112324. defines.REFLECTIONMAP_SPHERICAL = true;
  112325. break;
  112326. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  112327. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  112328. break;
  112329. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  112330. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  112331. break;
  112332. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  112333. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  112334. break;
  112335. case BABYLON.Texture.CUBIC_MODE:
  112336. case BABYLON.Texture.INVCUBIC_MODE:
  112337. default:
  112338. defines.REFLECTIONMAP_CUBIC = true;
  112339. break;
  112340. }
  112341. if (this.reflectionFresnel) {
  112342. defines.REFLECTIONFRESNEL = true;
  112343. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  112344. this._reflectionControls.x = this.reflectionAmount;
  112345. this._reflectionControls.y = this.reflectionReflectance0;
  112346. this._reflectionControls.z = this.reflectionReflectance90;
  112347. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  112348. }
  112349. else {
  112350. defines.REFLECTIONFRESNEL = false;
  112351. defines.REFLECTIONFALLOFF = false;
  112352. }
  112353. }
  112354. else {
  112355. defines.REFLECTION = false;
  112356. defines.REFLECTIONFRESNEL = false;
  112357. defines.REFLECTIONFALLOFF = false;
  112358. defines.REFLECTIONBLUR = false;
  112359. defines.REFLECTIONMAP_3D = false;
  112360. defines.REFLECTIONMAP_SPHERICAL = false;
  112361. defines.REFLECTIONMAP_PLANAR = false;
  112362. defines.REFLECTIONMAP_CUBIC = false;
  112363. defines.REFLECTIONMAP_PROJECTION = false;
  112364. defines.REFLECTIONMAP_SKYBOX = false;
  112365. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  112366. defines.REFLECTIONMAP_EXPLICIT = false;
  112367. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  112368. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  112369. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  112370. defines.INVERTCUBICMAP = false;
  112371. defines.REFLECTIONMAP_OPPOSITEZ = false;
  112372. defines.LODINREFLECTIONALPHA = false;
  112373. defines.GAMMAREFLECTION = false;
  112374. defines.RGBDREFLECTION = false;
  112375. }
  112376. }
  112377. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  112378. defines.USERGBCOLOR = this._useRGBColor;
  112379. defines.NOISE = this._enableNoise;
  112380. }
  112381. if (defines._areLightsDirty) {
  112382. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  112383. }
  112384. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  112385. if (!this._imageProcessingConfiguration.isReady()) {
  112386. return false;
  112387. }
  112388. this._imageProcessingConfiguration.prepareDefines(defines);
  112389. }
  112390. // Misc.
  112391. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  112392. // Values that need to be evaluated on every frame
  112393. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  112394. // Attribs
  112395. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  112396. if (mesh) {
  112397. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  112398. mesh.createNormals(true);
  112399. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  112400. }
  112401. }
  112402. }
  112403. // Get correct effect
  112404. if (defines.isDirty) {
  112405. defines.markAsProcessed();
  112406. scene.resetCachedMaterial();
  112407. // Fallbacks
  112408. var fallbacks = new BABYLON.EffectFallbacks();
  112409. if (defines.FOG) {
  112410. fallbacks.addFallback(0, "FOG");
  112411. }
  112412. if (defines.POINTSIZE) {
  112413. fallbacks.addFallback(1, "POINTSIZE");
  112414. }
  112415. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  112416. if (defines.NUM_BONE_INFLUENCERS > 0) {
  112417. fallbacks.addCPUSkinningFallback(0, mesh);
  112418. }
  112419. //Attributes
  112420. var attribs = [BABYLON.VertexBuffer.PositionKind];
  112421. if (defines.NORMAL) {
  112422. attribs.push(BABYLON.VertexBuffer.NormalKind);
  112423. }
  112424. if (defines.UV1) {
  112425. attribs.push(BABYLON.VertexBuffer.UVKind);
  112426. }
  112427. if (defines.UV2) {
  112428. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  112429. }
  112430. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  112431. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  112432. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  112433. "vFogInfos", "vFogColor", "pointSize",
  112434. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  112435. "vPrimaryColor", "vPrimaryColorShadow",
  112436. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  112437. "shadowLevel", "alpha",
  112438. "vBackgroundCenter", "vReflectionControl",
  112439. "vDiffuseInfos", "diffuseMatrix",
  112440. ];
  112441. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  112442. var uniformBuffers = ["Material", "Scene"];
  112443. if (BABYLON.ImageProcessingConfiguration) {
  112444. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  112445. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  112446. }
  112447. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  112448. uniformsNames: uniforms,
  112449. uniformBuffersNames: uniformBuffers,
  112450. samplers: samplers,
  112451. defines: defines,
  112452. maxSimultaneousLights: this._maxSimultaneousLights
  112453. });
  112454. var onCompiled = function (effect) {
  112455. if (_this.onCompiled) {
  112456. _this.onCompiled(effect);
  112457. }
  112458. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  112459. };
  112460. var join = defines.toString();
  112461. subMesh.setEffect(scene.getEngine().createEffect("background", {
  112462. attributes: attribs,
  112463. uniformsNames: uniforms,
  112464. uniformBuffersNames: uniformBuffers,
  112465. samplers: samplers,
  112466. defines: join,
  112467. fallbacks: fallbacks,
  112468. onCompiled: onCompiled,
  112469. onError: this.onError,
  112470. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  112471. }, engine), defines);
  112472. this.buildUniformLayout();
  112473. }
  112474. if (!subMesh.effect || !subMesh.effect.isReady()) {
  112475. return false;
  112476. }
  112477. defines._renderId = scene.getRenderId();
  112478. this._wasPreviouslyReady = true;
  112479. return true;
  112480. };
  112481. /**
  112482. * Compute the primary color according to the chosen perceptual color.
  112483. */
  112484. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  112485. if (!this.__perceptualColor) {
  112486. return;
  112487. }
  112488. this._primaryColor.copyFrom(this.__perceptualColor);
  112489. // Revert gamma space.
  112490. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  112491. // Revert image processing configuration.
  112492. if (this._imageProcessingConfiguration) {
  112493. // Revert Exposure.
  112494. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  112495. }
  112496. this._computePrimaryColors();
  112497. };
  112498. /**
  112499. * Compute the highlights and shadow colors according to their chosen levels.
  112500. */
  112501. BackgroundMaterial.prototype._computePrimaryColors = function () {
  112502. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  112503. return;
  112504. }
  112505. // Find the highlight color based on the configuration.
  112506. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  112507. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  112508. // Find the shadow color based on the configuration.
  112509. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  112510. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  112511. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  112512. };
  112513. /**
  112514. * Build the uniform buffer used in the material.
  112515. */
  112516. BackgroundMaterial.prototype.buildUniformLayout = function () {
  112517. // Order is important !
  112518. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  112519. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  112520. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  112521. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  112522. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  112523. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  112524. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  112525. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  112526. this._uniformBuffer.addUniform("pointSize", 1);
  112527. this._uniformBuffer.addUniform("shadowLevel", 1);
  112528. this._uniformBuffer.addUniform("alpha", 1);
  112529. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  112530. this._uniformBuffer.addUniform("vReflectionControl", 4);
  112531. this._uniformBuffer.create();
  112532. };
  112533. /**
  112534. * Unbind the material.
  112535. */
  112536. BackgroundMaterial.prototype.unbind = function () {
  112537. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  112538. this._uniformBuffer.setTexture("diffuseSampler", null);
  112539. }
  112540. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  112541. this._uniformBuffer.setTexture("reflectionSampler", null);
  112542. }
  112543. _super.prototype.unbind.call(this);
  112544. };
  112545. /**
  112546. * Bind only the world matrix to the material.
  112547. * @param world The world matrix to bind.
  112548. */
  112549. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  112550. this._activeEffect.setMatrix("world", world);
  112551. };
  112552. /**
  112553. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  112554. * @param world The world matrix to bind.
  112555. * @param subMesh The submesh to bind for.
  112556. */
  112557. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  112558. var scene = this.getScene();
  112559. var defines = subMesh._materialDefines;
  112560. if (!defines) {
  112561. return;
  112562. }
  112563. var effect = subMesh.effect;
  112564. if (!effect) {
  112565. return;
  112566. }
  112567. this._activeEffect = effect;
  112568. // Matrices
  112569. this.bindOnlyWorldMatrix(world);
  112570. // Bones
  112571. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  112572. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  112573. if (mustRebind) {
  112574. this._uniformBuffer.bindToEffect(effect, "Material");
  112575. this.bindViewProjection(effect);
  112576. var reflectionTexture = this._reflectionTexture;
  112577. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  112578. // Texture uniforms
  112579. if (scene.texturesEnabled) {
  112580. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  112581. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  112582. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  112583. }
  112584. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  112585. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  112586. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  112587. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  112588. }
  112589. }
  112590. if (this.shadowLevel > 0) {
  112591. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  112592. }
  112593. this._uniformBuffer.updateFloat("alpha", this.alpha);
  112594. // Point size
  112595. if (this.pointsCloud) {
  112596. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  112597. }
  112598. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  112599. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  112600. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  112601. }
  112602. else {
  112603. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  112604. }
  112605. }
  112606. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  112607. // Textures
  112608. if (scene.texturesEnabled) {
  112609. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  112610. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  112611. }
  112612. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  112613. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  112614. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  112615. }
  112616. else if (!defines.REFLECTIONBLUR) {
  112617. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  112618. }
  112619. else {
  112620. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  112621. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  112622. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  112623. }
  112624. if (defines.REFLECTIONFRESNEL) {
  112625. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  112626. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  112627. }
  112628. }
  112629. }
  112630. // Clip plane
  112631. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  112632. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  112633. }
  112634. if (mustRebind || !this.isFrozen) {
  112635. if (scene.lightsEnabled) {
  112636. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  112637. }
  112638. // View
  112639. this.bindView(effect);
  112640. // Fog
  112641. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  112642. // image processing
  112643. if (this._imageProcessingConfiguration) {
  112644. this._imageProcessingConfiguration.bind(this._activeEffect);
  112645. }
  112646. }
  112647. this._uniformBuffer.update();
  112648. this._afterBind(mesh, this._activeEffect);
  112649. };
  112650. /**
  112651. * Dispose the material.
  112652. * @param forceDisposeEffect Force disposal of the associated effect.
  112653. * @param forceDisposeTextures Force disposal of the associated textures.
  112654. */
  112655. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  112656. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  112657. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  112658. if (forceDisposeTextures) {
  112659. if (this.diffuseTexture) {
  112660. this.diffuseTexture.dispose();
  112661. }
  112662. if (this.reflectionTexture) {
  112663. this.reflectionTexture.dispose();
  112664. }
  112665. }
  112666. this._renderTargets.dispose();
  112667. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112668. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112669. }
  112670. _super.prototype.dispose.call(this, forceDisposeEffect);
  112671. };
  112672. /**
  112673. * Clones the material.
  112674. * @param name The cloned name.
  112675. * @returns The cloned material.
  112676. */
  112677. BackgroundMaterial.prototype.clone = function (name) {
  112678. var _this = this;
  112679. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  112680. };
  112681. /**
  112682. * Serializes the current material to its JSON representation.
  112683. * @returns The JSON representation.
  112684. */
  112685. BackgroundMaterial.prototype.serialize = function () {
  112686. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112687. serializationObject.customType = "BABYLON.BackgroundMaterial";
  112688. return serializationObject;
  112689. };
  112690. /**
  112691. * Gets the class name of the material
  112692. * @returns "BackgroundMaterial"
  112693. */
  112694. BackgroundMaterial.prototype.getClassName = function () {
  112695. return "BackgroundMaterial";
  112696. };
  112697. /**
  112698. * Parse a JSON input to create back a background material.
  112699. * @param source The JSON data to parse
  112700. * @param scene The scene to create the parsed material in
  112701. * @param rootUrl The root url of the assets the material depends upon
  112702. * @returns the instantiated BackgroundMaterial.
  112703. */
  112704. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  112705. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  112706. };
  112707. /**
  112708. * Standard reflectance value at parallel view angle.
  112709. */
  112710. BackgroundMaterial.StandardReflectance0 = 0.05;
  112711. /**
  112712. * Standard reflectance value at grazing angle.
  112713. */
  112714. BackgroundMaterial.StandardReflectance90 = 0.5;
  112715. __decorate([
  112716. BABYLON.serializeAsColor3()
  112717. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  112718. __decorate([
  112719. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  112720. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  112721. __decorate([
  112722. BABYLON.serializeAsColor3()
  112723. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  112724. __decorate([
  112725. BABYLON.serialize()
  112726. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  112727. __decorate([
  112728. BABYLON.serialize()
  112729. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  112730. __decorate([
  112731. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  112732. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  112733. __decorate([
  112734. BABYLON.serializeAsTexture()
  112735. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  112736. __decorate([
  112737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112738. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  112739. __decorate([
  112740. BABYLON.serialize()
  112741. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  112742. __decorate([
  112743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112744. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  112745. __decorate([
  112746. BABYLON.serializeAsTexture()
  112747. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  112748. __decorate([
  112749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112750. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  112751. __decorate([
  112752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112753. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  112754. __decorate([
  112755. BABYLON.serialize()
  112756. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  112757. __decorate([
  112758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112759. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  112760. __decorate([
  112761. BABYLON.serializeAsVector3()
  112762. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  112763. __decorate([
  112764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112765. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  112766. __decorate([
  112767. BABYLON.serialize()
  112768. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  112769. __decorate([
  112770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112771. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  112772. __decorate([
  112773. BABYLON.serialize()
  112774. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  112775. __decorate([
  112776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112777. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  112778. __decorate([
  112779. BABYLON.serialize()
  112780. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  112781. __decorate([
  112782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112783. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  112784. __decorate([
  112785. BABYLON.serialize()
  112786. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  112787. __decorate([
  112788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112789. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  112790. __decorate([
  112791. BABYLON.serialize()
  112792. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  112793. __decorate([
  112794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112795. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  112796. __decorate([
  112797. BABYLON.serialize()
  112798. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  112799. __decorate([
  112800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112801. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  112802. __decorate([
  112803. BABYLON.serialize()
  112804. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  112805. __decorate([
  112806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112807. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  112808. __decorate([
  112809. BABYLON.serialize()
  112810. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  112811. __decorate([
  112812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112813. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  112814. __decorate([
  112815. BABYLON.serialize()
  112816. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  112817. __decorate([
  112818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112819. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  112820. __decorate([
  112821. BABYLON.serializeAsImageProcessingConfiguration()
  112822. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  112823. return BackgroundMaterial;
  112824. }(BABYLON.PushMaterial));
  112825. BABYLON.BackgroundMaterial = BackgroundMaterial;
  112826. })(BABYLON || (BABYLON = {}));
  112827. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  112828. var __assign = (this && this.__assign) || function () {
  112829. __assign = Object.assign || function(t) {
  112830. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112831. s = arguments[i];
  112832. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112833. t[p] = s[p];
  112834. }
  112835. return t;
  112836. };
  112837. return __assign.apply(this, arguments);
  112838. };
  112839. var BABYLON;
  112840. (function (BABYLON) {
  112841. /**
  112842. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  112843. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  112844. * It also helps with the default setup of your imageProcessing configuration.
  112845. */
  112846. var EnvironmentHelper = /** @class */ (function () {
  112847. /**
  112848. * constructor
  112849. * @param options
  112850. * @param scene The scene to add the material to
  112851. */
  112852. function EnvironmentHelper(options, scene) {
  112853. var _this = this;
  112854. this._errorHandler = function (message, exception) {
  112855. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  112856. };
  112857. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  112858. this._scene = scene;
  112859. this.onErrorObservable = new BABYLON.Observable();
  112860. this._setupBackground();
  112861. this._setupImageProcessing();
  112862. }
  112863. /**
  112864. * Creates the default options for the helper.
  112865. */
  112866. EnvironmentHelper._getDefaultOptions = function () {
  112867. return {
  112868. createGround: true,
  112869. groundSize: 15,
  112870. groundTexture: this._groundTextureCDNUrl,
  112871. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112872. groundOpacity: 0.9,
  112873. enableGroundShadow: true,
  112874. groundShadowLevel: 0.5,
  112875. enableGroundMirror: false,
  112876. groundMirrorSizeRatio: 0.3,
  112877. groundMirrorBlurKernel: 64,
  112878. groundMirrorAmount: 1,
  112879. groundMirrorFresnelWeight: 1,
  112880. groundMirrorFallOffDistance: 0,
  112881. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  112882. groundYBias: 0.00001,
  112883. createSkybox: true,
  112884. skyboxSize: 20,
  112885. skyboxTexture: this._skyboxTextureCDNUrl,
  112886. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112887. backgroundYRotation: 0,
  112888. sizeAuto: true,
  112889. rootPosition: BABYLON.Vector3.Zero(),
  112890. setupImageProcessing: true,
  112891. environmentTexture: this._environmentTextureCDNUrl,
  112892. cameraExposure: 0.8,
  112893. cameraContrast: 1.2,
  112894. toneMappingEnabled: true,
  112895. };
  112896. };
  112897. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  112898. /**
  112899. * Gets the root mesh created by the helper.
  112900. */
  112901. get: function () {
  112902. return this._rootMesh;
  112903. },
  112904. enumerable: true,
  112905. configurable: true
  112906. });
  112907. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  112908. /**
  112909. * Gets the skybox created by the helper.
  112910. */
  112911. get: function () {
  112912. return this._skybox;
  112913. },
  112914. enumerable: true,
  112915. configurable: true
  112916. });
  112917. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  112918. /**
  112919. * Gets the skybox texture created by the helper.
  112920. */
  112921. get: function () {
  112922. return this._skyboxTexture;
  112923. },
  112924. enumerable: true,
  112925. configurable: true
  112926. });
  112927. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  112928. /**
  112929. * Gets the skybox material created by the helper.
  112930. */
  112931. get: function () {
  112932. return this._skyboxMaterial;
  112933. },
  112934. enumerable: true,
  112935. configurable: true
  112936. });
  112937. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  112938. /**
  112939. * Gets the ground mesh created by the helper.
  112940. */
  112941. get: function () {
  112942. return this._ground;
  112943. },
  112944. enumerable: true,
  112945. configurable: true
  112946. });
  112947. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  112948. /**
  112949. * Gets the ground texture created by the helper.
  112950. */
  112951. get: function () {
  112952. return this._groundTexture;
  112953. },
  112954. enumerable: true,
  112955. configurable: true
  112956. });
  112957. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  112958. /**
  112959. * Gets the ground mirror created by the helper.
  112960. */
  112961. get: function () {
  112962. return this._groundMirror;
  112963. },
  112964. enumerable: true,
  112965. configurable: true
  112966. });
  112967. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  112968. /**
  112969. * Gets the ground mirror render list to helps pushing the meshes
  112970. * you wish in the ground reflection.
  112971. */
  112972. get: function () {
  112973. if (this._groundMirror) {
  112974. return this._groundMirror.renderList;
  112975. }
  112976. return null;
  112977. },
  112978. enumerable: true,
  112979. configurable: true
  112980. });
  112981. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  112982. /**
  112983. * Gets the ground material created by the helper.
  112984. */
  112985. get: function () {
  112986. return this._groundMaterial;
  112987. },
  112988. enumerable: true,
  112989. configurable: true
  112990. });
  112991. /**
  112992. * Updates the background according to the new options
  112993. * @param options
  112994. */
  112995. EnvironmentHelper.prototype.updateOptions = function (options) {
  112996. var newOptions = __assign({}, this._options, options);
  112997. if (this._ground && !newOptions.createGround) {
  112998. this._ground.dispose();
  112999. this._ground = null;
  113000. }
  113001. if (this._groundMaterial && !newOptions.createGround) {
  113002. this._groundMaterial.dispose();
  113003. this._groundMaterial = null;
  113004. }
  113005. if (this._groundTexture) {
  113006. if (this._options.groundTexture != newOptions.groundTexture) {
  113007. this._groundTexture.dispose();
  113008. this._groundTexture = null;
  113009. }
  113010. }
  113011. if (this._skybox && !newOptions.createSkybox) {
  113012. this._skybox.dispose();
  113013. this._skybox = null;
  113014. }
  113015. if (this._skyboxMaterial && !newOptions.createSkybox) {
  113016. this._skyboxMaterial.dispose();
  113017. this._skyboxMaterial = null;
  113018. }
  113019. if (this._skyboxTexture) {
  113020. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  113021. this._skyboxTexture.dispose();
  113022. this._skyboxTexture = null;
  113023. }
  113024. }
  113025. if (this._groundMirror && !newOptions.enableGroundMirror) {
  113026. this._groundMirror.dispose();
  113027. this._groundMirror = null;
  113028. }
  113029. if (this._scene.environmentTexture) {
  113030. if (this._options.environmentTexture != newOptions.environmentTexture) {
  113031. this._scene.environmentTexture.dispose();
  113032. }
  113033. }
  113034. this._options = newOptions;
  113035. this._setupBackground();
  113036. this._setupImageProcessing();
  113037. };
  113038. /**
  113039. * Sets the primary color of all the available elements.
  113040. * @param color the main color to affect to the ground and the background
  113041. */
  113042. EnvironmentHelper.prototype.setMainColor = function (color) {
  113043. if (this.groundMaterial) {
  113044. this.groundMaterial.primaryColor = color;
  113045. }
  113046. if (this.skyboxMaterial) {
  113047. this.skyboxMaterial.primaryColor = color;
  113048. }
  113049. if (this.groundMirror) {
  113050. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  113051. }
  113052. };
  113053. /**
  113054. * Setup the image processing according to the specified options.
  113055. */
  113056. EnvironmentHelper.prototype._setupImageProcessing = function () {
  113057. if (this._options.setupImageProcessing) {
  113058. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  113059. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  113060. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  113061. this._setupEnvironmentTexture();
  113062. }
  113063. };
  113064. /**
  113065. * Setup the environment texture according to the specified options.
  113066. */
  113067. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  113068. if (this._scene.environmentTexture) {
  113069. return;
  113070. }
  113071. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  113072. this._scene.environmentTexture = this._options.environmentTexture;
  113073. return;
  113074. }
  113075. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  113076. this._scene.environmentTexture = environmentTexture;
  113077. };
  113078. /**
  113079. * Setup the background according to the specified options.
  113080. */
  113081. EnvironmentHelper.prototype._setupBackground = function () {
  113082. if (!this._rootMesh) {
  113083. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  113084. }
  113085. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  113086. var sceneSize = this._getSceneSize();
  113087. if (this._options.createGround) {
  113088. this._setupGround(sceneSize);
  113089. this._setupGroundMaterial();
  113090. this._setupGroundDiffuseTexture();
  113091. if (this._options.enableGroundMirror) {
  113092. this._setupGroundMirrorTexture(sceneSize);
  113093. }
  113094. this._setupMirrorInGroundMaterial();
  113095. }
  113096. if (this._options.createSkybox) {
  113097. this._setupSkybox(sceneSize);
  113098. this._setupSkyboxMaterial();
  113099. this._setupSkyboxReflectionTexture();
  113100. }
  113101. this._rootMesh.position.x = sceneSize.rootPosition.x;
  113102. this._rootMesh.position.z = sceneSize.rootPosition.z;
  113103. this._rootMesh.position.y = sceneSize.rootPosition.y;
  113104. };
  113105. /**
  113106. * Get the scene sizes according to the setup.
  113107. */
  113108. EnvironmentHelper.prototype._getSceneSize = function () {
  113109. var _this = this;
  113110. var groundSize = this._options.groundSize;
  113111. var skyboxSize = this._options.skyboxSize;
  113112. var rootPosition = this._options.rootPosition;
  113113. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  113114. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  113115. }
  113116. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  113117. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  113118. });
  113119. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  113120. if (this._options.sizeAuto) {
  113121. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  113122. this._scene.activeCamera.upperRadiusLimit) {
  113123. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  113124. skyboxSize = groundSize;
  113125. }
  113126. var sceneDiagonalLenght = sceneDiagonal.length();
  113127. if (sceneDiagonalLenght > groundSize) {
  113128. groundSize = sceneDiagonalLenght * 2;
  113129. skyboxSize = groundSize;
  113130. }
  113131. // 10 % bigger.
  113132. groundSize *= 1.1;
  113133. skyboxSize *= 1.5;
  113134. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  113135. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  113136. }
  113137. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  113138. };
  113139. /**
  113140. * Setup the ground according to the specified options.
  113141. */
  113142. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  113143. var _this = this;
  113144. if (!this._ground || this._ground.isDisposed()) {
  113145. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  113146. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  113147. this._ground.parent = this._rootMesh;
  113148. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  113149. }
  113150. this._ground.receiveShadows = this._options.enableGroundShadow;
  113151. };
  113152. /**
  113153. * Setup the ground material according to the specified options.
  113154. */
  113155. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  113156. if (!this._groundMaterial) {
  113157. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  113158. }
  113159. this._groundMaterial.alpha = this._options.groundOpacity;
  113160. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  113161. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  113162. this._groundMaterial.primaryColor = this._options.groundColor;
  113163. this._groundMaterial.useRGBColor = false;
  113164. this._groundMaterial.enableNoise = true;
  113165. if (this._ground) {
  113166. this._ground.material = this._groundMaterial;
  113167. }
  113168. };
  113169. /**
  113170. * Setup the ground diffuse texture according to the specified options.
  113171. */
  113172. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  113173. if (!this._groundMaterial) {
  113174. return;
  113175. }
  113176. if (this._groundTexture) {
  113177. return;
  113178. }
  113179. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  113180. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  113181. return;
  113182. }
  113183. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  113184. diffuseTexture.gammaSpace = false;
  113185. diffuseTexture.hasAlpha = true;
  113186. this._groundMaterial.diffuseTexture = diffuseTexture;
  113187. };
  113188. /**
  113189. * Setup the ground mirror texture according to the specified options.
  113190. */
  113191. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  113192. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113193. if (!this._groundMirror) {
  113194. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  113195. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  113196. this._groundMirror.anisotropicFilteringLevel = 1;
  113197. this._groundMirror.wrapU = wrapping;
  113198. this._groundMirror.wrapV = wrapping;
  113199. this._groundMirror.gammaSpace = false;
  113200. if (this._groundMirror.renderList) {
  113201. for (var i = 0; i < this._scene.meshes.length; i++) {
  113202. var mesh = this._scene.meshes[i];
  113203. if (mesh !== this._ground &&
  113204. mesh !== this._skybox &&
  113205. mesh !== this._rootMesh) {
  113206. this._groundMirror.renderList.push(mesh);
  113207. }
  113208. }
  113209. }
  113210. }
  113211. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  113212. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  113213. };
  113214. /**
  113215. * Setup the ground to receive the mirror texture.
  113216. */
  113217. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  113218. if (this._groundMaterial) {
  113219. this._groundMaterial.reflectionTexture = this._groundMirror;
  113220. this._groundMaterial.reflectionFresnel = true;
  113221. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  113222. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  113223. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  113224. }
  113225. };
  113226. /**
  113227. * Setup the skybox according to the specified options.
  113228. */
  113229. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  113230. var _this = this;
  113231. if (!this._skybox || this._skybox.isDisposed()) {
  113232. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  113233. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  113234. }
  113235. this._skybox.parent = this._rootMesh;
  113236. };
  113237. /**
  113238. * Setup the skybox material according to the specified options.
  113239. */
  113240. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  113241. if (!this._skybox) {
  113242. return;
  113243. }
  113244. if (!this._skyboxMaterial) {
  113245. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  113246. }
  113247. this._skyboxMaterial.useRGBColor = false;
  113248. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  113249. this._skyboxMaterial.enableNoise = true;
  113250. this._skybox.material = this._skyboxMaterial;
  113251. };
  113252. /**
  113253. * Setup the skybox reflection texture according to the specified options.
  113254. */
  113255. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  113256. if (!this._skyboxMaterial) {
  113257. return;
  113258. }
  113259. if (this._skyboxTexture) {
  113260. return;
  113261. }
  113262. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  113263. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  113264. return;
  113265. }
  113266. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  113267. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  113268. this._skyboxTexture.gammaSpace = false;
  113269. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  113270. };
  113271. /**
  113272. * Dispose all the elements created by the Helper.
  113273. */
  113274. EnvironmentHelper.prototype.dispose = function () {
  113275. if (this._groundMaterial) {
  113276. this._groundMaterial.dispose(true, true);
  113277. }
  113278. if (this._skyboxMaterial) {
  113279. this._skyboxMaterial.dispose(true, true);
  113280. }
  113281. this._rootMesh.dispose(false);
  113282. };
  113283. /**
  113284. * Default ground texture URL.
  113285. */
  113286. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  113287. /**
  113288. * Default skybox texture URL.
  113289. */
  113290. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  113291. /**
  113292. * Default environment texture URL.
  113293. */
  113294. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  113295. return EnvironmentHelper;
  113296. }());
  113297. BABYLON.EnvironmentHelper = EnvironmentHelper;
  113298. })(BABYLON || (BABYLON = {}));
  113299. //# sourceMappingURL=babylon.environmentHelper.js.map
  113300. var BABYLON;
  113301. (function (BABYLON) {
  113302. /** Internal class used to store shapes for emitters */
  113303. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  113304. function ParticleSystemSetEmitterCreationOptions() {
  113305. }
  113306. return ParticleSystemSetEmitterCreationOptions;
  113307. }());
  113308. /**
  113309. * Represents a set of particle systems working together to create a specific effect
  113310. */
  113311. var ParticleSystemSet = /** @class */ (function () {
  113312. function ParticleSystemSet() {
  113313. /**
  113314. * Gets the particle system list
  113315. */
  113316. this.systems = new Array();
  113317. }
  113318. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  113319. /**
  113320. * Gets the emitter node used with this set
  113321. */
  113322. get: function () {
  113323. return this._emitterNode;
  113324. },
  113325. enumerable: true,
  113326. configurable: true
  113327. });
  113328. /**
  113329. * Creates a new emitter mesh as a sphere
  113330. * @param options defines the options used to create the sphere
  113331. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  113332. * @param scene defines the hosting scene
  113333. */
  113334. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  113335. if (this._emitterNode) {
  113336. this._emitterNode.dispose();
  113337. }
  113338. this._emitterCreationOptions = {
  113339. kind: "Sphere",
  113340. options: options,
  113341. renderingGroupId: renderingGroupId
  113342. };
  113343. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  113344. emitterMesh.renderingGroupId = renderingGroupId;
  113345. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  113346. material.emissiveColor = options.color;
  113347. emitterMesh.material = material;
  113348. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113349. var system = _a[_i];
  113350. system.emitter = emitterMesh;
  113351. }
  113352. this._emitterNode = emitterMesh;
  113353. };
  113354. /**
  113355. * Starts all particle systems of the set
  113356. * @param emitter defines an optional mesh to use as emitter for the particle systems
  113357. */
  113358. ParticleSystemSet.prototype.start = function (emitter) {
  113359. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113360. var system = _a[_i];
  113361. if (emitter) {
  113362. system.emitter = emitter;
  113363. }
  113364. system.start();
  113365. }
  113366. };
  113367. /**
  113368. * Release all associated resources
  113369. */
  113370. ParticleSystemSet.prototype.dispose = function () {
  113371. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113372. var system = _a[_i];
  113373. system.dispose();
  113374. }
  113375. this.systems = [];
  113376. if (this._emitterNode) {
  113377. this._emitterNode.dispose();
  113378. this._emitterNode = null;
  113379. }
  113380. };
  113381. /**
  113382. * Serialize the set into a JSON compatible object
  113383. * @returns a JSON compatible representation of the set
  113384. */
  113385. ParticleSystemSet.prototype.serialize = function () {
  113386. var result = {};
  113387. result.systems = [];
  113388. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113389. var system = _a[_i];
  113390. result.systems.push(system.serialize());
  113391. }
  113392. if (this._emitterNode) {
  113393. result.emitter = this._emitterCreationOptions;
  113394. }
  113395. return result;
  113396. };
  113397. /**
  113398. * Parse a new ParticleSystemSet from a serialized source
  113399. * @param data defines a JSON compatible representation of the set
  113400. * @param scene defines the hosting scene
  113401. * @param gpu defines if we want GPU particles or CPU particles
  113402. * @returns a new ParticleSystemSet
  113403. */
  113404. ParticleSystemSet.Parse = function (data, scene, gpu) {
  113405. if (gpu === void 0) { gpu = false; }
  113406. var result = new ParticleSystemSet();
  113407. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  113408. scene = scene || BABYLON.Engine.LastCreatedScene;
  113409. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  113410. var system = _a[_i];
  113411. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  113412. }
  113413. if (data.emitter) {
  113414. var options = data.emitter.options;
  113415. switch (data.emitter.kind) {
  113416. case "Sphere":
  113417. result.setEmitterAsSphere({
  113418. diameter: options.diameter,
  113419. segments: options.segments,
  113420. color: BABYLON.Color3.FromArray(options.color)
  113421. }, data.emitter.renderingGroupId, scene);
  113422. break;
  113423. }
  113424. }
  113425. return result;
  113426. };
  113427. return ParticleSystemSet;
  113428. }());
  113429. BABYLON.ParticleSystemSet = ParticleSystemSet;
  113430. })(BABYLON || (BABYLON = {}));
  113431. //# sourceMappingURL=babylon.particleSystemSet.js.map
  113432. var BABYLON;
  113433. (function (BABYLON) {
  113434. /**
  113435. * This class is made for on one-liner static method to help creating particle system set.
  113436. */
  113437. var ParticleHelper = /** @class */ (function () {
  113438. function ParticleHelper() {
  113439. }
  113440. /**
  113441. * Create a default particle system that you can tweak
  113442. * @param emitter defines the emitter to use
  113443. * @param capacity defines the system capacity (default is 500 particles)
  113444. * @param scene defines the hosting scene
  113445. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  113446. * @returns the new Particle system
  113447. */
  113448. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  113449. if (capacity === void 0) { capacity = 500; }
  113450. if (useGPU === void 0) { useGPU = false; }
  113451. var system;
  113452. if (useGPU) {
  113453. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  113454. }
  113455. else {
  113456. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  113457. }
  113458. system.emitter = emitter;
  113459. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  113460. system.createConeEmitter(0.1, Math.PI / 4);
  113461. // Particle color
  113462. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  113463. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  113464. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  113465. // Particle Size
  113466. system.minSize = 0.1;
  113467. system.maxSize = 0.1;
  113468. // Emission speed
  113469. system.minEmitPower = 2;
  113470. system.maxEmitPower = 2;
  113471. // Update speed
  113472. system.updateSpeed = 1 / 60;
  113473. system.emitRate = 30;
  113474. return system;
  113475. };
  113476. /**
  113477. * This is the main static method (one-liner) of this helper to create different particle systems
  113478. * @param type This string represents the type to the particle system to create
  113479. * @param scene The scene where the particle system should live
  113480. * @param gpu If the system will use gpu
  113481. * @returns the ParticleSystemSet created
  113482. */
  113483. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  113484. if (gpu === void 0) { gpu = false; }
  113485. if (!scene) {
  113486. scene = BABYLON.Engine.LastCreatedScene;
  113487. ;
  113488. }
  113489. var token = {};
  113490. scene._addPendingData(token);
  113491. return new Promise(function (resolve, reject) {
  113492. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  113493. scene._removePendingData(token);
  113494. return reject("Particle system with GPU is not supported.");
  113495. }
  113496. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  113497. scene._removePendingData(token);
  113498. var newData = JSON.parse(data.toString());
  113499. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  113500. }, undefined, undefined, undefined, function (req, exception) {
  113501. scene._removePendingData(token);
  113502. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  113503. });
  113504. });
  113505. };
  113506. /**
  113507. * Static function used to export a particle system to a ParticleSystemSet variable.
  113508. * Please note that the emitter shape is not exported
  113509. * @param system defines the particle systems to export
  113510. */
  113511. ParticleHelper.ExportSet = function (systems) {
  113512. var set = new BABYLON.ParticleSystemSet();
  113513. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  113514. var system = systems_1[_i];
  113515. set.systems.push(system);
  113516. }
  113517. return set;
  113518. };
  113519. /**
  113520. * Gets or sets base Assets URL
  113521. */
  113522. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  113523. return ParticleHelper;
  113524. }());
  113525. BABYLON.ParticleHelper = ParticleHelper;
  113526. })(BABYLON || (BABYLON = {}));
  113527. //# sourceMappingURL=babylon.particleHelper.js.map
  113528. var BABYLON;
  113529. (function (BABYLON) {
  113530. /**
  113531. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  113532. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  113533. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  113534. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  113535. */
  113536. var VideoDome = /** @class */ (function (_super) {
  113537. __extends(VideoDome, _super);
  113538. /**
  113539. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  113540. * @param name Element's name, child elements will append suffixes for their own names.
  113541. * @param urlsOrVideo defines the url(s) or the video element to use
  113542. * @param options An object containing optional or exposed sub element properties
  113543. */
  113544. function VideoDome(name, urlsOrVideo, options, scene) {
  113545. var _this = _super.call(this, name, scene) || this;
  113546. _this._useDirectMapping = false;
  113547. // set defaults and manage values
  113548. name = name || "videoDome";
  113549. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  113550. options.clickToPlay = Boolean(options.clickToPlay);
  113551. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  113552. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  113553. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  113554. if (options.useDirectMapping === undefined) {
  113555. _this._useDirectMapping = true;
  113556. }
  113557. else {
  113558. _this._useDirectMapping = options.useDirectMapping;
  113559. }
  113560. _this._setReady(false);
  113561. // create
  113562. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  113563. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  113564. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  113565. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  113566. texture.onLoadObservable.addOnce(function () {
  113567. _this._setReady(true);
  113568. });
  113569. // configure material
  113570. material.useEquirectangularFOV = true;
  113571. material.fovMultiplier = 1.0;
  113572. material.opacityFresnel = false;
  113573. if (_this._useDirectMapping) {
  113574. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113575. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113576. material.diffuseTexture = texture;
  113577. }
  113578. else {
  113579. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  113580. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113581. material.reflectionTexture = texture;
  113582. }
  113583. // configure mesh
  113584. _this._mesh.material = material;
  113585. _this._mesh.parent = _this;
  113586. // optional configuration
  113587. if (options.clickToPlay) {
  113588. scene.onPointerUp = function () {
  113589. _this._videoTexture.video.play();
  113590. };
  113591. }
  113592. return _this;
  113593. }
  113594. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  113595. /**
  113596. * Gets the video texture being displayed on the sphere
  113597. */
  113598. get: function () {
  113599. return this._videoTexture;
  113600. },
  113601. enumerable: true,
  113602. configurable: true
  113603. });
  113604. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  113605. /**
  113606. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  113607. * Also see the options.resolution property.
  113608. */
  113609. get: function () {
  113610. return this._material.fovMultiplier;
  113611. },
  113612. set: function (value) {
  113613. this._material.fovMultiplier = value;
  113614. },
  113615. enumerable: true,
  113616. configurable: true
  113617. });
  113618. /**
  113619. * Releases resources associated with this node.
  113620. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  113621. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  113622. */
  113623. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  113624. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  113625. this._videoTexture.dispose();
  113626. this._mesh.dispose();
  113627. this._material.dispose();
  113628. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  113629. };
  113630. return VideoDome;
  113631. }(BABYLON.TransformNode));
  113632. BABYLON.VideoDome = VideoDome;
  113633. })(BABYLON || (BABYLON = {}));
  113634. //# sourceMappingURL=babylon.videoDome.js.map
  113635. var BABYLON;
  113636. (function (BABYLON) {
  113637. /**
  113638. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  113639. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  113640. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  113641. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  113642. */
  113643. var PhotoDome = /** @class */ (function (_super) {
  113644. __extends(PhotoDome, _super);
  113645. /**
  113646. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  113647. * @param name Element's name, child elements will append suffixes for their own names.
  113648. * @param urlsOfPhoto defines the url of the photo to display
  113649. * @param options defines an object containing optional or exposed sub element properties
  113650. * @param onError defines a callback called when an error occured while loading the texture
  113651. */
  113652. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  113653. if (onError === void 0) { onError = null; }
  113654. var _this = _super.call(this, name, scene) || this;
  113655. _this._useDirectMapping = false;
  113656. /**
  113657. * Observable raised when an error occured while loading the 360 image
  113658. */
  113659. _this.onLoadErrorObservable = new BABYLON.Observable();
  113660. // set defaults and manage values
  113661. name = name || "photoDome";
  113662. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  113663. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  113664. if (options.useDirectMapping === undefined) {
  113665. _this._useDirectMapping = true;
  113666. }
  113667. else {
  113668. _this._useDirectMapping = options.useDirectMapping;
  113669. }
  113670. _this._setReady(false);
  113671. // create
  113672. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  113673. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  113674. // configure material
  113675. material.opacityFresnel = false;
  113676. material.useEquirectangularFOV = true;
  113677. material.fovMultiplier = 1.0;
  113678. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  113679. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  113680. if (onError) {
  113681. onError(message, exception);
  113682. }
  113683. });
  113684. _this.photoTexture.onLoadObservable.addOnce(function () {
  113685. _this._setReady(true);
  113686. });
  113687. // configure mesh
  113688. _this._mesh.material = material;
  113689. _this._mesh.parent = _this;
  113690. return _this;
  113691. }
  113692. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  113693. /**
  113694. * Gets or sets the texture being displayed on the sphere
  113695. */
  113696. get: function () {
  113697. return this._photoTexture;
  113698. },
  113699. set: function (value) {
  113700. if (this._photoTexture === value) {
  113701. return;
  113702. }
  113703. this._photoTexture = value;
  113704. if (this._useDirectMapping) {
  113705. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113706. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113707. this._material.diffuseTexture = this._photoTexture;
  113708. }
  113709. else {
  113710. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  113711. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113712. this._material.reflectionTexture = this._photoTexture;
  113713. }
  113714. },
  113715. enumerable: true,
  113716. configurable: true
  113717. });
  113718. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  113719. /**
  113720. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  113721. * Also see the options.resolution property.
  113722. */
  113723. get: function () {
  113724. return this._material.fovMultiplier;
  113725. },
  113726. set: function (value) {
  113727. this._material.fovMultiplier = value;
  113728. },
  113729. enumerable: true,
  113730. configurable: true
  113731. });
  113732. /**
  113733. * Releases resources associated with this node.
  113734. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  113735. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  113736. */
  113737. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  113738. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  113739. this._photoTexture.dispose();
  113740. this._mesh.dispose();
  113741. this._material.dispose();
  113742. this.onLoadErrorObservable.clear();
  113743. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  113744. };
  113745. return PhotoDome;
  113746. }(BABYLON.TransformNode));
  113747. BABYLON.PhotoDome = PhotoDome;
  113748. })(BABYLON || (BABYLON = {}));
  113749. //# sourceMappingURL=babylon.photoDome.js.map
  113750. var BABYLON;
  113751. (function (BABYLON) {
  113752. /** @hidden */
  113753. var _OcclusionDataStorage = /** @class */ (function () {
  113754. function _OcclusionDataStorage() {
  113755. /** @hidden */
  113756. this.occlusionInternalRetryCounter = 0;
  113757. /** @hidden */
  113758. this.isOcclusionQueryInProgress = false;
  113759. /** @hidden */
  113760. this.isOccluded = false;
  113761. /** @hidden */
  113762. this.occlusionRetryCount = -1;
  113763. /** @hidden */
  113764. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  113765. /** @hidden */
  113766. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  113767. }
  113768. return _OcclusionDataStorage;
  113769. }());
  113770. BABYLON.Engine.prototype.createQuery = function () {
  113771. return this._gl.createQuery();
  113772. };
  113773. BABYLON.Engine.prototype.deleteQuery = function (query) {
  113774. this._gl.deleteQuery(query);
  113775. return this;
  113776. };
  113777. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  113778. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  113779. };
  113780. BABYLON.Engine.prototype.getQueryResult = function (query) {
  113781. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  113782. };
  113783. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  113784. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  113785. this._gl.beginQuery(glAlgorithm, query);
  113786. return this;
  113787. };
  113788. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  113789. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  113790. this._gl.endQuery(glAlgorithm);
  113791. return this;
  113792. };
  113793. BABYLON.Engine.prototype._createTimeQuery = function () {
  113794. var timerQuery = this.getCaps().timerQuery;
  113795. if (timerQuery.createQueryEXT) {
  113796. return timerQuery.createQueryEXT();
  113797. }
  113798. return this.createQuery();
  113799. };
  113800. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  113801. var timerQuery = this.getCaps().timerQuery;
  113802. if (timerQuery.deleteQueryEXT) {
  113803. timerQuery.deleteQueryEXT(query);
  113804. return;
  113805. }
  113806. this.deleteQuery(query);
  113807. };
  113808. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  113809. var timerQuery = this.getCaps().timerQuery;
  113810. if (timerQuery.getQueryObjectEXT) {
  113811. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  113812. }
  113813. return this.getQueryResult(query);
  113814. };
  113815. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  113816. var timerQuery = this.getCaps().timerQuery;
  113817. if (timerQuery.getQueryObjectEXT) {
  113818. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  113819. }
  113820. return this.isQueryResultAvailable(query);
  113821. };
  113822. BABYLON.Engine.prototype.startTimeQuery = function () {
  113823. var caps = this.getCaps();
  113824. var timerQuery = caps.timerQuery;
  113825. if (!timerQuery) {
  113826. return null;
  113827. }
  113828. var token = new BABYLON._TimeToken();
  113829. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113830. if (caps.canUseTimestampForTimerQuery) {
  113831. token._startTimeQuery = this._createTimeQuery();
  113832. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  113833. }
  113834. else {
  113835. if (this._currentNonTimestampToken) {
  113836. return this._currentNonTimestampToken;
  113837. }
  113838. token._timeElapsedQuery = this._createTimeQuery();
  113839. if (timerQuery.beginQueryEXT) {
  113840. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113841. }
  113842. else {
  113843. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113844. }
  113845. this._currentNonTimestampToken = token;
  113846. }
  113847. return token;
  113848. };
  113849. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  113850. var caps = this.getCaps();
  113851. var timerQuery = caps.timerQuery;
  113852. if (!timerQuery || !token) {
  113853. return -1;
  113854. }
  113855. if (caps.canUseTimestampForTimerQuery) {
  113856. if (!token._startTimeQuery) {
  113857. return -1;
  113858. }
  113859. if (!token._endTimeQuery) {
  113860. token._endTimeQuery = this._createTimeQuery();
  113861. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  113862. }
  113863. }
  113864. else if (!token._timeElapsedQueryEnded) {
  113865. if (!token._timeElapsedQuery) {
  113866. return -1;
  113867. }
  113868. if (timerQuery.endQueryEXT) {
  113869. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  113870. }
  113871. else {
  113872. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  113873. }
  113874. token._timeElapsedQueryEnded = true;
  113875. }
  113876. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113877. var available = false;
  113878. if (token._endTimeQuery) {
  113879. available = this._getTimeQueryAvailability(token._endTimeQuery);
  113880. }
  113881. else if (token._timeElapsedQuery) {
  113882. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  113883. }
  113884. if (available && !disjoint) {
  113885. var result = 0;
  113886. if (caps.canUseTimestampForTimerQuery) {
  113887. if (!token._startTimeQuery || !token._endTimeQuery) {
  113888. return -1;
  113889. }
  113890. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  113891. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  113892. result = timeEnd - timeStart;
  113893. this._deleteTimeQuery(token._startTimeQuery);
  113894. this._deleteTimeQuery(token._endTimeQuery);
  113895. token._startTimeQuery = null;
  113896. token._endTimeQuery = null;
  113897. }
  113898. else {
  113899. if (!token._timeElapsedQuery) {
  113900. return -1;
  113901. }
  113902. result = this._getTimeQueryResult(token._timeElapsedQuery);
  113903. this._deleteTimeQuery(token._timeElapsedQuery);
  113904. token._timeElapsedQuery = null;
  113905. token._timeElapsedQueryEnded = false;
  113906. this._currentNonTimestampToken = null;
  113907. }
  113908. return result;
  113909. }
  113910. return -1;
  113911. };
  113912. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  113913. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  113914. };
  113915. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  113916. get: function () {
  113917. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  113918. },
  113919. enumerable: false,
  113920. configurable: true
  113921. });
  113922. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  113923. get: function () {
  113924. if (!this.__occlusionDataStorage) {
  113925. this.__occlusionDataStorage = new _OcclusionDataStorage();
  113926. }
  113927. return this.__occlusionDataStorage;
  113928. },
  113929. enumerable: false,
  113930. configurable: true
  113931. });
  113932. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  113933. get: function () {
  113934. return this._occlusionDataStorage.isOccluded;
  113935. },
  113936. set: function (value) {
  113937. this._occlusionDataStorage.isOccluded = value;
  113938. },
  113939. enumerable: true,
  113940. configurable: true
  113941. });
  113942. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  113943. get: function () {
  113944. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  113945. },
  113946. set: function (value) {
  113947. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  113948. },
  113949. enumerable: true,
  113950. configurable: true
  113951. });
  113952. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  113953. get: function () {
  113954. return this._occlusionDataStorage.occlusionType;
  113955. },
  113956. set: function (value) {
  113957. this._occlusionDataStorage.occlusionType = value;
  113958. },
  113959. enumerable: true,
  113960. configurable: true
  113961. });
  113962. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  113963. get: function () {
  113964. return this._occlusionDataStorage.occlusionRetryCount;
  113965. },
  113966. set: function (value) {
  113967. this._occlusionDataStorage.occlusionRetryCount = value;
  113968. },
  113969. enumerable: true,
  113970. configurable: true
  113971. });
  113972. // We also need to update AbstractMesh as there is a portion of the code there
  113973. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  113974. var dataStorage = this._occlusionDataStorage;
  113975. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  113976. dataStorage.isOccluded = false;
  113977. return false;
  113978. }
  113979. var engine = this.getEngine();
  113980. if (engine.webGLVersion < 2) {
  113981. dataStorage.isOccluded = false;
  113982. return false;
  113983. }
  113984. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  113985. dataStorage.isOccluded = false;
  113986. return false;
  113987. }
  113988. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  113989. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  113990. if (isOcclusionQueryAvailable) {
  113991. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  113992. dataStorage.isOcclusionQueryInProgress = false;
  113993. dataStorage.occlusionInternalRetryCounter = 0;
  113994. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  113995. }
  113996. else {
  113997. dataStorage.occlusionInternalRetryCounter++;
  113998. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  113999. dataStorage.isOcclusionQueryInProgress = false;
  114000. dataStorage.occlusionInternalRetryCounter = 0;
  114001. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  114002. // if strict continue the last state of the object.
  114003. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  114004. }
  114005. else {
  114006. return false;
  114007. }
  114008. }
  114009. }
  114010. var scene = this.getScene();
  114011. if (scene.getBoundingBoxRenderer) {
  114012. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  114013. if (!this._occlusionQuery) {
  114014. this._occlusionQuery = engine.createQuery();
  114015. }
  114016. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  114017. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  114018. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  114019. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  114020. }
  114021. return dataStorage.isOccluded;
  114022. };
  114023. })(BABYLON || (BABYLON = {}));
  114024. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  114025. var BABYLON;
  114026. (function (BABYLON) {
  114027. /**
  114028. * Class used to generate noise procedural textures
  114029. */
  114030. var NoiseProceduralTexture = /** @class */ (function (_super) {
  114031. __extends(NoiseProceduralTexture, _super);
  114032. /**
  114033. * Creates a new NoiseProceduralTexture
  114034. * @param name defines the name fo the texture
  114035. * @param size defines the size of the texture (default is 256)
  114036. * @param scene defines the hosting scene
  114037. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  114038. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  114039. */
  114040. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  114041. if (size === void 0) { size = 256; }
  114042. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  114043. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  114044. _this._time = 0;
  114045. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  114046. _this.brightness = 0.2;
  114047. /** Defines the number of octaves to process */
  114048. _this.octaves = 3;
  114049. /** Defines the level of persistence (0.8 by default) */
  114050. _this.persistence = 0.8;
  114051. /** Gets or sets animation speed factor (default is 1) */
  114052. _this.animationSpeedFactor = 1;
  114053. _this._updateShaderUniforms();
  114054. return _this;
  114055. }
  114056. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  114057. var scene = this.getScene();
  114058. if (!scene) {
  114059. return;
  114060. }
  114061. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  114062. this.setFloat("brightness", this.brightness);
  114063. this.setFloat("persistence", this.persistence);
  114064. this.setFloat("timeScale", this._time);
  114065. };
  114066. NoiseProceduralTexture.prototype._getDefines = function () {
  114067. return "#define OCTAVES " + (this.octaves | 0);
  114068. };
  114069. /** Generate the current state of the procedural texture */
  114070. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  114071. this._updateShaderUniforms();
  114072. _super.prototype.render.call(this, useCameraPostProcess);
  114073. };
  114074. /**
  114075. * Serializes this noise procedural texture
  114076. * @returns a serialized noise procedural texture object
  114077. */
  114078. NoiseProceduralTexture.prototype.serialize = function () {
  114079. var serializationObject = {};
  114080. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  114081. serializationObject.brightness = this.brightness;
  114082. serializationObject.octaves = this.octaves;
  114083. serializationObject.persistence = this.persistence;
  114084. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  114085. serializationObject.size = this.getSize().width;
  114086. serializationObject.generateMipMaps = this._generateMipMaps;
  114087. return serializationObject;
  114088. };
  114089. /**
  114090. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  114091. * @param parsedTexture defines parsed texture data
  114092. * @param scene defines the current scene
  114093. * @param rootUrl defines the root URL containing noise procedural texture information
  114094. * @returns a parsed NoiseProceduralTexture
  114095. */
  114096. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  114097. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  114098. texture.brightness = parsedTexture.brightness;
  114099. texture.octaves = parsedTexture.octaves;
  114100. texture.persistence = parsedTexture.persistence;
  114101. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  114102. return texture;
  114103. };
  114104. return NoiseProceduralTexture;
  114105. }(BABYLON.ProceduralTexture));
  114106. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  114107. })(BABYLON || (BABYLON = {}));
  114108. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  114109. var __assign = (this && this.__assign) || function () {
  114110. __assign = Object.assign || function(t) {
  114111. for (var s, i = 1, n = arguments.length; i < n; i++) {
  114112. s = arguments[i];
  114113. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  114114. t[p] = s[p];
  114115. }
  114116. return t;
  114117. };
  114118. return __assign.apply(this, arguments);
  114119. };
  114120. var BABYLON;
  114121. (function (BABYLON) {
  114122. /**
  114123. * This can helps recording videos from BabylonJS.
  114124. * This is based on the available WebRTC functionalities of the browser.
  114125. *
  114126. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  114127. */
  114128. var VideoRecorder = /** @class */ (function () {
  114129. /**
  114130. * Create a new VideoCapture object which can help converting what you see in Babylon to
  114131. * a video file.
  114132. * @param engine Defines the BabylonJS Engine you wish to record
  114133. * @param options Defines options that can be used to customized the capture
  114134. */
  114135. function VideoRecorder(engine, options) {
  114136. if (options === void 0) { options = null; }
  114137. if (!VideoRecorder.IsSupported(engine)) {
  114138. throw "Your browser does not support recording so far.";
  114139. }
  114140. var canvas = engine.getRenderingCanvas();
  114141. if (!canvas) {
  114142. throw "The babylon engine must have a canvas to be recorded";
  114143. }
  114144. this._canvas = canvas;
  114145. this._canvas.isRecording = false;
  114146. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  114147. var stream = this._canvas.captureStream(this._options.fps);
  114148. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  114149. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  114150. this._mediaRecorder.onerror = this._handleError.bind(this);
  114151. this._mediaRecorder.onstop = this._handleStop.bind(this);
  114152. }
  114153. /**
  114154. * Returns wehther or not the VideoRecorder is available in your browser.
  114155. * @param engine Defines the Babylon Engine to check the support for
  114156. * @returns true if supported otherwise false
  114157. */
  114158. VideoRecorder.IsSupported = function (engine) {
  114159. var canvas = engine.getRenderingCanvas();
  114160. return (!!canvas && typeof canvas.captureStream === "function");
  114161. };
  114162. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  114163. /**
  114164. * True wether a recording is already in progress.
  114165. */
  114166. get: function () {
  114167. return !!this._canvas && this._canvas.isRecording;
  114168. },
  114169. enumerable: true,
  114170. configurable: true
  114171. });
  114172. /**
  114173. * Stops the current recording before the default capture timeout passed in the startRecording
  114174. * functions.
  114175. */
  114176. VideoRecorder.prototype.stopRecording = function () {
  114177. if (!this._canvas || !this._mediaRecorder) {
  114178. return;
  114179. }
  114180. if (!this.isRecording) {
  114181. return;
  114182. }
  114183. this._canvas.isRecording = false;
  114184. this._mediaRecorder.stop();
  114185. };
  114186. /**
  114187. * Starts recording the canvas for a max duration specified in parameters.
  114188. * @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.
  114189. * @param maxDuration Defines the maximum recording time in seconds.
  114190. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  114191. * @return a promise callback at the end of the recording with the video data in Blob.
  114192. */
  114193. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  114194. var _this = this;
  114195. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  114196. if (maxDuration === void 0) { maxDuration = 7; }
  114197. if (!this._canvas || !this._mediaRecorder) {
  114198. throw "Recorder has already been disposed";
  114199. }
  114200. if (this.isRecording) {
  114201. throw "Recording already in progress";
  114202. }
  114203. if (maxDuration > 0) {
  114204. setTimeout(function () {
  114205. _this.stopRecording();
  114206. }, maxDuration * 1000);
  114207. }
  114208. this._fileName = fileName;
  114209. this._recordedChunks = [];
  114210. this._resolve = null;
  114211. this._reject = null;
  114212. this._canvas.isRecording = true;
  114213. this._mediaRecorder.start(this._options.recordChunckSize);
  114214. return new Promise(function (resolve, reject) {
  114215. _this._resolve = resolve;
  114216. _this._reject = reject;
  114217. });
  114218. };
  114219. /**
  114220. * Releases internal resources used during the recording.
  114221. */
  114222. VideoRecorder.prototype.dispose = function () {
  114223. this._canvas = null;
  114224. this._mediaRecorder = null;
  114225. this._recordedChunks = [];
  114226. this._fileName = null;
  114227. this._resolve = null;
  114228. this._reject = null;
  114229. };
  114230. VideoRecorder.prototype._handleDataAvailable = function (event) {
  114231. if (event.data.size > 0) {
  114232. this._recordedChunks.push(event.data);
  114233. }
  114234. };
  114235. VideoRecorder.prototype._handleError = function (event) {
  114236. this.stopRecording();
  114237. if (this._reject) {
  114238. this._reject(event.error);
  114239. }
  114240. else {
  114241. throw new event.error;
  114242. }
  114243. };
  114244. VideoRecorder.prototype._handleStop = function () {
  114245. this.stopRecording();
  114246. var superBuffer = new Blob(this._recordedChunks);
  114247. if (this._resolve) {
  114248. this._resolve(superBuffer);
  114249. }
  114250. window.URL.createObjectURL(superBuffer);
  114251. if (this._fileName) {
  114252. BABYLON.Tools.Download(superBuffer, this._fileName);
  114253. }
  114254. };
  114255. VideoRecorder._defaultOptions = {
  114256. mimeType: "video/webm",
  114257. fps: 25,
  114258. recordChunckSize: 3000
  114259. };
  114260. return VideoRecorder;
  114261. }());
  114262. BABYLON.VideoRecorder = VideoRecorder;
  114263. })(BABYLON || (BABYLON = {}));
  114264. //# sourceMappingURL=babylon.videoRecorder.js.map
  114265. var BABYLON;
  114266. (function (BABYLON) {
  114267. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  114268. if (replace === void 0) { replace = false; }
  114269. // Dispose existing light in replace mode.
  114270. if (replace) {
  114271. if (this.lights) {
  114272. for (var i = 0; i < this.lights.length; i++) {
  114273. this.lights[i].dispose();
  114274. }
  114275. }
  114276. }
  114277. // Light
  114278. if (this.lights.length === 0) {
  114279. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  114280. }
  114281. };
  114282. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  114283. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  114284. if (replace === void 0) { replace = false; }
  114285. if (attachCameraControls === void 0) { attachCameraControls = false; }
  114286. // Dispose existing camera in replace mode.
  114287. if (replace) {
  114288. if (this.activeCamera) {
  114289. this.activeCamera.dispose();
  114290. this.activeCamera = null;
  114291. }
  114292. }
  114293. // Camera
  114294. if (!this.activeCamera) {
  114295. var worldExtends = this.getWorldExtends();
  114296. var worldSize = worldExtends.max.subtract(worldExtends.min);
  114297. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  114298. var camera;
  114299. var radius = worldSize.length() * 1.5;
  114300. // empty scene scenario!
  114301. if (!isFinite(radius)) {
  114302. radius = 1;
  114303. worldCenter.copyFromFloats(0, 0, 0);
  114304. }
  114305. if (createArcRotateCamera) {
  114306. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  114307. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  114308. arcRotateCamera.wheelPrecision = 100 / radius;
  114309. camera = arcRotateCamera;
  114310. }
  114311. else {
  114312. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  114313. freeCamera.setTarget(worldCenter);
  114314. camera = freeCamera;
  114315. }
  114316. camera.minZ = radius * 0.01;
  114317. camera.maxZ = radius * 1000;
  114318. camera.speed = radius * 0.2;
  114319. this.activeCamera = camera;
  114320. var canvas = this.getEngine().getRenderingCanvas();
  114321. if (attachCameraControls && canvas) {
  114322. camera.attachControl(canvas);
  114323. }
  114324. }
  114325. };
  114326. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  114327. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  114328. if (replace === void 0) { replace = false; }
  114329. if (attachCameraControls === void 0) { attachCameraControls = false; }
  114330. this.createDefaultLight(replace);
  114331. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  114332. };
  114333. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  114334. if (pbr === void 0) { pbr = false; }
  114335. if (scale === void 0) { scale = 1000; }
  114336. if (blur === void 0) { blur = 0; }
  114337. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  114338. if (!environmentTexture) {
  114339. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  114340. return null;
  114341. }
  114342. if (setGlobalEnvTexture) {
  114343. if (environmentTexture) {
  114344. this.environmentTexture = environmentTexture;
  114345. }
  114346. }
  114347. // Skybox
  114348. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  114349. if (pbr) {
  114350. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  114351. hdrSkyboxMaterial.backFaceCulling = false;
  114352. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  114353. if (hdrSkyboxMaterial.reflectionTexture) {
  114354. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114355. }
  114356. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  114357. hdrSkyboxMaterial.disableLighting = true;
  114358. hdrSkyboxMaterial.twoSidedLighting = true;
  114359. hdrSkybox.infiniteDistance = true;
  114360. hdrSkybox.material = hdrSkyboxMaterial;
  114361. }
  114362. else {
  114363. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  114364. skyboxMaterial.backFaceCulling = false;
  114365. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  114366. if (skyboxMaterial.reflectionTexture) {
  114367. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114368. }
  114369. skyboxMaterial.disableLighting = true;
  114370. hdrSkybox.infiniteDistance = true;
  114371. hdrSkybox.material = skyboxMaterial;
  114372. }
  114373. return hdrSkybox;
  114374. };
  114375. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  114376. if (BABYLON.EnvironmentHelper) {
  114377. return new BABYLON.EnvironmentHelper(options, this);
  114378. }
  114379. return null;
  114380. };
  114381. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  114382. if (webVROptions === void 0) { webVROptions = {}; }
  114383. return new BABYLON.VRExperienceHelper(this, webVROptions);
  114384. };
  114385. })(BABYLON || (BABYLON = {}));
  114386. //# sourceMappingURL=babylon.sceneHelpers.js.map
  114387. 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(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  114388. 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};"};